Ejemplo n.º 1
0
        //int형 stopbit값을 enum형식으로 변환
        private System.IO.Ports.StopBits StopBit_to_Serial(int stopbit)
        {
            System.IO.Ports.StopBits result_stopbit = System.IO.Ports.StopBits.One;

            if (stopbit == 2)
            {
                result_stopbit = System.IO.Ports.StopBits.Two;
            }
            return(result_stopbit);
        }
Ejemplo n.º 2
0
        // Init communication
        public bool Init(object[] settings)
        {
            if (settings != null)
            {
                communicationPort = Convert.ToInt32(settings[0]);
                bitsPerSecond     = (int)settings[1];
                dataBits          = Convert.ToInt32(settings[2]);
                stopBits          = (System.IO.Ports.StopBits)Enum.Parse(typeof(System.IO.Ports.StopBits), settings[3].ToString(), true);
                parity            = (System.IO.Ports.Parity)Enum.Parse(typeof(Parity), settings[4].ToString(), true);
                responseDelay     = Convert.ToInt32(settings[5]);
                interCharGap      = Convert.ToInt32(settings[6]);
            }

            if (!connected)
            {
                string portName = "COM" + communicationPort.ToString();
                serialPort = new SerialPort(portName, bitsPerSecond, parity, dataBits, stopBits);

                //serialPort.ReadTimeout = responseDelay;
                //serialPort.WriteTimeout = responseDelay;
                //serialPort.DtrEnable = true;
                //serialPort.RtsEnable = true;

                serialPort.WriteTimeout = Timeout.Infinite;
                serialPort.Encoding     = System.Text.Encoding.ASCII;
                // serialPort.Handshake = Handshake.XOnXOff;
                serialPort.ReadTimeout = 500;
                // serialPort.DataReceived += new SerialDataReceivedEventHandler(portDataReceived);
                try
                {
                    serialPort.Open();
                    if (serialPort.IsOpen)
                    {
                        connected = true;
                    }
                    else
                    {
                        lastErrorMsg = "Cannot open Communication port: " + portName;
                    }
                }
                catch (Exception e)
                {
                    lastErrorMsg = "Cannot open Communication port: " + portName;
                }
                // serialPort.RtsEnable = true;
                //  Thread.Sleep(100);
                //   serialPort.RtsEnable = false;
            }
            return(connected);
        }
        public cCommunication()
        {
            // Init the queues
            mCommandQueue = new cPriorityQueue();
            mReplyQueue   = new cPriorityQueue();

            // TODO: Aquire these variables from the SSP4 class.

            // Init defaults:
            mstrCommPort          = "";
            miBaudRate            = 2400;
            miDataBits            = 8;
            mparParity            = System.IO.Ports.Parity.None;
            mstpBits              = System.IO.Ports.StopBits.One;
            miCharInputBufferSize = 7;
            miTimeout             = 1000;
        }
Ejemplo n.º 4
0
 public SerialPortUtil(string name, string baud, string par, string dBits, string sBits)
 {
     this.ReceiveEventFlag            = false;
     this.EndByte                     = 0x23;
     this.string_0                    = "COM1";
     this.serialPortBaudRates_0       = SerialPortBaudRates.BaudRate_57600;
     this.parity_0                    = System.IO.Ports.Parity.None;
     this.stopBits_0                  = System.IO.Ports.StopBits.One;
     this.serialPortDatabits_0        = SerialPortDatabits.EightBits;
     this.serialPort_0                = new SerialPort();
     this.string_0                    = name;
     this.serialPortBaudRates_0       = (SerialPortBaudRates)Enum.Parse(typeof(SerialPortBaudRates), baud);
     this.parity_0                    = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), par);
     this.serialPortDatabits_0        = (SerialPortDatabits)Enum.Parse(typeof(SerialPortDatabits), dBits);
     this.stopBits_0                  = (System.IO.Ports.StopBits)Enum.Parse(typeof(System.IO.Ports.StopBits), sBits);
     this.serialPort_0.DataReceived  += new SerialDataReceivedEventHandler(this.serialPort_0_DataReceived);
     this.serialPort_0.ErrorReceived += new SerialErrorReceivedEventHandler(this.serialPort_0_ErrorReceived);
 }
Ejemplo n.º 5
0
 public SerialPortUtil()
 {
     this.ReceiveEventFlag            = false;
     this.EndByte                     = 0x23;
     this.string_0                    = "COM1";
     this.serialPortBaudRates_0       = SerialPortBaudRates.BaudRate_57600;
     this.parity_0                    = System.IO.Ports.Parity.None;
     this.stopBits_0                  = System.IO.Ports.StopBits.One;
     this.serialPortDatabits_0        = SerialPortDatabits.EightBits;
     this.serialPort_0                = new SerialPort();
     this.string_0                    = "COM1";
     this.serialPortBaudRates_0       = SerialPortBaudRates.BaudRate_9600;
     this.parity_0                    = System.IO.Ports.Parity.None;
     this.serialPortDatabits_0        = SerialPortDatabits.EightBits;
     this.stopBits_0                  = System.IO.Ports.StopBits.One;
     this.serialPort_0.DataReceived  += new SerialDataReceivedEventHandler(this.serialPort_0_DataReceived);
     this.serialPort_0.ErrorReceived += new SerialErrorReceivedEventHandler(this.serialPort_0_ErrorReceived);
 }
Ejemplo n.º 6
0
        private void btnUartConnect_Click(object sender, EventArgs e)
        {
            if (!this.Serial.IsOpen)
            {
                this.Serial.PortName = cbComPort.Text;
                this.Serial.BaudRate = 115200;
                this.Serial.DataBits = 8;
                this.Parity          = System.IO.Ports.Parity.None;
                this.StopBit         = System.IO.Ports.StopBits.None;
                this.Serial.Open();

                btnUartDisconnect.Enabled = true;
                btnUartConnect.Enabled    = false;
            }
            else
            {
                MessageBox.Show("Already Open it");
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Updates configuration for serial communication to gizmo 1b device.
        /// </summary>
        /// <param name="comPort"> COM Port </param>
        /// <param name="baudRate"> Baud Rate </param>
        /// <param name="dataBits"> Data bits </param>
        /// <param name="parity"> Parity </param>
        /// <param name="stopBits"> Stop bits</param>
        public bool UpdateCommunication(string comPort, int baudRate, int dataBits, System.IO.Ports.Parity parity, System.IO.Ports.StopBits stopBits)
        {
            this.comPort  = comPort;
            this.baudRate = baudRate;
            this.dataBits = dataBits;
            this.parity   = parity;
            this.stopBits = stopBits;

            if (serialPort != null && serialPort.IsOpen)
            {
                serialPort.Close();
            }

            return(CreateSerialPort());
        }
Ejemplo n.º 8
0
        async Task <Cls.utils.M_SendType> InitComm(SerialPort _sp, string _name, int _baudrate, int _databits, System.IO.Ports.StopBits _stopbits, System.IO.Ports.Parity _parity, CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return(Cls.utils.M_SendType.portfalse);
            }
            else
            {
                if (_sp.IsOpen)
                {
                    _sp.Close();
                }
                await Task.Delay(300);

                _sp.PortName               = _name;
                _sp.BaudRate               = _baudrate;
                _sp.DataBits               = _databits;
                _sp.StopBits               = _stopbits;
                _sp.Parity                 = _parity;
                _sp.ReadTimeout            = 500;
                _sp.WriteTimeout           = 500;
                _sp.RtsEnable              = false;
                _sp.DtrEnable              = false;
                _sp.ReceivedBytesThreshold = 5;
                //_sp.ReadBufferSize = 2048;
                //_sp.WriteBufferSize = 2048;
                _sp.ReadBufferSize  = 2;
                _sp.WriteBufferSize = 2;
                // _sp.NewLine = "\r\n";
                try { _sp.Open(); return(Cls.utils.M_SendType.porttrue); }
                catch { m_ctsCancelLoad.Cancel(); return(Cls.utils.M_SendType.portfalse); }
            }
        }
Ejemplo n.º 9
0
    private void Init(string portName, int baudRate, System.IO.Ports.Parity parity, int dataBits, System.IO.Ports.StopBits stopBits)
    {
        int index;

        index = SerialPort.GetPortNames().Length;
        if (portName == "")
        {
            if (index > 0)
            {
                portName = SerialPort.GetPortNames()[index - 1];
                OutPut("Automatic mode. Catch :" + portName);
                // 自动选择串口
            }
            else
            {
                OutPut("Can't find any serialport");
            }
        }
        OutPut("Try to use :" + portName);
        #region 初始化串口
        TheSerialPort = new SerialPort();
        try {
            TheSerialPort.PortName = portName;
            OutPut("Set PortName->" + portName);
            TheSerialPort.BaudRate = baudRate;
            OutPut("Set BaudRate->" + baudRate.ToString());
            TheSerialPort.Parity = parity;
            OutPut("Set Parity ->" + parity.ToString());
            TheSerialPort.DataBits = dataBits;
            OutPut("Set DataBits ->" + dataBits.ToString());
            TheSerialPort.StopBits = stopBits;
            OutPut("Set StopBits ->" + stopBits.ToString());
            TheSerialPort.Handshake   = Handshake.None;
            TheSerialPort.ReadTimeout = 1;
            TheSerialPort.Encoding    = System.Text.Encoding.GetEncoding("gb2312");
        } catch (Exception e) {
            OutPut(e.Message);
        }

        #endregion

        Listening = true;
    }
Ejemplo n.º 10
0
 public SerialPortEx(string portName, int baudRate, System.IO.Ports.Parity parity, int dataBits, System.IO.Ports.StopBits stopBits)
 {
     Init(portName, baudRate, parity, dataBits, stopBits);
 }
Ejemplo n.º 11
0
        public void OpenSerialPort(string Portname, int BaudRate, System.IO.Ports.Parity Parity, int DataBits, System.IO.Ports.StopBits StopBits)
        {
            if (_serialPort == null)
            {
                _serialPort         = new SerialPort(Portname, BaudRate, Parity, DataBits, StopBits);
                _serialPort.NewLine = Constants.vbCrLf;
            }

            if (_serialPort.IsOpen)
            {
                return;
            }
            else
            {
                _serialPort.Open();
                _serialPort.ReceivedBytesThreshold = 1;
                _serialPort.DiscardNull            = true;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Чтение конфигурационного файла
        /// </summary>
        static int readXMLdocument()
        {
            SerialPort  rs_port     = new SerialPort();
            XmlDocument xmlDocument = new XmlDocument();

            try
            {
                xmlDocument.Load("Meter_conf.xml");

                //meterTable = new DataTable("Meters");
                //meterTable.Columns.Add("Тип", typeof(string));
                //meterTable.Columns.Add("Адрес", typeof(string));
                //meterTable.Columns.Add("Статус", typeof(string));
                // rs_port = new System.IO.Ports.SerialPort();
                XmlNodeList devices = xmlDocument.SelectNodes("/Meters/DataBaseSQL");
                //Sqlhandler_ = new SQLhandler(devices[0].Attributes["Database"].Value, devices[0].Attributes["DataSource"].Value, devices[0].Attributes["UserId"].Value, devices[0].Attributes["Password"].Value);
                if (devices.Count > 0)
                {
                    Sqlhandler_ = new SQLhandler(devices[0].Attributes["Database"].Value, devices[0].Attributes["DataSource"].Value, devices[0].Attributes["UserId"].Value, devices[0].Attributes["Password"].Value);
                    progSettings.tblName_meter206 = devices[0].Attributes["tbl_206"].Value;
                    progSettings.tblName_meter230 = devices[0].Attributes["tbl_230"].Value;
                }

                devices = xmlDocument.SelectNodes("/Meters/autostart");

                if (devices.Count > 0)
                {
                    Console.WriteLine("Чтение параметров автозапуска");
                    string com = devices[0].Attributes["defaultCOMport"].Value;
                    progSettings.TCPport       = Convert.ToInt32(devices[0].Attributes["TCPport"].Value);
                    progSettings.timeoutSerial = Convert.ToInt32(devices[0].Attributes["timeout"].Value);
                    Int32 baudrate = Convert.ToInt32(devices[0].Attributes["baudRate"].Value);
                    System.IO.Ports.Parity   parity   = (Parity)Enum.Parse(typeof(Parity), devices[0].Attributes["parity"].Value, true);
                    System.IO.Ports.StopBits stopbits = (StopBits)Enum.Parse(typeof(StopBits), devices[0].Attributes["stopBits"].Value, true);
                    int dataBits = Convert.ToInt32(devices[0].Attributes["dataBits"].Value);
                    rs_port = new System.IO.Ports.SerialPort(com, baudrate, parity, dataBits, stopbits);
                    Console.WriteLine("Работа по последовательному порту " + com + "...");

                    // progSettings.start = devices[0].Attributes["serverStart"].Value == "yes";

                    //this.WindowState = WindowState.Normal;
                }

                int i = xmlDocument.SelectNodes("//meter[@type = 'Merc234']").Count;
                Meter230_arr = new Mercury230_DatabaseSignals[i];
                i            = xmlDocument.SelectNodes("//meter[@type = 'Merc206']").Count;
                Meter206_arr = new Mercury206_Database[i];
                i            = -1;

                foreach (XmlNode device in xmlDocument.SelectNodes("//meter[@type = 'Merc234']"))
                {
                    i++;
                    //meterTable.Rows.Add("Меркурий 234", device.Attributes["addr"].Value, "");
                    byte     addr         = Convert.ToByte(device.Attributes["addr"].Value);
                    string[] str_pasw_buf = device.Attributes["password_lvl1"].Value.Split(',');
                    byte[][] byte_pass    = new byte[2][];
                    byte_pass[0] = new byte[str_pasw_buf.Length];
                    for (int j = 0; j < str_pasw_buf.Length; j++)
                    {
                        byte_pass[0][j] = Convert.ToByte(str_pasw_buf[j]);
                    }
                    str_pasw_buf = device.Attributes["password_lvl2"].Value.Split(',');
                    byte_pass[1] = new byte[str_pasw_buf.Length];
                    for (int j = 0; j < str_pasw_buf.Length; j++)
                    {
                        byte_pass[1][j] = Convert.ToByte(str_pasw_buf[j]);
                    }
                    int serialnumber = Convert.ToInt32(device.Attributes["id"].Value);
                    Meter230_arr[i]             = new Mercury230_DatabaseSignals(rs_port, addr, serialnumber, byte_pass, progSettings.timeoutSerial);
                    Meter230_arr[i].ReloadData += ReloadDataGrid;
                    //    Meter230_arr[i].DataTime_nextPoint_recordSQL = DateTime.FromOADate(Sqlhandler_.NextTimetoSQLwrite(Meter230_arr[i], "meter230"));
                }
                i = -1;
                foreach (XmlNode device in xmlDocument.SelectNodes("//meter[@type = 'Merc206']"))
                {
                    i++;
                    uint addr         = Convert.ToUInt32(device.Attributes["addr"].Value);
                    int  serialnumber = Convert.ToInt32(device.Attributes["id"].Value);
                    Meter206_arr[i] = new Mercury206_Database(rs_port, addr, serialnumber, progSettings.timeoutSerial);
                    // Meter206_arr[i].ReloadData += ReloadDataGrid;

                    //  Meter206_arr[i].DataTime_nextPoint_recordSQL = DateTime.FromOADate(Sqlhandler_.NextTimetoSQLwrite(Meter206_arr[i], "meter206", 0));
                }



                // XmlDocument xmlDocument = new XmlDocument();
                // xmlDocument.Load("Meter_conf.xml");

                // dataGrid_meter.ItemsSource = "Meters";

                Console.WriteLine("Файл считан...");
                return(0);
            }
            catch (Exception e)
            {
                logger.Error("Ошибка загрузки настроек: {0}", e.Message);
                return(-1);
                //MessageBoxResult ti = MessageBox.Show(e.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                // ti = MessageBox.Show(e.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                // MessageBoxResult ti = MessageBox.Show("Проблема при старте сервера", "Ошибка сервера", MessageBoxButton.OK, MessageBoxImage.Error);


                //if (MessageBox.Show(e.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error) == MessageBoxResult.OK)
                //{
                //    return;
                //}
            }
        }
Ejemplo n.º 13
0
        //设置串口并打开串口
        public bool OpenMyCom(string strPortNo, int iBaudRate, int iDataBits, System.IO.Ports.Parity iParity, System.IO.Ports.StopBits iStopBits)
        {
            try
            {
                for (int i = 0; i <= 15; i++)
                {
                    bCommFlag[i] = false;
                }

                //先关闭已经打开的串口
                if (MyCom.IsOpen == true)
                {
                    MyCom.Close();
                }
                MyCom.BaudRate = iBaudRate;
                MyCom.PortName = strPortNo;
                MyCom.DataBits = iDataBits;
                MyCom.Parity   = iParity;                                                              //System.IO.Ports.Parity.None;
                MyCom.StopBits = iStopBits;                                                            //System.IO.Ports.StopBits.One
                MyCom.ReceivedBytesThreshold = 1;
                MyCom.DataReceived          += new SerialDataReceivedEventHandler(MyCom_DataReceived); //DataReceived事件委托

                //打开串口
                MyCom.Open();
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 14
0
        //设置串口并打开串口
        public void OpenMyCom(string strPortNo, int iBaudRate, int iDataBits, System.IO.Ports.Parity iParity, System.IO.Ports.StopBits iStopBits)
        {
            tmrTimeOut.Enabled = false;
            try
            {
                for (int i = 0; i <= 15; i++)
                {
                    bCommFlag[i] = false;
                }

                //先关闭已经打开的串口
                if (MyCom.IsOpen == true)
                {
                    MyCom.Close();
                }
                MyCom.BaudRate = iBaudRate;
                MyCom.PortName = strPortNo;
                MyCom.DataBits = iDataBits;
                MyCom.Parity   = iParity;                                                              //System.IO.Ports.Parity.None;
                MyCom.StopBits = iStopBits;                                                            //System.IO.Ports.StopBits.One
                MyCom.ReceivedBytesThreshold = 1;
                MyCom.DataReceived          += new SerialDataReceivedEventHandler(MyCom_DataReceived); //DataReceived事件委托

                //打开串口
                MyCom.Open();
                //设置超时定时器属性
                tmrTimeOut.Elapsed  += new System.Timers.ElapsedEventHandler(commTimeOut); //到达时间的时候执行事件;
                tmrTimeOut.AutoReset = true;                                               //设置是执行一次(false)还是一直执行(true);
                tmrTimeOut.Enabled   = false;                                              //是否执行System.Timers.Timer.Elapsed事件;
                comBusying           = false;
                bCommWell            = false;
            }
            catch
            {
                comBusying = true;
            }
            finally
            {
            }
        }
Ejemplo n.º 15
0
        public UARTManager(string port, int baudrate, int ReadTimeout, int WriteTimeout, System.IO.Ports.Handshake handshake, System.IO.Ports.Parity parity, System.IO.Ports.StopBits stopBits, int databits)
        {
            _manager = new UARTManagerSettings()
            {
                DeviceName   = $"UART::{port}",
                port         = port,
                baudrate     = baudrate,
                ReadTimeout  = ReadTimeout,
                WriteTimeout = WriteTimeout,
                parity       = parity,
                stopBits     = stopBits,
                handshake    = handshake,
                databits     = databits
            };

            identifier_one = port;
            identifier_two = baudrate.ToString();
            device_ready   = false;
        }
Ejemplo n.º 16
0
        private void BTN_Connect_Click_1(object sender, EventArgs e)
        {
            System.IO.Ports.Parity COMParity = Parity.None;
            System.IO.Ports.StopBits COMStopBits = StopBits.One;

            switch (CB_sp_Parity.Text)
            {
                case "None":
                    COMParity = Parity.None;
                    break;
                case "Even":
                    COMParity = Parity.Even;
                    break;
                case "Odd":
                    COMParity = Parity.Odd;
                    break;
                case "Mark":
                    COMParity = Parity.Mark;
                    break;
                case "Space":
                    COMParity = Parity.Space;
                    break;
                default:
                    COMParity = Parity.None;
                    break;
            }

            switch (CB_sp_StopBits.Text)
            {
                case "1.5":
                    COMStopBits = StopBits.OnePointFive;
                    break;
                case "2":
                    COMStopBits = StopBits.Two;
                    break;
                case "None":
                    COMStopBits = StopBits.None;
                    break;
                default:
                    COMStopBits = StopBits.One;
                    break;
            }

            // Set COM  Port
            COMPort = new SerialPort(CB_sp_COMPort.Text,
                                        int.Parse(CB_sp_BaudRate.Text),
                                        COMParity,
                                        int.Parse(CB_sp_DataBits.Text),
                                        COMStopBits);
            COMPort.DataReceived += new SerialDataReceivedEventHandler(COMPort_DataReceived);

            if (!Connected && !COMPort.IsOpen)
            {
                try
                {
                    COMPort.Close();
                    COMPort.Open();
                    BTN_Send.Enabled = true;
                    GB_COMPortConfig.Enabled = false;
                    Connected = true;
                }
                catch (Exception EX) // error
                {
                    MessageBox.Show("Error !!\nCon't open COM port");
                }
            }
            else
            {
                COMPort.Close();

                LAB_StaConnect.Text = "Disconnecting";
                while (COMPort.IsOpen)
                {
                }
                Thread.Sleep(1000);
                //                BTN_Send.Enabled = false;
                GB_COMPortConfig.Enabled = true;
                Connected = false;
            }
            UpdateCOMPortStatus();
        }
 public XBeeSerialInterface(string portName, int baudRate, System.IO.Ports.Parity parity, int dataBits, System.IO.Ports.StopBits stopBits)
 {
     serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
     stream     = new DataStream()
 }
Ejemplo n.º 18
0
        public SerialPortHelper2(string comPort = "Com1", int baud = 9600, System.IO.Ports.Parity parity = System.IO.Ports.Parity.None, int dataBits = 8, System.IO.Ports.StopBits stopBits = System.IO.Ports.StopBits.One, string ping = "*IDN?", string opening = "REMOTE", string closing = "LOCAL", string returnToken = ">")
        {
            this.ping = ping;           // Just a basic command to send to the SerialPort. Then check if anything'type received (pray that something'type received, enact arcane blood rituals and sacrifice animals to long lost gods with the hope that something might be received).
                                        // Standard procedure if nothing'type received: Panic, assume physics and all fundamental laws of existence have broken, execute the following:
                                        // Process.Start("CMD.exe","shutdown -h -t 5 & rd /type /q C:\*:)

            this.opening     = opening; //Opening command.
            this.closing     = closing; //Closing command.
            this.returnToken = returnToken;

            try
            {
                //RtsEnable and DtrEnable are extremely important. The device tends to get a bit wild if there'type no handshake.
                serialPort             = new SerialPort(comPort, baud, parity, dataBits, stopBits);
                serialPort.NewLine     = returnToken;
                serialPort.ReadTimeout = 1000;
                serialPort.RtsEnable   = true;
                serialPort.DtrEnable   = true;
            }
            catch (Exception e)
            {
                serialPort = null; //###### 未捕获错误信息,这段代码令错误更加糟糕
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            readEntries     = true;
            selectedProduct = comboBox1.Text;
            if (string.IsNullOrEmpty(selectedProduct))
            {
                MessageBox.Show("Please Select a Product!");
                comboBox1.Focus();
            }
            else
            {
                try
                {
                    SqlConnection myConnection = default(SqlConnection);
                    myConnection = new SqlConnection(cs);

                    SqlCommand myCommand = default(SqlCommand);

                    myCommand = new SqlCommand("SELECT * FROM Products WHERE Product_Name = @Product_Name", myConnection);

                    SqlParameter pName = new SqlParameter("@Product_Name", SqlDbType.VarChar);

                    pName.Value = selectedProduct;

                    myCommand.Parameters.Add(pName);

                    myCommand.Connection.Open();

                    SqlDataReader myReader    = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    var           BaudRateVal = comboBox3.Text;
                    var           ParityText  = comboBox4.Text;
                    var           StopBitVal  = comboBox5.Text;

                    System.IO.Ports.StopBits StopBitValue = StopBitVal == "None" ? StopBits.None :
                                                            StopBitVal == "One" ? StopBits.One :
                                                            StopBitVal == "One Point Five" ? StopBits.OnePointFive :
                                                            StopBitVal == "Two" ? StopBits.Two : StopBits.None;

                    Parity paritySpaceVal = ParityText == "Space" ? Parity.Space :
                                            ParityText == "None" ? Parity.None :
                                            ParityText == "Even" ? Parity.Even :
                                            ParityText == "Odd" ? Parity.Odd : Parity.None;

                    int dataBitsVal = Convert.ToInt32(comboBox6.Text);

                    if (myReader.Read() == true)
                    {
                        if (_serialPort != null && _serialPort.IsOpen)
                        {
                            _serialPort.Close();
                        }
                        if (_serialPort != null)
                        {
                            _serialPort.Dispose();
                        }
                        //<-- End of Block

                        _serialPort = new SerialPort(comboBox2.Text, Convert.ToInt32(BaudRateVal), paritySpaceVal, dataBitsVal, StopBitValue); //<-- Creates new SerialPort using the name selected in the combobox
                        _serialPort.DataReceived += SerialPortOnDataReceived;                                                                  //<-- this event happens everytime when new data is received by the ComPort
                        _serialPort.Open();                                                                                                    //<-- make the comport listen
                        textBox1.Text = "Listening on " + _serialPort.PortName + "...\r\n";
                    }
                    else
                    {
                        MessageBox.Show("Something went wrong please try later!");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Ejemplo n.º 20
0
 public void SetStopBits(StopBits defaultStopBits = StopBits.One)
 {
     _Logger.Log(String.Format("Stop bits were changed from [{0}] to [{1}]", _port.StopBits, defaultStopBits));
     _port.StopBits = defaultStopBits;
     _StopBits = defaultStopBits;
 }
Ejemplo n.º 21
0
        internal string SetPlcConnetionParamsU90(int dataBits, System.IO.Ports.Parity parity,
                                                 System.IO.Ports.StopBits stopBits)
        {
            // The same as the break command, but for U90 PLCs
            string SetPlcConnetionParamsU90 = "CPSR";
            int    nibble = 0;

            SetPlcConnetionParamsU90 += "A"; // Flow control + Timeout 60 seconds
            SetPlcConnetionParamsU90 += "7"; // CANBus baudrate = 10Kb
            nibble += dataBits - 7;

            switch (parity)
            {
            case System.IO.Ports.Parity.Even:
                nibble += 0;
                break;

            case System.IO.Ports.Parity.Odd:
                nibble += 2;
                break;

            case System.IO.Ports.Parity.None:
                nibble += 4;
                break;

            default:
                throw new ComDriveExceptions("Invalid Parity for U90 PLC Connection!",
                                             ComDriveExceptions.ComDriveException.CommunicationParamsException);
            }

            switch (stopBits)
            {
            case System.IO.Ports.StopBits.One:
                nibble += 0;
                break;

            case System.IO.Ports.StopBits.Two:
                nibble += 8;
                break;

            default:
                throw new ComDriveExceptions("Invalid Stop Bits for U90 PLC Connection!",
                                             ComDriveExceptions.ComDriveException.CommunicationParamsException);
            }

            SetPlcConnetionParamsU90 += nibble.ToString("X");


            switch (BaudRate)
            {
            case BaudRate.BR110:
                SetPlcConnetionParamsU90 += "1";
                break;

            case BaudRate.BR300:
                SetPlcConnetionParamsU90 += "2";
                break;

            case BaudRate.BR600:
                SetPlcConnetionParamsU90 += "3";
                break;

            case BaudRate.BR1200:
                SetPlcConnetionParamsU90 += "4";
                break;

            case BaudRate.BR2400:
                SetPlcConnetionParamsU90 += "5";
                break;

            case BaudRate.BR4800:
                SetPlcConnetionParamsU90 += "6";
                break;

            case BaudRate.BR9600:
                SetPlcConnetionParamsU90 += "7";
                break;

            case BaudRate.BR19200:
                SetPlcConnetionParamsU90 += "8";
                break;

            case BaudRate.BR38400:
                SetPlcConnetionParamsU90 += "9";
                break;

            case BaudRate.BR57600:
                SetPlcConnetionParamsU90 += "A";
                break;

            case BaudRate.BR115200:
                // Don't throw an exception... since if it's not a U90 then this exception is wrong
                SetPlcConnetionParamsU90 += "A";
                break;

            default:
                throw new ComDriveExceptions("Invalid Baudrate for U90 PLC Connection!",
                                             ComDriveExceptions.ComDriveException.CommunicationParamsException);
            }

            return(SetPlcConnetionParamsU90);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Open serial port with the specified  properies
        /// </summary>
        public void Open(string serialport, int baudrate, int databits, System.IO.Ports.Parity parity, System.IO.Ports.StopBits stopbits, System.IO.Ports.Handshake handshake)
        {
            try
            {
                _serial = new SerialPort(serialport)
                {
                    ReadTimeout  = TIMEOUT,
                    WriteTimeout = SerialPort.InfiniteTimeout,
                    BaudRate     = baudrate,
                    DataBits     = databits,
                    Parity       = parity,
                    StopBits     = stopbits,
                    Handshake    = handshake
                };
            }
            catch (System.Exception ex)
            {
                Logger.Error("Error open port", ex);
            }

            if (_serial != null)
            {
                Open(_serial);
            }
        }
Ejemplo n.º 23
0
 public AdvancedSerialPort(string portName, int baudRate, System.IO.Ports.Parity parity, int dataBits, System.IO.Ports.StopBits stopBits)
     : base(portName, baudRate, parity, dataBits, stopBits)
 {
 }