Example #1
0
        public XBeeSerialPort(uint baudRate, SerialParity parity, SerialStopBitCount stopBitCount, ushort dataBits, APIVersion apiVersion)
        {
            this.baudRate = baudRate;
            this.parity = parity;
            this.stopBitCount = stopBitCount;
            this.dataBits = dataBits;
            this.apiVersion = apiVersion;

            StartListeningForSerialPortChanges();
        }
Example #2
0
        internal void SetFormat(int data_bits, SerialParity parity, int stop_bits)
        {
            this.data_bits = data_bits;
            this.parity    = parity;
            this.stop_bits = stop_bits;

            if (serial != null)
            {
                serial.DataBits = data_bits;
                switch (parity)
                {
                case SerialParity.ParityNone:
                    serial.Parity = Parity.None;
                    break;

                case SerialParity.ParityOdd:
                    serial.Parity = Parity.Odd;
                    break;

                case SerialParity.ParityEven:
                    serial.Parity = Parity.Even;
                    break;

                case SerialParity.ParityForced1:
                    serial.Parity = Parity.Mark;
                    break;

                case SerialParity.ParityForced0:
                    serial.Parity = Parity.Space;
                    break;
                }
                switch (stop_bits)
                {
                case 0:
                    serial.StopBits = StopBits.None;
                    break;

                case 1:
                    serial.StopBits = StopBits.One;
                    break;

                case 2:
                    serial.StopBits = StopBits.Two;
                    break;

                case 15:
                    serial.StopBits = StopBits.OnePointFive;
                    break;
                }
            }
        }
Example #3
0
        public SerialPortSettings(
            string serialPortName,
            uint baudRate,
            SerialStopBitCount stopBits,
            SerialParity parity,
            ushort dataBits = 8)
        {
            Assure.ArgumentNotNull(serialPortName, nameof(serialPortName));

            SerialPortName = serialPortName;
            BaudRate       = baudRate;
            StopBits       = stopBits;
            Parity         = parity;
            DataBits       = dataBits;
        }
Example #4
0
 public Device(
     int writeTimeOut            = 1000,
     int readTimeout             = 1000,
     uint baudRate               = 9600,
     SerialParity parity         = SerialParity.None,
     SerialStopBitCount stopBits = SerialStopBitCount.One,
     ushort dataBits             = 8,
     SerialHandshake handshake   = SerialHandshake.None)
 {
     this.writeTimeOutTimeSpan = TimeSpan.FromMilliseconds(writeTimeOut);
     this.readTimeOutTimeSpan  = TimeSpan.FromMilliseconds(readTimeout);
     this.baudRate             = baudRate;
     this.parity    = parity;
     this.stopBits  = stopBits;
     this.dataBits  = dataBits;
     this.handshake = handshake;
 }
        public IDeviceNetwork CreateDeviceNetwork(Dictionary<string, string> configuration)
        {
            // get serial port configuration from the configuration dictionary
            baudRate = UInt32.Parse(configuration["BaudRate"]);
            parity = (SerialParity)Enum.Parse(typeof(SerialParity), configuration["SerialParity"], true);
            stopBit = (SerialStopBitCount)Enum.Parse(typeof(SerialStopBitCount), configuration["SerialStopBitCount"], true);
            dataBits = UInt16.Parse(configuration["DataBits"]);
            apiVersion = (APIVersion)Enum.Parse(typeof(APIVersion), configuration["APIVersion"], true);

            // create the serial port
            IXBeeSerialPort serialPort = CreateSerialPortWithSavedConfigurationParameters();

            // now create the device network with this serial port
            XBeeDeviceNetwork network = new XBeeDeviceNetwork(serialPort);

            return network;
        }
Example #6
0
        /// <summary>
        /// Creates an instance of <see cref="Serial" /> for the given socket.
        /// </summary>
        /// <remarks>This automatically checks that the socket supports Type U, and reserves the pins.
        /// An exception will be thrown if there is a problem with these checks.</remarks>
        /// <param name="baudRate">The baud rate for the serial port.</param>
        /// <param name="parity">A value from the <see cref="SerialParity"/> enumeration that specifies
        /// the parity for the port.</param>
        /// <param name="stopBits">A value from the <see cref="SerialStopBits"/> enumeration that specifies
        /// the stop bits for the port.</param>
        /// <param name="dataBits">The number of data bits.</param>
        /// <param name="socket">The socket for this serial interface.</param>
        /// <param name="hardwareFlowControlRequirement">Specifies whether the module must use hardware flow control, will use hardware flow control if available, or does not use hardware flow control.</param>
        /// <param name="module">The module using this interface (which can be null if unspecified).</param>
        /// <returns>An instance of <see cref="Serial" /> for the given socket.</returns>
        public static Serial Create(Socket socket, int baudRate, SerialParity parity, SerialStopBits stopBits, int dataBits, HardwareFlowControl hardwareFlowControlRequirement, Module module)
        {
            bool hwFlowSupported = false;

            if (hardwareFlowControlRequirement == HardwareFlowControl.Required)
            {
                socket.EnsureTypeIsSupported('K', module);
            }
            else
            {
                hwFlowSupported = socket.SupportsType('K');

                if (!hwFlowSupported)
                {
                    socket.EnsureTypeIsSupported('U', module);
                }
            }

            socket.ReservePin(Socket.Pin.Four, module);
            socket.ReservePin(Socket.Pin.Five, module);
            if (hardwareFlowControlRequirement != HardwareFlowControl.NotRequired)
            {
                // must reserve hardware flow control pins even if not using them, since they are electrically connected.
                socket.ReservePin(Socket.Pin.Six, module);
                socket.ReservePin(Socket.Pin.Seven, module);
            }

            string portName = socket.SerialPortName;

            Serial instance;

            if ((portName == null || portName == "") && socket.SerialIndirector != null)
            {
                instance = socket.SerialIndirector(socket, baudRate, (SerialParity)parity, (SerialStopBits)stopBits, dataBits, (HardwareFlowControl)hardwareFlowControlRequirement, module);
            }

            else
            {
                instance = new NativeSerial(socket, baudRate, (SerialParity)parity, (SerialStopBits)stopBits, dataBits, (HardwareFlowControl)hardwareFlowControlRequirement, module, portName, hwFlowSupported);
            }

            instance.NewLine      = "\n";
            instance.ReadTimeout  = System.Threading.Timeout.Infinite;
            instance.WriteTimeout = System.Threading.Timeout.Infinite;
            return(instance);
        }
Example #7
0
        public static SerialParityType Convert(this SerialParity sp)
        {
            switch (sp)
            {
            case SerialParity.None: return(SerialParityType.None);

            case SerialParity.Odd: return(SerialParityType.Odd);

            case SerialParity.Even: return(SerialParityType.Even);

            case SerialParity.Mark: return(SerialParityType.Mark);

            case SerialParity.Space: return(SerialParityType.Space);

            default: return(SerialParityType.None);
            }
        }
Example #8
0
 private static PARITY GetParity(SerialParity parity)
 {
     switch (parity)
     {
         case SerialParity.Even:
             return PARITY.EVEN;
             case SerialParity.Mark:
             return PARITY.MARK;
             case SerialParity.None:
             return PARITY.NONE;
             case SerialParity.Odd:
             return PARITY.ODD;
         case SerialParity.Space:
             return PARITY.SPACE;
         default:
             throw new Exception($"SerialParity {parity} is not supported for the FTDIDevice.");
     }
 }
Example #9
0
        /// <summary>Initializes the serial port with the given parameters.</summary>
        /// <param name="baudRate">The baud rate to use.</param>
        /// <param name="parity">The parity to use.</param>
        /// <param name="stopBits">The stop bits to use.</param>
        /// <param name="dataBits">The number of data bits to use.</param>
        /// <param name="flowControl">The flow control to use.</param>
        public void Configure(uint baudRate, SerialParity parity, SerialStopBitCount stopBits, ushort dataBits, SerialHandshake flowControl)
        {
            if (this.serialPort != null)
            {
                throw new InvalidOperationException("Configure can only be called once.");
            }

            serialPort           = SerialDevice.FromId(ComId);
            serialPort.BaudRate  = baudRate;
            serialPort.Parity    = parity;
            serialPort.StopBits  = stopBits;
            serialPort.DataBits  = dataBits;
            serialPort.Handshake = flowControl;
            _outStream           = serialPort.OutputStream;
            _inStream            = serialPort.InputStream;
            SerialWriter         = new DataWriter(_outStream);
            SerialReader         = new DataReader(_inStream);
        }
        public Result Initialise(string serialPortId, uint baudRate, SerialParity serialParity = SerialParity.None, ushort dataBits = 8, SerialStopBitCount stopBitCount = SerialStopBitCount.One, TimeSpan readTimeout = default, TimeSpan writeTimeout = default)
        {
            if ((serialPortId == null) || (serialPortId == ""))
            {
                throw new ArgumentException("Invalid SerialPortId", "serialPortId");
            }
            if ((baudRate < BaudRateMinimum) || (baudRate > BaudRateMaximum))
            {
                throw new ArgumentException("Invalid BaudRate", "baudRate");
            }

            serialDevice = SerialDevice.FromId(serialPortId);

            // set parameters
            serialDevice.BaudRate  = baudRate;
            serialDevice.Parity    = serialParity;
            serialDevice.StopBits  = stopBitCount;
            serialDevice.Handshake = SerialHandshake.None;
            serialDevice.DataBits  = dataBits;
            serialDevice.WatchChar = '\n';

            if (readTimeout == default)
            {
                serialDevice.ReadTimeout = ReadTimeoutDefault;
            }

            if (writeTimeout == default)
            {
                serialDevice.WriteTimeout = WriteTimeoutDefault;
            }

            atCommandExpectedResponse = string.Empty;

            outputDataWriter = new DataWriter(serialDevice.OutputStream);

            serialDevice.DataReceived += SerialDevice_DataReceived;

            // Ignoring the return from this is intentional
            this.SendCommand("+LOWPOWER: WAKEUP", "AT+LOWPOWER: WAKEUP", SendTimeoutMinimum);

            return(Result.Success);
        }
        public ApplicationSettings(string configFileName)
        {
            string applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
            string configFile      = Path.Combine(applicationPath, configFileName);

            // Use defaults if configuration file is not readable
            if (!File.Exists(configFile))
            {
                return;
            }

            // Read configuration file settings
            XElement xmlConfig = XElement.Load(configFile);

            // Get serial port settings
            foreach (XElement serialPort in xmlConfig.Elements("SerialPort"))
            {
                SerialPortName = (string)serialPort.Element("PortName") ?? SerialPortName;
                SerialBaudRate = (int?)serialPort.Element("BaudRate") ?? SerialBaudRate;
                SerialDataBits = (int?)serialPort.Element("DataBits") ?? SerialDataBits;

                Enum.TryParse((string)serialPort.Element("Parity") ?? SerialParity.ToString(), true, out Parity parseParity);
                SerialParity = parseParity;

                Enum.TryParse((string)serialPort.Element("StopBits") ?? SerialStopBits.ToString(), true, out StopBits parseStopBits);
                SerialStopBits = parseStopBits;

                Enum.TryParse((string)serialPort.Element("FlowControl") ?? SerialFlowControl.ToString(), true, out Handshake parseFlowControl);
                SerialFlowControl = parseFlowControl;
            }

            // Get GPIB adapter settings
            foreach (XElement gpibAdapter in xmlConfig.Elements("GPIBAdapter"))
            {
                GPIBAdapterTimeout       = (int?)gpibAdapter.Element("Timeout") ?? GPIBAdapterTimeout;
                GPIBAdapterVersionString = (string)gpibAdapter.Element("VersionString") ?? GPIBAdapterVersionString;
            }
        }
Example #12
0
        /// <summary>
        /// Creates an instance of <see cref="Serial" /> for the given socket.
        /// </summary>
        /// <remarks>This automatically checks that the socket supports Type U, and reserves the pins.
        /// An exception will be thrown if there is a problem with these checks.</remarks>
        /// <param name="baudRate">The baud rate for the serial port.</param>
        /// <param name="parity">A value from the <see cref="SerialParity"/> enumeration that specifies 
        /// the parity for the port.</param>
        /// <param name="stopBits">A value from the <see cref="SerialStopBits"/> enumeration that specifies 
        /// the stop bits for the port.</param>
        /// <param name="dataBits">The number of data bits.</param>
        /// <param name="socket">The socket for this serial interface.</param>
        /// <param name="hardwareFlowControlRequirement">Specifies whether the module must use hardware flow control, will use hardware flow control if available, or does not use hardware flow control.</param>
        /// <param name="module">The module using this interface (which can be null if unspecified).</param>
        /// <returns>An instance of <see cref="Serial" /> for the given socket.</returns>
        public static Serial Create(Socket socket, int baudRate, SerialParity parity, SerialStopBits stopBits, int dataBits, HardwareFlowControl hardwareFlowControlRequirement, Module module)
        {
            bool hwFlowSupported = false;

            if (hardwareFlowControlRequirement == HardwareFlowControl.Required)
                socket.EnsureTypeIsSupported('K', module);
            else
            {
                hwFlowSupported = socket.SupportsType('K');

                if (!hwFlowSupported)
                    socket.EnsureTypeIsSupported('U', module);
            }

            socket.ReservePin(Socket.Pin.Four, module);
            socket.ReservePin(Socket.Pin.Five, module);
            if (hardwareFlowControlRequirement != HardwareFlowControl.NotRequired)
            {
                // must reserve hardware flow control pins even if not using them, since they are electrically connected.
                socket.ReservePin(Socket.Pin.Six, module);
                socket.ReservePin(Socket.Pin.Seven, module);
            }

            string portName = socket.SerialPortName;

            Serial instance;

            if ((portName == null || portName == "") && socket.SerialIndirector != null)
                instance = socket.SerialIndirector(socket, baudRate, (SerialParity)parity, (SerialStopBits)stopBits, dataBits, (HardwareFlowControl)hardwareFlowControlRequirement, module);

            else
                instance = new NativeSerial(socket, baudRate, (SerialParity)parity, (SerialStopBits)stopBits, dataBits, (HardwareFlowControl)hardwareFlowControlRequirement, module, portName, hwFlowSupported);

            instance.NewLine = "\n";
            instance.ReadTimeout = System.Threading.Timeout.Infinite;
            instance.WriteTimeout = System.Threading.Timeout.Infinite;            
            return instance;
        }
Example #13
0
        public NativeSerial(Socket socket, int baudRate, SerialParity parity, SerialStopBits stopBits, int dataBits, HardwareFlowControl hwFlowRequirement, Module module, string portName, bool hwFlowSupported)
        {
            if (portName == null || portName == "")
            {
                // this is a mainboard error that should not happen (we already check for it in SocketInterfaces.RegisterSocket) but just in case...
                throw Socket.InvalidSocketException.FunctionalityException(socket, "Serial");
            }

            _port = new Hardware.SerialPort(portName, baudRate, (Hardware.Parity)parity, dataBits, (Hardware.StopBits)stopBits);

            if ((hwFlowRequirement != SocketInterfaces.HardwareFlowControl.NotRequired) && hwFlowSupported)
            {
                _port.Handshake = Hardware.Handshake.RequestToSend;
                _hardwareFlowControl = true;
            }

            try
            {
                this.ReadTimeout = System.Threading.Timeout.Infinite;
                this.WriteTimeout = System.Threading.Timeout.Infinite;
            }
            catch { }
        }
Example #14
0
        private static PARITY GetParity(SerialParity parity)
        {
            switch (parity)
            {
            case SerialParity.Even:
                return(PARITY.EVEN);

            case SerialParity.Mark:
                return(PARITY.MARK);

            case SerialParity.None:
                return(PARITY.NONE);

            case SerialParity.Odd:
                return(PARITY.ODD);

            case SerialParity.Space:
                return(PARITY.SPACE);

            default:
                throw new Exception($"SerialParity {parity} is not supported for the FTDIDevice.");
            }
        }
Example #15
0
        public NativeSerial(Socket socket, int baudRate, SerialParity parity, SerialStopBits stopBits, int dataBits, HardwareFlowControl hwFlowRequirement, Module module, string portName, bool hwFlowSupported)
        {
            if (portName == null || portName == "")
            {
                // this is a mainboard error that should not happen (we already check for it in SocketInterfaces.RegisterSocket) but just in case...
                throw Socket.InvalidSocketException.FunctionalityException(socket, "Serial");
            }

            _port = new Hardware.SerialPort(portName, baudRate, (Hardware.Parity)parity, dataBits, (Hardware.StopBits)stopBits);

            if ((hwFlowRequirement != SocketInterfaces.HardwareFlowControl.NotRequired) && hwFlowSupported)
            {
                _port.Handshake      = Hardware.Handshake.RequestToSend;
                _hardwareFlowControl = true;
            }

            try
            {
                this.ReadTimeout  = System.Threading.Timeout.Infinite;
                this.WriteTimeout = System.Threading.Timeout.Infinite;
            }
            catch { }
        }
Example #16
0
        public async Task <int> Open(string portName, int baudRate, SerialParity parity = SerialParity.None, int dataBits = 8, SerialStopBitCount stopBits = SerialStopBitCount.One)
        {
            //new SerialPort(portName, baudRate, parity, dataBits, stopBits);
            try
            {
                string aqs = SerialDevice.GetDeviceSelector(portName);
                var    dis = await DeviceInformation.FindAllAsync(aqs);

                if (dis.Count == 0)
                {
                    return(-1);
                }

                serial = await SerialDevice.FromIdAsync(dis[0].Id);

                if (serial == null)
                {
                    return(-1);
                }

                Debug.WriteLine("   open serial OK \r\n", serial.PortName);

                serial.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serial.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                serial.BaudRate     = (uint)baudRate;
                serial.Parity       = parity;
                serial.StopBits     = stopBits;
                serial.DataBits     = (ushort)dataBits;
                serial.Handshake    = SerialHandshake.None;
                //serial.Open();
                return(0);
            }
            catch (Exception e)
            {
                return(-1);
            }
        }
Example #17
0
 public ConnectionSettings(uint baudRate, ushort dataBits, SerialStopBitCount stopBits, 
                           SerialParity parity, SerialHandshake handshake, 
                           byte xOn = 0x00, byte xOff = 0x00)
 {
     BaudRate = baudRate;
     DataBits = dataBits;
     StopBits = stopBits;
     Parity = parity;
     Handshake = handshake;
     XOn = xOn;
     XOff = xOff;
 }
Example #18
0
        /// <summary>
        /// Parse the serial port setting.
        /// </summary>
        /// <param name="setting">The serial port setting string.</param>
        /// <returns>True if the operation succeeded, otherwise false</returns>
        bool ParsePortSetting(string setting)
        {
            string[] result = setting.Split(delimiter);
            if (result.Length != 4)
            {
                return false;
            }

            if (!UInt32.TryParse(result[0], out baudRate))
            {
                return false;
            }

            if (!UInt32.TryParse(result[1], out dataBits))
            {
                return false;
            }

            if (0 == string.Compare(result[2], "N", StringComparison.OrdinalIgnoreCase))
            {
                parity = SerialParity.None;
            }
            else if (0 == string.Compare(result[2], "E", StringComparison.OrdinalIgnoreCase))
            {
                parity = SerialParity.Even;
            }
            else if (0 == string.Compare(result[2], "O", StringComparison.OrdinalIgnoreCase))
            {
                parity = SerialParity.Odd;
            }
            else
            {
                return false;
            }

            if (!UInt32.TryParse(result[3], out stopBits))
            {
                return false;
            }

            return true;
        }
Example #19
0
        ///<summary>
        ///Open port to make a connect
        ///打开串口开始连接
        ///</summary>
        ///<param name="portName">Name of COM port to open</param>
        ///<param name="pAddress">StaatusFrame类的实例的地址</param>
        ///<param name="baudRate">baud rate of COM port 传输速率</param>
        ///<param name="parity">type of data parity</param>
        ///<param name="dataBits">Number of data bits</param>
        ///<param name="stopbits">Number of stop</param>
        public async Task <bool> Open(string portName, StatusFrame pAddress, uint baudRate = 9600, SerialParity parity = SerialParity.None, ushort dataBits = 8, SerialStopBitCount stopBits = SerialStopBitCount.One)
        {
            //close open port 关闭当前正在打开的串口
            //防止错误覆盖
            Close();

            //get a list of devices from the given portname
            string selector = SerialDevice.GetDeviceSelector(portName);

            // Get a list of devices that match the given name
            DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);

            // If any device found...
            if (devices.Any())
            {
                // Get first device (should be only device)
                DeviceInformation deviceInfo = devices.First();

                // Create a serial port device from the COM port device ID
                this.SerialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);

                // If serial device is valid...
                if (this.SerialDevice != null)
                {
                    // Setup serial port configuration
                    this.SerialDevice.StopBits = stopBits;
                    this.SerialDevice.Parity   = parity;
                    this.SerialDevice.BaudRate = baudRate;
                    this.SerialDevice.DataBits = dataBits;

                    // Create a single device writer for this port connection
                    this.dataWriterObject = new DataWriter(this.SerialDevice.OutputStream);

                    // Create a single device reader for this port connection
                    this.dataReaderObject = new DataReader(this.SerialDevice.InputStream);

                    // Allow partial reads of the input stream
                    this.dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;


                    pAddress.PortName = portName;

                    // Port is now open
                    this.IsOpen = true;
                }
            }

            return(this.IsOpen);
        }
        // Note: A constructor summary is auto-generated by the doc builder.
        /// <summary></summary>
        /// <remarks>This automatically checks that the socket supports Type U, and reserves the pins.
        /// An exception will be thrown if there is a problem with these checks.</remarks>
        /// <param name="baudRate">The baud rate for the serial port.</param>
        /// <param name="parity">A value from the <see cref="SerialParity"/> enumeration that specifies
        /// the parity for the port.</param>
        /// <param name="stopBits">A value from the <see cref="SerialStopBits"/> enumeration that specifies
        /// the stop bits for the port.</param>
        /// <param name="dataBits">The number of data bits.</param>
        /// <param name="socket">The socket for this serial interface.</param>
        /// <param name="hardwareFlowControlRequirement">Specifies whether the module must use hardware flow control, will use hardware flow control if available, or does not use hardware flow control.</param>
        /// <param name="module">The module using this interface (which can be null if unspecified).</param>
        public Serial(Socket socket, int baudRate, SerialParity parity, SerialStopBits stopBits, int dataBits, HardwareFlowControl hardwareFlowControlRequirement, Module module)
        {
            if (!socket.SupportsType('U'))
            {
                if (module != null)
                {
                    throw new Socket.InvalidSocketException("Module " + module + " cannot use socket " + socket + " because it requires a socket supporting type 'K'" + (hardwareFlowControlRequirement == HardwareFlowControl.Required ? "" : " or type 'U'."));
                }
                else
                {
                    throw new Socket.InvalidSocketException("Cannot use socket " + socket + " because it does not support socket type 'K'" + (hardwareFlowControlRequirement == HardwareFlowControl.Required ? "" : " or type 'U'."));
                }
            }

            bool socketSupportsHardwareFlowControl = socket.SupportsType('K');

            if (hardwareFlowControlRequirement == HardwareFlowControl.Required && !socketSupportsHardwareFlowControl)
            {
                if (module != null)
                {
                    throw new Socket.InvalidSocketException("Module " + module + " cannot use socket " + socket + " because it requires a socket supporting type 'K'.");
                }
                else
                {
                    throw new Socket.InvalidSocketException("Cannot use socket " + socket + " because it does not support socket type 'K' and hardware flow control is required. Please relax the requirement for hardware flow control or use a socket supporting type 'K'.");
                }
            }

            string portName = socket.SerialPortName;

            if (portName == null || portName == "")
            {
                // this is a mainboard error that should not happen (we already check for it in SocketInterfaces.RegisterSocket) but just in case...
                throw new Socket.InvalidSocketException("Socket " + socket + " has an error with its Serial functionality. Please try a different socket.");
            }

            socket.ReservePin(Socket.Pin.Four, module);
            socket.ReservePin(Socket.Pin.Five, module);
            if (hardwareFlowControlRequirement != HardwareFlowControl.NotRequired)
            {
                // must reserve hardware flow control pins even if not using them, since they are electrically connected.
                socket.ReservePin(Socket.Pin.Six, module);
                socket.ReservePin(Socket.Pin.Seven, module);
            }

            this.LineReceivedEventDelimiter = "\n";

            this.Encoding = System.Text.Encoding.UTF8;

            this._serialPort = new SerialPort(portName, baudRate, (System.IO.Ports.Parity)parity, dataBits, (System.IO.Ports.StopBits)stopBits);
            if ((hardwareFlowControlRequirement != HardwareFlowControl.NotRequired) && socketSupportsHardwareFlowControl)
            {
                this._serialPort.Handshake = Handshake.RequestToSend;
                this._hardwareFlowControl  = true;
            }
            else
            {
                this._hardwareFlowControl = false;
            }

            this._serialPort.DataReceived += new SerialDataReceivedEventHandler(this._serialPort_DataReceived);
            this.ReadTimeout  = InfiniteTimeout;
            this.WriteTimeout = InfiniteTimeout;
        }
Example #21
0
        // Note: A constructor summary is auto-generated by the doc builder.
        /// <summary></summary>
        /// <remarks>This automatically checks that the socket supports Type U, and reserves the pins.
        /// An exception will be thrown if there is a problem with these checks.</remarks>
        /// <param name="baudRate">The baud rate for the serial port.</param>
        /// <param name="parity">A value from the <see cref="SerialParity"/> enumeration that specifies 
        /// the parity for the port.</param>
        /// <param name="stopBits">A value from the <see cref="SerialStopBits"/> enumeration that specifies 
        /// the stop bits for the port.</param>
        /// <param name="dataBits">The number of data bits.</param>
        /// <param name="socket">The socket for this serial interface.</param>
        /// <param name="hardwareFlowControlRequirement">Specifies whether the module must use hardware flow control, will use hardware flow control if available, or does not use hardware flow control.</param>
        /// <param name="module">The module using this interface (which can be null if unspecified).</param>
        public Serial(Socket socket, int baudRate, SerialParity parity, SerialStopBits stopBits, int dataBits, HardwareFlowControl hardwareFlowControlRequirement, Module module)
        {
            if (!socket.SupportsType('U'))
            {
                if (module != null)
                {
                    throw new Socket.InvalidSocketException("Module " + module + " cannot use socket " + socket + " because it requires a socket supporting type 'K'" + (hardwareFlowControlRequirement == HardwareFlowControl.Required ? "" : " or type 'U'."));
                }
                else
                {
                    throw new Socket.InvalidSocketException("Cannot use socket " + socket + " because it does not support socket type 'K'" + (hardwareFlowControlRequirement == HardwareFlowControl.Required ? "" : " or type 'U'."));
                }
            }

            bool socketSupportsHardwareFlowControl = socket.SupportsType('K');
            if (hardwareFlowControlRequirement == HardwareFlowControl.Required && !socketSupportsHardwareFlowControl)
            {
                if (module != null)
                {
                    throw new Socket.InvalidSocketException("Module " + module + " cannot use socket " + socket + " because it requires a socket supporting type 'K'.");
                }
                else
                {
                    throw new Socket.InvalidSocketException("Cannot use socket " + socket + " because it does not support socket type 'K' and hardware flow control is required. Please relax the requirement for hardware flow control or use a socket supporting type 'K'.");
                }
            }

            string portName = socket.SerialPortName;

            if (portName == null || portName == "")
            {
                // this is a mainboard error that should not happen (we already check for it in SocketInterfaces.RegisterSocket) but just in case...
                throw new Socket.InvalidSocketException("Socket " + socket + " has an error with its Serial functionality. Please try a different socket.");

            }

            socket.ReservePin(Socket.Pin.Four, module);
            socket.ReservePin(Socket.Pin.Five, module);
            if (hardwareFlowControlRequirement != HardwareFlowControl.NotRequired)
            {
                // must reserve hardware flow control pins even if not using them, since they are electrically connected.
                socket.ReservePin(Socket.Pin.Six, module);
                socket.ReservePin(Socket.Pin.Seven, module);
            }

            this.LineReceivedEventDelimiter = "\n";

            this.Encoding = System.Text.Encoding.UTF8;

            this._serialPort = new SerialPort(portName, baudRate, (System.IO.Ports.Parity)parity, dataBits, (System.IO.Ports.StopBits)stopBits);
            if ((hardwareFlowControlRequirement != HardwareFlowControl.NotRequired) && socketSupportsHardwareFlowControl)
            {
                this._serialPort.Handshake = Handshake.RequestToSend;
                this._hardwareFlowControl = true;
            }
            else
            {
                this._hardwareFlowControl = false;
            }

            this._serialPort.DataReceived += new SerialDataReceivedEventHandler(this._serialPort_DataReceived);
            this.ReadTimeout = InfiniteTimeout;
            this.WriteTimeout = InfiniteTimeout;
        }