Exemplo n.º 1
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);
            }
        }
Exemplo n.º 2
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);
            }
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
0
 public void RS232_Device_Setting(string comname, int baudrate, int databit, int Paritytype, int stopbittype)
 {
     comportname = comname;
     baudRate    = baudrate;
     mdatabit    = databit;
     if (Paritytype == 0)
     {
         SerialParity = Parity.None;
     }
     if (stopbittype == 0)
     {
         stopbit = StopBits.One;
     }
 }
Exemplo n.º 5
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());
        }
Exemplo n.º 6
0
        //string parity값을 enum형식으로 변환
        private System.IO.Ports.Parity Parity_to_Serial(string parity)
        {
            System.IO.Ports.Parity result_parity = System.IO.Ports.Parity.None;

            if (parity == "Odd")
            {
                result_parity = System.IO.Ports.Parity.Odd;
            }
            else if (parity == "Even")
            {
                result_parity = System.IO.Ports.Parity.Even;
            }

            return(result_parity);
        }
Exemplo n.º 7
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);
 }
Exemplo n.º 8
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);
 }
        //
        public Stream GetConnection(Uri uri)
        {
            if (uri == null)
            {
                return(null);
            }
            if (!_connections.ContainsKey(uri))
            {
                if (uri.Scheme == Uri.UriSchemeNetTcp)
                {
                    var tcpClient = new System.Net.Sockets.TcpClient();
                    tcpClient.Connect(uri.Host, uri.Port);
                    _connections.Add(uri, tcpClient.GetStream());
                }
                else if (uri.Scheme == Uri.UriSchemeFile)
                {
                    //0
                    // stop bit 0
                    int dataBit  = ImageConfig.DataBit;
                    int baudRate = ImageConfig.BaudRate;
                    System.IO.Ports.Parity parity = (System.IO.Ports.Parity)ImageConfig.Parity;
                    StopBits stopbit = (StopBits)ImageConfig.StopBit;
                    try
                    {
                        var com = new System.IO.Ports.SerialPort(uri.Host.ToUpper(), baudRate, parity, dataBit, stopbit);
                        com.WriteTimeout = ImageConfig.WriteTimeout;
                        com.ReadTimeout  = ImageConfig.ReadTimeout;
                        com.Open();
                        _connections.Add(uri, com.BaseStream);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    throw new NotSupportedException("uri is not supported");
                }
            }

            return(_connections[uri]);
        }
Exemplo n.º 10
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;
            }
        }
Exemplo n.º 11
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");
            }
        }
Exemplo n.º 12
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;
    }
Exemplo n.º 13
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
            {
            }
        }
Exemplo n.º 14
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; //###### 未捕获错误信息,这段代码令错误更加糟糕
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Получить протокол контроля четности
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private Parity GetParity(string text)
        {
            System.IO.Ports.Parity pr = Parity.None;
            switch (text)
            {
            case "Чет":

                pr = Parity.Even;
                break;

            case "Нечет":

                pr = Parity.Odd;
                break;

            case "Нет":

                pr = Parity.None;
                break;

            case "Маркер":

                pr = Parity.Mark;
                break;

            case "Пробел":

                pr = Parity.Space;
                break;

            default:

                break;
            }
            return(pr);
        }
Exemplo n.º 16
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)
 {
 }
Exemplo n.º 17
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;
        }
Exemplo n.º 18
0
 public void SetParity(Parity defaultParity = Parity.None)
 {
     _Logger.Log(String.Format("Parity was changed from [{0}] to [{1}]", _port.Parity, defaultParity));
     _port.Parity = defaultParity;
     _Parity = defaultParity;
 }
Exemplo n.º 19
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;
                //}
            }
        }
Exemplo n.º 20
0
 public bool Open(string portname, string baudrate, string databits, System.IO.Ports.Parity parity, StopBits stopbits)
 {
     throw new NotImplementedException();
 }
 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()
 }
Exemplo n.º 22
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();
        }
Exemplo n.º 23
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); }
            }
        }
Exemplo n.º 24
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);
 }
Exemplo n.º 25
0
 public SerialPortEx(string portName, int baudRate, System.IO.Ports.Parity parity)
 {
     Init(portName, baudRate, parity, 8, StopBits.One);
 }
Exemplo n.º 26
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);
        }