static public ushort ParityDecode(Parity aParity)
        {
            ushort zReturn;            

            switch (aParity)
            {
                case Parity.Even:
                    zReturn = 1;
                    break;
                case Parity.Mark:
                    zReturn = 2;
                    break;
                case Parity.None:
                    zReturn = 4;
                    break;
                case Parity.Odd:
                    zReturn = 0;
                    break;
                case Parity.Space:
                    zReturn = 3;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();                    
            }

            return zReturn;
        }
Пример #2
0
 public SerialTerminal(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
     : base(portName, baudRate, parity, dataBits, stopBits)
 {
     Open();
     Handshake = Handshake.XOnXOff;
     OperatingMode = IBM3151.OperatingModes.Echo;
 }
        public void SetComboBoxes(String comPortName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            try
               {
                    cmbComPortName.Text = GetValidPortName(cmbComPortName.Text);
               }
               catch (Exception ex)
               {
                    MessageBox.Show(ex.ToString());
                    cmbComPortName.Text = "NONE";
               }

               cmbBaudRate.Text = baudRate.ToString();
               cmbParity.SelectedIndex = GetIndexOfValue(cmbParity.Items, parity.ToString());
               cmbDataBits.SelectedIndex = GetIndexOfValue(cmbDataBits.Items, dataBits.ToString());
               switch (stopBits)
               {
                    case StopBits.One:
                         cmbStopBits.SelectedIndex = GetIndexOfValue(cmbStopBits.Items, "1");
                         break;
                    case StopBits.OnePointFive:
                         cmbStopBits.SelectedIndex = GetIndexOfValue(cmbStopBits.Items, "1.5");
                         break;
                    case StopBits.Two:
                         cmbStopBits.SelectedIndex = GetIndexOfValue(cmbStopBits.Items, "2");
                         break;
                    case StopBits.None:
                         cmbStopBits.SelectedIndex = GetIndexOfValue(cmbStopBits.Items, "1");
                         break;
                    default:
                         cmbStopBits.SelectedIndex = GetIndexOfValue(cmbStopBits.Items, "1");
                         break;
               }
        }
            /// <summary>
            /// Opens the serial port using the specified baud rate, parity bit, data bits, and stop bit.
            /// </summary>
            /// <param name="baudRate">The baud rate.</param>
            /// <param name="parity">One of the Parity values.</param>
            /// <param name="dataBits">The data bits value.</param>
            /// <param name="stopBits">One of the StopBits values.</param>
            public Windows.Foundation.IAsyncAction Open(
                uint baudRate,
                Parity parity,
                int dataBits,
                StopBits stopBits
            )
            {
                return Task.Run(async () =>
                {
                    this.baudRate  = baudRate;
                    this.parity    = parity;
                    this.dataBits  = dataBits;
                    this.stopBits  = stopBits;

                    if (this.cdcControl == null)
                    {
                        return;
                    }

                    // Do SetLineCoding
                    var len = await SetLineCoding(this.cdcControl.InterfaceNumber, this.baudRate, (byte)this.stopBits, (byte)this.parity, (byte)this.dataBits);
                    if (len != Constants.ExpectedResultSetLineCoding)
                    {
                        throw new System.NotSupportedException("SetLineCoding request is not supported.");
                    }

                    // Do SetControlLineState
                    len = await SetControlLineState(this.cdcControl.InterfaceNumber);
                    
                    return;

                }).AsAsyncAction();
            }
Пример #5
0
        public bool Open(string portName, int baudRate, int databits, Parity parity, StopBits stopBits)
        {
            //Ensure port isn't already opened:
            if (!sp.IsOpen)
            {
                //Assign desired settings to the serial port:
                sp.PortName = portName;
                sp.BaudRate = baudRate;
                sp.DataBits = databits;
                sp.Parity = parity;
                sp.StopBits = stopBits;
                //These timeouts are default and cannot be editted through the class at this point:
                sp.ReadTimeout = 2000;
                sp.WriteTimeout = 2000;
                try
                {
                    sp.Open();
                }
                catch (Exception err)
                {

                    return false;
                }

                return true;
            }
            else
            {

                return false;
            }
        }
Пример #6
0
 public SerialConfig(string cfg)
 {
     var parts = cfg.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
     this.initialConfig = cfg;
     int index = 0;
     if (!parts[index].StartsWith("COM"))
     {
         this.DeviceName = parts[index];
         index++;
     }
     this.PortName = parts[index]; index++;
     this.AutoConnect = Boolean.Parse(parts[index]); index++;
     this.Speed = UInt32.Parse(parts[index]); index++;
     this.DataBits = Byte.Parse(parts[index]); index++;
     this.Parity = (Parity)Byte.Parse(parts[index]); index++;
     this.StopBits = (StopBits)Byte.Parse(parts[index]); index++;
     //this.PacketType = (PacketType)Byte.Parse(parts[index]); index++;
     this.RxPacketType = (PacketType)Byte.Parse(parts[index]); index++;
     this.TxPacketType = (PacketType)Byte.Parse(parts[index]); index++;
     this.PacketType = this.RxPacketType;
     if (parts.Length > index)
     {
         this.ReceiverCRC = Byte.Parse(parts[index]); index++;
         this.TransmitterCRC = Byte.Parse(parts[index]); index++;
     }
     if (parts.Length > index)
     {
         this.DefaultDeviceAddr = Byte.Parse(parts[index]); index++;
     }
 }
Пример #7
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="bardRate"></param>
 /// <param name="parity"></param>
 /// <param name="dataBits"></param>
 /// <param name="stopBits"></param>
 public SerialPortSetting(int baudRate, Parity parity, int dataBits, StopBits stopBits)
 {
     this.BaudRate = baudRate;
         this.Parity = parity;
         this.DataBits = dataBits;
         this.StopBits = stopBits;
 }
Пример #8
0
        public RTU_Client(string PortName, int BaudRate = 9600, Parity Parity = Parity.None, int DataBits = 8, StopBits StopBits = StopBits.One, int Timeout = 2500)
        {
            try
            {
                Port = new SerialPort(PortName, BaudRate, Parity, DataBits, StopBits);
            }
            catch (IOException ex)
            {
                throw new RTU_Exception("Ошибка настроек коммуникационного порта. " + ex.Message, ex);
            }
            ByteTimeout = 20;
            MaxCount = 5;
            this.Timeout = Timeout;

            this.Buffer = new List<byte>(256);


            ReqSendEvent += delegate { };
            ByteRecievedEvent += delegate { };

            try
            {
                Port.Open();
            }
            catch (Exception ex)
            {
                throw new RTU_Exception("Ошибка открытия коммуникационного порта. " + ex.Message, ex);
            }

        }
Пример #9
0
 public void setportvalues(UInt32 BaudRate, int DataBits, StopBits StopBits, Parity Parity)
 {
     vBaudRate = BaudRate;
     vDataBits = DataBits;
     vStopBits = StopBits;
     vParity = Parity;
 }
Пример #10
0
 public static void initialize(string COM_port_Name, int baudRate, Parity parity, int dataBits, StopBits stopBits)
 {
     try
     {
         if (COM_port != null)
         {
             if (COM_port.IsOpen)
             {
                 COM_port.Close();
             }
         }
         COM_port = new SerialPort(COM_port_Name, baudRate, parity, dataBits, stopBits);
         COM_port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
         if (!COM_port.IsOpen)
         {
             COM_port.Open();
         }
         initialized = 1;
         Receiver.Interval = 10;
         Receiver.Elapsed += new System.Timers.ElapsedEventHandler(Receiver_time_out);
         Receiver.AutoReset = false;
         Synchro.Interval = 50;
         Synchro.Elapsed += new System.Timers.ElapsedEventHandler(Synchro_time_out);
         Synchro.AutoReset = false;
     }
     catch (Exception exception)
     {
         Error_messager.Invoke("Ошибка инициализации!\r\nRadist: \r\n" + exception.Message);
         initialized = 2;
     }
 }
Пример #11
0
 public RCRadio(string id, string port = "COM1", int baudRate = 115200, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
 {
     Port = new SerialPort(port, baudRate, parity, dataBits, stopBits);
     AutoPing = true;
     PingPeriod = 3000;
     DataQueue = new StringFifoQueue();
 }
Пример #12
0
        public PortManager(String portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, Form1 form )
        {
            if (this.port == null)
            {
                this.portName = portName;
                this.baudRate = baudRate;
                this.parity = parity;
                this.dataBits = dataBits;
                this.stopBits = stopBits;

                this.port = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
                this.port.DtrEnable = true;
                this.port.RtsEnable = true;
                this.port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

                Form = form;
            }
            else
            {
                this.port.BaudRate = baudRate;
                this.port.Parity = parity;
                this.port.DataBits = dataBits;
                this.port.StopBits = stopBits;
            }
        }
Пример #13
0
 public static EM406aGPS Start(string portName, int baudRate = 4800, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
 {
     EM406aGPS gps = new EM406aGPS(portName, baudRate, parity, dataBits, stopBits);
     gps._thread = new Thread(gps.Run);
     gps._thread.Start();
     return gps;
 }
Пример #14
0
 /// <summary>Initializes a new instance of the <see cref="SerialPort"/> class using the specified port name, baud rate, and parity bit.
 /// </summary>
 /// <param name="portName">The port to use (for example, COM1)</param>
 /// <param name="baudRate">The baud rate</param>
 /// <param name="parity">One of the <see cref="Parity"/> values</param>
 public SerialPort(string portName, int baudRate, Parity parity)
     : this()
 {
     PortName = portName;
     BaudRate = baudRate;
     Parity = parity;
 }
Пример #15
0
        /*
         *         public string ComPort = String.Empty;
        public int BaudRate = 110;
        public StopBits StopBits = StopBits.None;
        public int DataBits = 7;
        public Parity Parity = Parity.None;
         * */
        public BalanceReader(string comPort = "COM1", int baudRate = 9600, StopBits stopBits = StopBits.One,
            int dataBits = 7, Parity parity = Parity.Even, string sicsCommand = "SI", bool rts = false)
        {
            _sicsCommand = sicsCommand;

            if (comPort == String.Empty) comPort = "COM1";
            _port = new SerialPort
            {
                PortName = comPort,
                BaudRate = baudRate,
                StopBits = stopBits,
                DataBits = 7,
                Parity = Parity.Even,
                RtsEnable = rts
            };

            // from Page 39 of NewClassic Balances METTLER TOLEDO manual for MS-S / MS-L Models
            //_port.Handshake = Handshake.XOnXOff;

            if (_port.IsOpen == false)
            {
                try
                {
                    _port.Open();
                }
                catch (Exception)
                {
                    // port will not be open, therefore will become null
                }
            }

            _port.DataReceived += _port_DataReceived;
        }
Пример #16
0
 public void SetOptions(int baudrate, Parity parity, int databits, StopBits stopbits)
 {
     this.baudrate = baudrate;
     this.parity = parity;
     this.databits = databits;
     this.stopbits = stopbits;
 }
Пример #17
0
 public Transceiver(string portName, int baudRate = 96000, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
 {
     port = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
     port.Open();
     port.DataReceived += PortOnDataReceived;
     Debug.Print("Created transceiver on port " + portName);
 }
Пример #18
0
        public ComPort(byte number, int baudrate, byte data_bits, byte parity, byte stop_bits, ushort write_timeout, ushort read_timeout, byte attemts)
        {
            m_name = "COM" + Convert.ToString(number);
            m_baudrate = baudrate;
            m_data_bits = data_bits;
            m_parity = (Parity)parity;
            m_stop_bits = (StopBits)stop_bits;
            m_write_timeout = write_timeout;
            m_read_timeout = read_timeout;
            m_attemts = attemts;

            try
            {
                m_Port = new SerialPort(m_name, m_baudrate, m_parity, m_data_bits, m_stop_bits);

                /*ELF: для работы с elf108*/
                m_Port.DtrEnable = true;
                m_Port.RtsEnable = true;
            }
            catch (Exception ex)
            {
                #if (DEBUG)
                    WriteToLog("Create " + m_name + ": " + ex.Message);
                #endif
            }
        }
Пример #19
0
 public void InitCOM(string comName, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeout,int writeTimeout)
 {
     //com = new SerialPort("COM3", 9600, Parity.Even, 7, StopBits.One);
     com = new SerialPort(comName, baudRate, parity, dataBits, StopBits.One);
     com.ReadTimeout = readTimeout;
     com.WriteTimeout = writeTimeout;
 }
Пример #20
0
        public bool Open(string portName, int baudRate, int databits, Parity parity, StopBits stopBits)
        {
            //Ensure port isn't already opened:
            if (!sp.IsOpen)
            {
                //Assign desired settings to the serial port:
                sp.PortName = portName;
                sp.BaudRate = baudRate;
                sp.DataBits = databits;
                sp.Parity = parity;
                sp.StopBits = stopBits;
                //These timeouts are default and cannot be editted through the class at this point:
                sp.ReadTimeout = 1000;
                sp.WriteTimeout = 1000;

                try
                {
                    sp.Open();
                }
                catch (Exception err)
                {
                    modbusStatus = "Error opening " + portName + ": " + err.Message;
                    return false;
                    throw err;
                }
                modbusStatus = portName + " opened successfully";
                return true;
            }
            else
            {
                modbusStatus = portName + " already opened";
                return false;
            }
        }
Пример #21
0
        public FrostedSerialPortStream(string portName, int baudRate, int dataBits, Parity parity, StopBits stopBits,
                bool dtrEnable, bool rtsEnable, Handshake handshake, int readTimeout, int writeTimeout,
                int readBufferSize, int writeBufferSize)
        {


			fd = open_serial(portName);
			if (fd == -1) {
				ThrowIOException ();
			}

            TryBaudRate(baudRate);

			int canSetAttributes = set_attributes (fd, baudRate, parity, dataBits, stopBits, handshake);

			if (canSetAttributes != 0)
			{
				throw new IOException(canSetAttributes.ToString()); // Probably Win32Exc for compatibility
			}

            read_timeout = readTimeout;
            write_timeout = writeTimeout;

            SetSignal(SerialSignal.Dtr, dtrEnable);

            if (handshake != Handshake.RequestToSend &&
                    handshake != Handshake.RequestToSendXOnXOff)
                SetSignal(SerialSignal.Rts, rtsEnable);
        }
        public SerialDevice(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, string returnToken = "\n")
        {
            _dataReading = string.Empty;
            _dataQueue = new ConcurrentQueue<string>();

            _timeCounter = new Stopwatch();
            _timeCounter.Start();

            _COMPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);

            _returnToken = returnToken;

            _COMPort.NewLine = _returnToken;
            _COMPort.RtsEnable = true;
            _COMPort.DtrEnable = true;

            _COMPort.ReadTimeout = SerialPort.InfiniteTimeout;
            _COMPort.WriteTimeout = SerialPort.InfiniteTimeout;

            _COMPort.Open();

            if (!_COMPort.IsOpen)
                _COMPort.Open();
            if (!_COMPort.IsOpen)
                throw new Exception("Can't connect to the COM port!");

            _serialThread = new Thread(new ThreadStart(GetSerialDataContinious));
            _serialThread.Priority = ThreadPriority.Normal;
            _serialThread.Name = string.Format("SerialHandle{0}", _serialThread.ManagedThreadId);

            _communicatyionIsActive = true;
            _serialThread.Start();
        }
Пример #23
0
        private async void SaveSettingss(string port, int baud, Parity parity, Handshake handshake, int dataBits, StopBits stopBits)
        {
            writing = true;
            XmlWriterSettings settings = new XmlWriterSettings { Indent = true, NewLineOnAttributes = true };
            XmlWriter writer = XmlWriter.Create("Settings.xml", settings);

            writer.WriteStartDocument();
            writer.WriteStartElement("Settings");

            writer.WriteElementString("Port", port);
            writer.WriteElementString("Baudrate", baud.ToString());
            writer.WriteElementString("Parity", parity.ToString());
            writer.WriteElementString("Handshake", handshake.ToString());
            writer.WriteElementString("Data_Bits", dataBits.ToString());
            writer.WriteElementString("Stop_Bits", stopBits.ToString());

            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
            writing = false;
            if(!initialization)
            {
                MessageDialogResult result = await MessageService.ShowMessage("Gespeichert!", "Settings wurden gespeichert!", MessageDialogStyle.Affirmative).ConfigureAwait(false);
            }
            
        }
        public void Start(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            if (!GetAvailablePorts().Contains(portName))
            {
                throw new Exception(string.Format("Unknown serial port: {0}", portName));
            }

            // Start the timer to empty the receive buffer (in case data smaller than MAX_RECEIVE_BUFFER is received)
            _bufferTimer = new Timer();
            _bufferTimer.Interval = BUFFER_TIMER_INTERVAL;
            _bufferTimer.Elapsed += _bufferTimer_Elapsed;
            _bufferTimer.Start();

            // Instantiate new serial port communication
            _serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);

            // Open serial port communication
            _serialPort.Open();

            // Check that it is actually open
            if (!_serialPort.IsOpen)
            {
                throw new Exception(string.Format("Could not open serial port: {0}", portName));
            }

            _serialPort.ReadTimeout = 100; // Milliseconds

            _readThread = new System.Threading.Thread(ReadThread);
            _readThreadRunning = true;
            _readThread.Start();
        }
Пример #25
0
 public BasicInformation(string portName, int baudRate, Parity parity, StopBits stopBits, int dataBits, Handshake handShake, string serviceCenter, bool pduMode)
 { 
     this.Connector = new ATController(portName, baudRate, parity, stopBits, dataBits, handShake);
     ServiceCenter = serviceCenter;
     PDUMode = pduMode;
     this.PortName = portName;
 }
Пример #26
0
 public PortInitInfo(int mBaudRate,Parity mParity, int mDataBits, StopBits mStopBits)
 {
     this._BaudRate    = mBaudRate;
     this._Parity      = mParity;
     this._DataBits    = mDataBits;
     this._StopBits    = mStopBits;
 }
Пример #27
0
 /// <summary>
 /// 构造函数,可以自定义串口的初始化参数
 /// </summary>
 /// <param name="comPortName">需要操作的COM口名称</param>
 /// <param name="baudRate">COM的速度</param>
 /// <param name="parity">奇偶校验位</param>
 /// <param name="dataBits">数据长度</param>
 /// <param name="stopBits">停止位</param>
 public SerialClass(string comPortName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
 {
     _serialPort = new SerialPort(comPortName, baudRate, parity, dataBits, stopBits);
     _serialPort.RtsEnable = true;  //自动请求
     _serialPort.ReadTimeout = 3000;//超时
     setSerialPort();
 }
Пример #28
0
 /// <summary>Initializes a new instance of the <see cref="SerialPort"/> class using the specified port name, baud rate, parity bit, and data bits.
 /// </summary>
 /// <param name="portName">The port to use (for example, COM1)</param>
 /// <param name="baudRate">The baud rate</param>
 /// <param name="parity">One of the <see cref="Parity"/> values</param>
 /// <param name="dataBits">The data bits value</param>
 public SerialPort(string portName, int baudRate, Parity parity, int dataBits)
     : this()
 {
     PortName = portName;
     BaudRate = baudRate;
     Parity = parity;
     DataBits = dataBits;
 }
 public void CreateDefault()
 {
     comname = "Com1";
     speed = 115200;
     databits = 8;
     parity = Parity.None;
     stopbits = StopBits.One;
 }
Пример #30
0
 /// <summary>
 /// Create a new ConnectionSettings object passed into the ELM327API to configure the serial port connections used
 /// for communication between OBD Express and the ELM327 device it is connected to.
 /// </summary>
 /// <param name="baudRate">Baud Rate to connect with.</param>
 /// <param name="dataBits">Data Bits used for communication.</param>
 /// <param name="parity">Parity used for verification on communications.</param>
 /// <param name="stopBits">Stop Bits used for communication.</param>
 /// <param name="deviceDescription">Device Description to expect from the ELM327.</param>
 public ConnectionSettings(int baudRate, int dataBits, Parity parity, StopBits stopBits, string deviceDescription)
 {
     _baudRate = baudRate;
     _dataBits = dataBits;
     _parity = parity;
     _stopBits = stopBits;
     _deviceDescription = deviceDescription;
 }
Пример #31
0
 public TestSerialPort(string portName, int baudRate, Parity parity)
     : base(portName, baudRate, parity)
 {
     this.TestSerialPort_Init();
 }
Пример #32
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="portName">端口号</param>
 /// <param name="baudRate">波特率</param>
 /// <param name="parity">奇偶校验</param>
 /// <param name="dataBits">数据位</param>
 /// <param name="stopBits">停止位</param>
 public SerialClass(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
 {
     _serialPort             = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
     _serialPort.RtsEnable   = true; //自动请求
     _serialPort.ReadTimeout = 3000; //超时
 }
Пример #33
0
 //
 // Summary:
 //     Initializes a new instance of the System.IO.Ports.SerialPort class using
 //     the specified port name, baud rate, parity bit, data bits, and stop bit.
 //
 // Parameters:
 //   portName:
 //     The port to use (for example, COM1).
 //
 //   baudRate:
 //     The baud rate.
 //
 //   parity:
 //     One of the System.IO.Ports.SerialPort.Parity values.
 //
 //   dataBits:
 //     The data bits value.
 //
 //   stopBits:
 //     One of the System.IO.Ports.SerialPort.StopBits values.
 //
 // Exceptions:
 //   System.IO.IOException:
 //     The specified port could not be found or opened.
 public SerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits) : this(
         new System.IO.Ports.SerialPort(portName, baudRate, parity, dataBits, stopBits))
 {
 }
Пример #34
0
 //
 // Summary:
 //     Initializes a new instance of the System.IO.Ports.SerialPort class using
 //     the specified port name, baud rate, and parity bit.
 //
 // Parameters:
 //   portName:
 //     The port to use (for example, COM1).
 //
 //   baudRate:
 //     The baud rate.
 //
 //   parity:
 //     One of the System.IO.Ports.SerialPort.Parity values.
 //
 // Exceptions:
 //   System.IO.IOException:
 //     The specified port could not be found or opened.
 public SerialPort(string portName, int baudRate, Parity parity) : this(
         new System.IO.Ports.SerialPort(portName, baudRate, parity))
 {
 }
Пример #35
0
 /// <summary>
 /// use serial port, set the port name,baud rate,data bits,stopbits,parity
 /// </summary>
 /// <param name="portName">serial port name</param>
 /// <param name="baudRate">serial port baud rate</param>
 /// <param name="dataBits">serial port data bits</param>
 /// <param name="StopBits">serial port stopbits</param>
 /// <param name="Parity">serial port parity</param>
 public void InitializeDevice(string portName, int baudRate, int dataBits, StopBits stopBits, Parity parity)
 {
     InitializeDevice(portName, baudRate, dataBits, stopBits, parity, HANDSHAKE);
 }
Пример #36
0
        void PollingLoop()
        {
            try
            {
                /* ----------------------------------------------------------------------------
                 * Start
                 * ----------------------------------------------------------------------------*/
                logText = "Start load cell console meter."; _Log.AppendText(logText);
                logText = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"); _Log.AppendText(logText);

                /* ----------------------------------------------------------------------------
                 * port setting
                 * ----------------------------------------------------------------------------*/
                this.portName  = Properties.Settings.Default.PortName;
                this.baudRate  = Properties.Settings.Default.BaudRate;
                this.dataBits  = Properties.Settings.Default.DataBits;
                this.parity    = Properties.Settings.Default.Parity;
                this.stopBits  = Properties.Settings.Default.StopBits;
                this.handshake = Properties.Settings.Default.Handshake;

                /* ----------------------------------------------------------------------------
                 * Treat load cell class with the port
                 * ----------------------------------------------------------------------------*/
                serialText = new SerialText.SimpleSerialText(portName, baudRate, dataBits, parity, stopBits, handshake);

                /* ----------------------------------------------------------------------------
                 * Connect
                 * ----------------------------------------------------------------------------*/
                logText    = "Connecting..."; _Log.AppendText(logText);
                StopFlag   = false;
                Connecting = true; Running = false;
                Connect();
                if (!Running || Connecting)
                {
                    tRecon = new Thread(Reconnection); // Fast response() and wait for connection here!
                    tRecon.Start();
                }

                /* ----------------------------------------------------------------------------
                 * LOOP
                 * ----------------------------------------------------------------------------*/
                SerialText.Utilities.Response serial_res;
                while (!StopFlag)
                {
                    if (Running && !Connecting)
                    {
                        logText = "Do polling..."; _Log.AppendText(logText);

                        serial_res = serialText.Read();
                        logText    = serial_res.Message;
                        _Log.AppendText(logText);
                        if (!serial_res.Success)
                        {
                            if (serial_res.Code != 6 && serial_res.Code != 7)
                            {
                                if (!StopFlag)
                                {
                                    Running = false;
                                    tRecon  = new Thread(Reconnection); // Fast response() and wait for connection here!
                                    tRecon.Start();
                                }
                            }
                        }
                        else // Success
                        {
                            List <StringBuilder> ret = (List <StringBuilder>)serial_res.Data;
                            foreach (StringBuilder sb in ret)
                            {
                                string str = (sb.ToString().Replace(":", "")).Replace("#", "");
                                GenerateQrCode(str);
                                logText = String.Format(">>> Qr Generated : {0}", str);
                                _Log.AppendText(logText);
                                PostResponse(logText);
                            }
                        }

                        Thread.Sleep(PollingDelay);
                    }
                }

                /* ----------------------------------------------------------------------------
                 * Exit
                 * ----------------------------------------------------------------------------*/
                logText = "End the process."; _Log.AppendText(logText); PostResponse(logText);
            }
            catch (Exception ex)
            {
                /* ----------------------------------------------------------------------------
                 * Log
                 * ----------------------------------------------------------------------------*/
                logText = "Exceptional stop."; _Log.AppendText(logText);
                logText = ex.Message; _Log.AppendText(logText);
                PostResponse(logText);
            }
        }
Пример #37
0
 public MySerialPort(string portName, int baudRate, Parity parity)
     : base(portName, baudRate, parity)
 {
     SetEvent();
 }
Пример #38
0
 public FrostedSerialPort(string portName, int baudRate, Parity parity) :
     this(portName, baudRate, parity, DefaultDataBits, DefaultStopBits)
 {
 }
Пример #39
0
 public ISerialMessagePort CreateSerialMessagePort(SerialPortName portName, byte[] prefixDelimiter, bool preserveDelimiter, int messageLength, int baudRate = 9600, int dataBits = 8, Parity parity = Parity.None, StopBits stopBits = StopBits.One, int readBufferSize = 512)
 {
     throw new NotImplementedException();
 }
Пример #40
0
 public ISerialPort CreateSerialPort(SerialPortName portName, int baudRate = 9600, int dataBits = 8, Parity parity = Parity.None, StopBits stopBits = StopBits.One, int readBufferSize = 1024)
 {
     throw new NotImplementedException();
 }
Пример #41
0
 /// <summary>
 /// Info for event
 /// </summary>
 /// <param name="number"></param>
 /// <param name="parity"></param>
 /// <param name="color"></param>
 public void SupplementInfo(int number, Parity parity, Color color)
 {
     InvokeEvent(new RouletteEventArgs(number, parity, color));
 }
        /// <summary>
        /// Change the RS-232 serial interface communication parameters.
        /// </summary>
        public static void Rs232SerialSettings(this Gu256x128c device, int baudRate = Gu256x128c.DefaultBaudRate, Parity parity = Gu256x128c.DefaultParity)
        {
            var a = BaudRateList[baudRate];
            var b = ParityList[parity];

            device.WriteBytes(new byte[] { 0x1F, 0x28, 0x69, 0x10, a, b });

            device.serialPort.Close();
            device.serialPort.BaudRate = baudRate;
            device.serialPort.Parity   = parity;
            device.serialPort.Open();
        }
Пример #43
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="portName">COM端口名称</param>
 /// <param name="baudRate">波特率</param>
 /// <param name="dataBits">数据位</param>
 /// <param name="stopBits">停止位</param>
 /// <param name="parity">奇偶校验</param>
 /// <param name="timeout">超时时间(毫秒)</param>
 /// <param name="format">大小端设置</param>
 public ModbusAsciiClient(string portName, int baudRate, int dataBits, StopBits stopBits, Parity parity, int timeout = 1500, EndianFormat format = EndianFormat.ABCD)
     : base(portName, baudRate, dataBits, stopBits, parity, timeout, format)
 {
 }
 private SerialDevice(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
 {
     this.serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
 }
Пример #45
0
 public SerialPort(string portName, int baudRate, Parity parity, int dataBits) :
     this(portName, baudRate, parity, dataBits, DefaultStopBits)
 {
 }
Пример #46
0
        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (TxtIdentifier.Text == "")
            {
                MessageBox.Show("分隔符不能为空"); return;
            }
            if (!无串口ToolStripMenuItem.Checked && !GrpPort1.Enabled && !GrpPort2.Enabled)
            {
                MessageBox.Show("请勾选生产模式"); return;
            }
            #region 检查是否有空值和2个串口是否用同一端口名
            if (GrpPort1.Enabled)
            {
                foreach (Control control in GrpPort1.Controls)
                {
                    if (control.Text == "")
                    {
                        MessageBox.Show("串口1参数有空值,不能保存");
                        return;
                    }
                }
            }
            if (GrpPort2.Enabled)
            {
                if (CmbPortName1.Text == CmbPortName2.Text && CmbPortName2.Text != "")
                {
                    MessageBox.Show("串口2的端口名已被串口1占用");
                    return;
                }
                foreach (Control control in GrpPort2.Controls)
                {
                    if (control.Text == "")
                    {
                        MessageBox.Show("串口2参数有空值,不能保存");
                        return;
                    }
                }
            }
            #endregion

            Parity   parity   = Parity.None;
            StopBits stopBits = StopBits.One;
            switch (CmbParity1.Text)
            {
            case "偶":
                parity = Parity.Even;
                break;

            case "奇":
                parity = Parity.Odd;
                break;

            case "无":
                parity = Parity.None;
                break;

            case "标记":
                parity = Parity.Mark;
                break;

            case "空格":
                parity = Parity.Space;
                break;
            }
            switch (CmbStopBits1.Text)
            {
            case "1":
                stopBits = StopBits.One;
                break;

            case "1.5":
                stopBits = StopBits.OnePointFive;
                break;

            case "2":
                stopBits = StopBits.Two;
                break;
            }
            //非"无串口"下,测试串口能否打开
            if (!无串口ToolStripMenuItem.Checked)
            {
                try
                {
                    //打开串口
                    Main.main.SptReceiveOrSend.Close();
                    Main.main.SptSend.Close();
                    //Main.main.SptReceiveOrSend = new SerialPort
                    //    (CmbPortName1.Text, int.Parse(CmbBaudRate1.Text), parity, int.Parse(CmbDataBits1.Text), stopBits);
                    Main.main.SptReceiveOrSend.PortName = CmbPortName1.Text;
                    Main.main.SptReceiveOrSend.BaudRate = int.Parse(CmbBaudRate1.Text);
                    Main.main.SptReceiveOrSend.Parity   = parity;
                    Main.main.SptReceiveOrSend.DataBits = int.Parse(CmbDataBits1.Text);
                    Main.main.SptReceiveOrSend.StopBits = stopBits;
                    Main.main.SptReceiveOrSend.Open();
                }
                catch (Exception ex)
                {
                    Main.main.SptReceiveOrSend.Close();
                    //Main.main.SptSend.Close();
                    MessageBox.Show(ex.Message, "串口1通讯:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (GrpPort2.Enabled)
                {
                    switch (CmbParity2.Text)
                    {
                    case "偶":
                        parity = Parity.Even;
                        break;

                    case "奇":
                        parity = Parity.Odd;
                        break;

                    case "无":
                        parity = Parity.None;
                        break;

                    case "标记":
                        parity = Parity.Mark;
                        break;

                    case "空格":
                        parity = Parity.Space;
                        break;
                    }
                    switch (CmbStopBits2.Text)
                    {
                    case "1":
                        stopBits = StopBits.One;
                        break;

                    case "1.5":
                        stopBits = StopBits.OnePointFive;
                        break;

                    case "2":
                        stopBits = StopBits.Two;
                        break;
                    }
                    try
                    {
                        //Main.main.SptSend.Close();
                        Main.main.SptSend.PortName = CmbPortName2.Text;
                        Main.main.SptSend.BaudRate = int.Parse(CmbBaudRate2.Text);
                        Main.main.SptSend.Parity   = parity;
                        Main.main.SptSend.DataBits = int.Parse(CmbDataBits2.Text);
                        Main.main.SptSend.StopBits = stopBits;
                        Main.main.SptSend.Open();
                    }
                    catch (Exception ex)
                    {
                        //Main.main.SptReceiveOrSend.Close();
                        Main.main.SptSend.Close();
                        MessageBox.Show(ex.Message, "串口2通讯:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
            }
            #region 能成功打开串口后,保存到注册表以及更改属性
            RegistryKey key      = Registry.LocalMachine;
            RegistryKey software = key.OpenSubKey(@"software\NTRS", true);
            //串口
            if (!无串口ToolStripMenuItem.Checked)
            {
                string[] port = { CmbPortName1.Text, CmbBaudRate1.Text, CmbParity1.Text, CmbDataBits1.Text, CmbStopBits1.Text };
                if (GrpPort2.Enabled)
                {
                    string[]      port2 = { CmbPortName2.Text, CmbBaudRate2.Text, CmbParity2.Text, CmbDataBits2.Text, CmbStopBits2.Text };
                    List <string> temp  = port.ToList();
                    temp.AddRange(port2);
                    port = new string[] { };
                    port = temp.ToArray();
                }
                software.SetValue("Port", port, RegistryValueKind.MultiString);
            }
            else
            {
                software.SetValue("Port", new string[] { }, RegistryValueKind.MultiString);
            }
            //生产模式
            string mode = "";
            if (旧机器API2ToolStripMenuItem.Checked)
            {
                Main.mode = Main.Mode.旧机器API2; mode = "旧机器API2";
            }
            else if (无串口ToolStripMenuItem.Checked)
            {
                Main.mode = Main.Mode.无串口; mode = "无串口";
            }

            software.SetValue("Mode", mode, RegistryValueKind.String);
            //分隔符
            if (TxtIdentifier.Text == "[CR]")
            {
                identifier = "\r";
            }
            else if (TxtIdentifier.Text == "[LF]")
            {
                identifier = "\n";
            }
            else if (TxtIdentifier.Text.Length != 1)
            {
                identifier = TxtIdentifier.Text.Substring(TxtIdentifier.Text.Length - 1, 1);
            }
            else
            {
                identifier = TxtIdentifier.Text;
            }

            software.SetValue("Identifier", identifier, RegistryValueKind.String);
            #endregion
            MessageBox.Show("保存成功");
            this.Close();
        }
Пример #47
0
 public BinarySerialDevice(string portName, int baudRate, Parity parity) : base(portName, baudRate, parity)
 {
 }
Пример #48
0
        public WinSerialStream(string port_name, int baud_rate, int data_bits, Parity parity, StopBits sb,
                               bool dtr_enable, bool rts_enable, Handshake hs, int read_timeout, int write_timeout,
                               int read_buffer_size, int write_buffer_size)
        {
            handle = CreateFile(port_name, GenericRead | GenericWrite, 0, 0, OpenExisting,
                                FileFlagOverlapped, 0);

            if (handle == -1)
            {
                ReportIOError(port_name);
            }

            // Set port low level attributes
            SetAttributes(baud_rate, parity, data_bits, sb, hs);

            // Clean buffers and set sizes
            if (!PurgeComm(handle, PurgeRxClear | PurgeTxClear) ||
                !SetupComm(handle, read_buffer_size, write_buffer_size))
            {
                ReportIOError(null);
            }

            // Set timeouts
            this.read_timeout  = read_timeout;
            this.write_timeout = write_timeout;
            timeouts           = new Timeouts(read_timeout, write_timeout);
            if (!SetCommTimeouts(handle, timeouts))
            {
                ReportIOError(null);
            }

            /// Set DTR and RTS
            SetSignal(SerialSignal.Dtr, dtr_enable);

            if (hs != Handshake.RequestToSend &&
                hs != Handshake.RequestToSendXOnXOff)
            {
                SetSignal(SerialSignal.Rts, rts_enable);
            }

            // Init overlapped structures
            NativeOverlapped wo = new NativeOverlapped();

            write_event = new ManualResetEvent(false);
#if NET_2_0
            wo.EventHandle = write_event.Handle;
#else
            wo.EventHandle = (int)write_event.Handle;
#endif
            write_overlapped = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeOverlapped)));
            Marshal.StructureToPtr(wo, write_overlapped, true);

            NativeOverlapped ro = new NativeOverlapped();
            read_event = new ManualResetEvent(false);
#if NET_2_0
            ro.EventHandle = read_event.Handle;
#else
            ro.EventHandle = (int)read_event.Handle;
#endif
            read_overlapped = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeOverlapped)));
            Marshal.StructureToPtr(ro, read_overlapped, true);
        }
Пример #49
0
 /// <summary>
 /// use serial port, set the port name,baud rate,data bits,stopbits,parity
 /// </summary>
 /// <param name="portName">serial port name</param>
 /// <param name="baudRate">serial port baud rate</param>
 /// <param name="dataBits">serial port data bits</param>
 /// <param name="StopBits">serial port stopbits</param>
 /// <param name="Parity">serial port parity</param>
 /// <param name="handshake">handshake type(hardware )</param>
 public void InitializeDevice(string portName, int baudRate, int dataBits, StopBits stopBits, Parity parity, Handshake handshake)
 {
     ResetDevice();
     if (null != _connectedSerialPort)
     {
         _connectedSerialPort.PortName  = portName;
         _connectedSerialPort.BaudRate  = baudRate;
         _connectedSerialPort.DataBits  = dataBits;
         _connectedSerialPort.StopBits  = stopBits;
         _connectedSerialPort.Parity    = parity;
         _connectedSerialPort.Handshake = handshake;
     }
 }
Пример #50
0
 /// <summary>Creates new ComPort instance</summary>
 /// <param name="portName">Name of the port (e.g. COM1)</param>
 /// <param name="baudRate">baudrate for the port</param>
 /// <param name="parity">parity for the port</param>
 public ComPort(string portName, int baudRate, Parity parity)
     : base(portName, baudRate, parity)
 {
 }
 public ObservableSerialPort_byte(string portName, int baudRate = 9600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
 : base(portName, baudRate, parity, dataBits, stopBits) { }
Пример #52
0
 /// <summary>Creates new ComPort instance</summary>
 /// <param name="portName">Name of the port (e.g. COM1)</param>
 /// <param name="baudRate">baudrate for the port</param>
 /// <param name="parity">parity for the port</param>
 /// <param name="dataBits">number of data bits</param>
 /// <param name="stopBits">number of stop bits</param>
 public ComPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
     : base(portName, baudRate, parity, dataBits, stopBits)
 {
 }
Пример #53
0
 public SerialConnection(string portName, int baudRate, int dataBits, StopBits stopBits, Parity parity)
 {
     this.portName = portName;
     this.baudRate = baudRate;
     this.dataBits = dataBits;
     this.stopBits = stopBits;
     this.parity   = parity;
 }
Пример #54
0
 public override void SetParameters(int baudRate, DataBits dataBits, StopBits stopBits, Parity parity) => BaudRate = baudRate;
Пример #55
0
        protected override void SetParameters(int baudRate, int dataBits, StopBits stopBits, Parity parity)
        {
            byte stopBitsByte;

            switch (stopBits)
            {
            case StopBits.One:
                stopBitsByte = 0;
                break;

            case StopBits.OnePointFive:
                stopBitsByte = 1;
                break;

            case StopBits.Two:
                stopBitsByte = 2;
                break;

            default: throw new ArgumentException("Bad value for stopBits: " + stopBits);
            }

            byte parityBitesByte;

            switch (parity)
            {
            case Parity.None:
                parityBitesByte = 0;
                break;

            case Parity.Odd:
                parityBitesByte = 1;
                break;

            case Parity.Even:
                parityBitesByte = 2;
                break;

            case Parity.Mark:
                parityBitesByte = 3;
                break;

            case Parity.Space:
                parityBitesByte = 4;
                break;

            default: throw new ArgumentException("Bad value for parity: " + parity);
            }

            byte[] msg =
            {
                (byte)(baudRate & 0xff),
                (byte)((baudRate >> 8) & 0xff),
                (byte)((baudRate >> 16) & 0xff),
                (byte)((baudRate >> 24) & 0xff),
                stopBitsByte,
                parityBitesByte,
                (byte)dataBits
            };
            SendAcmControlMessage(SET_LINE_CODING, 0, msg);
        }
        public static SerialDevice CreateDevice(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            List <string> serial_ports = new List <string>();

            return(new SerialDevice(portName, baudRate, parity, dataBits, stopBits));
        }
Пример #57
0
 public MySerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
     : base(portName, baudRate, parity, dataBits, stopBits)
 {
     SetEvent();
 }
Пример #58
0
 public virtual void Open(string Port, int Baud, int DataBits, StopBits Stop, Parity ParityBits)
 {
     throw new NotImplementedException();
 }
Пример #59
0
 public TestSerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
     : base(portName, baudRate, parity, dataBits, stopBits)
 {
     this.TestSerialPort_Init();
 }
        public static ISerialDevice CreateSerialDevice(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            ISerialDevice device = null;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                device = WinSerialDevice.CreateDevice(portName, baudRate, parity, dataBits, stopBits);
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                device = UnixSerialDevice.CreateDevice(portName, baudRate, parity, dataBits, stopBits);
            }
            return(device);
        }