示例#1
0
        public async Task Initialize(uint baudrate, SerialParity parity, SerialStopBitCount stopBits, ushort dataBits)
        {
            try
            {
                string aqs = SerialDevice.GetDeviceSelector();
                var    dis = await DeviceInformation.FindAllAsync(aqs);

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

                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate     = baudrate;
                serialPort.Parity       = parity;
                serialPort.StopBits     = stopBits;
                serialPort.DataBits     = dataBits;
                serialPort.Handshake    = SerialHandshake.None;

                _baudrate = baudrate;
                _parity   = parity;
                _stopBits = stopBits;
                _dataBits = dataBits;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
示例#2
0
        /// <summary>
        /// 생성자
        /// </summary>
        /// <param name="portName">포트 이름</param>
        /// <param name="baudRate">Baud Rate</param>
        /// <param name="dataBits">Data Bits</param>
        /// <param name="stopBits">Stop Bits</param>
        /// <param name="parity">Parity</param>
        /// <param name="handshake">ㅗandshake</param>
        public SerialPortModbusChannel(string portName, int baudRate, int dataBits,
                                       SerialStopBitCount stopBits, SerialParity parity, SerialHandshake handshake)
        {
            PortName  = portName;
            BaudRate  = baudRate;
            DataBits  = dataBits;
            StopBits  = stopBits;
            Parity    = parity;
            Handshake = handshake;

            Description = PortName;

            foreach (var instance in instances.ToArray())
            {
                if (!instance.Value.TryGetTarget(out var channelSerial))
                {
                    RemoveIntance(channelSerial.GetHashCode());
                }
            }


            Open(null);

            AddInstance(this);
        }
示例#3
0
 /// <summary>
 /// Metodo que guarda la configuracion de la conexion
 /// </summary>
 /// <param name="portName"></param>
 /// <param name="baudRate"></param>
 /// <param name="parity"></param>
 /// <param name="stopBits"></param>
 /// <param name="dataBits"></param>
 public static void Config(string portName, uint baudRate, SerialParity parity, SerialStopBitCount stopBits, ushort dataBits)
 {
     _portName = portName;
     _baudRate = baudRate;
     _parity   = parity;
     _stopBits = stopBits;
     _dataBits = dataBits;
 }
示例#4
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();
        }
示例#5
0
 private static STOP_BITS GetStopBits(SerialStopBitCount stopBits)
 {
     switch (stopBits)
     {
         case SerialStopBitCount.One:
             return STOP_BITS.BITS_1;
         case SerialStopBitCount.Two:
             return STOP_BITS.BITS_2;
         default:
             throw new Exception($"SerialStopBitCount {stopBits} is not supported for the FTDIDevice.");
     }
 }
示例#6
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;
 }
示例#7
0
 public ParametresPortSerie(string nom, string idRecherche, uint vitesse, SerialParity parite, SerialStopBitCount bitsDeStop, ushort bitsDeDonnees, SerialHandshake controleDeFlux, double dureeLectureMs, double dureeEcritureMs)
 {
     Nom             = nom;
     IdRecherche     = idRecherche;
     Vitesse         = vitesse;
     Parite          = parite;
     BitsDeStop      = bitsDeStop;
     BitsDeDonnees   = bitsDeDonnees;
     ControleDeFlux  = controleDeFlux;
     DureeLectureMs  = dureeLectureMs;
     DureeEcritureMs = dureeEcritureMs;
 }
示例#8
0
        public static SerialStopBits Convert(this SerialStopBitCount sb)
        {
            switch (sb)
            {
            case SerialStopBitCount.One: return(SerialStopBits.One);

            case SerialStopBitCount.OnePointFive: return(SerialStopBits.OnePointFive);

            case SerialStopBitCount.Two: return(SerialStopBits.Two);

            default: return(SerialStopBits.One);
            }
        }
示例#9
0
        private static STOP_BITS GetStopBits(SerialStopBitCount stopBits)
        {
            switch (stopBits)
            {
            case SerialStopBitCount.One:
                return(STOP_BITS.BITS_1);

            case SerialStopBitCount.Two:
                return(STOP_BITS.BITS_2);

            default:
                throw new Exception($"SerialStopBitCount {stopBits} is not supported for the FTDIDevice.");
            }
        }
示例#10
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;
        }
示例#11
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;
        }
示例#13
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);
        }
示例#15
0
 public static ParametresPortSerie CreerPourUARTGpioPi(uint vitesse, SerialParity parite, SerialStopBitCount bitsDeStop, ushort bitsDeDonnees, SerialHandshake controleDeFlux, double dureeLectureMs, double dureeEcritureMs)
 {
     if (string.IsNullOrEmpty(_piIdString))
     {
         _piIdString = RaspberryPi.EstRaspberryPi2() ? @"\\?\ACPI#BCM2837#4#" : @"\\?\ACPI#BCM2836#0#";
     }
     return(new ParametresPortSerie("", _piIdString, vitesse, parite, bitsDeStop, bitsDeDonnees, controleDeFlux, dureeLectureMs, dureeEcritureMs));
 }
示例#16
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);
        }
示例#17
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);
            }
        }
        public Result Initialise(string serialPortId, uint baudRate, SerialParity serialParity, ushort dataBits, SerialStopBitCount stopBitCount,
                                 TimeSpan readTimeout = default, TimeSpan writeTimeout = default)
        {
            Result result;

            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.DataBits  = dataBits;
            serialDevice.StopBits  = stopBitCount;
            serialDevice.Handshake = SerialHandshake.None;
            serialDevice.WatchChar = '\n';

            atCommandExpectedResponse = string.Empty;

            serialDevice.DataReceived += SerialDevice_DataReceived;

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

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

            outputDataWriter = new DataWriter(serialDevice.OutputStream);

            // Set the Working mode to LoRaWAN
#if DIAGNOSTICS
            Debug.WriteLine($" {DateTime.UtcNow:hh:mm:ss} lora:work_mode LoRaWAN");
#endif
            result = SendCommand("Initialization OK", "at+set_config=lora:work_mode:0", CommandTimeoutDefault);
            if (result != Result.Success)
            {
#if DIAGNOSTICS
                Debug.WriteLine($" {DateTime.UtcNow:hh:mm:ss} lora:work_mode failed {result}");
#endif
                return(result);
            }

            return(Result.Success);
        }
示例#19
0
        public async void Open(string portID, uint baudRate, ushort databits, SerialParity parity, SerialStopBitCount stopBits)
        {
            //Ensure port isn't already opened:
            if (!sp.IsDataTerminalReadyEnabled)
            {
                modbusStatus = portID + " already opened";
                return(false);
            }
            try {
                sp = await SerialDevice.FromIdAsync(portID);

                //Assign desired settings to the serial port:
                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  = TimeSpan.FromMilliseconds(1000);
                sp.WriteTimeout = TimeSpan.FromMilliseconds(1000);
            }
            catch (Exception err)
            {
                modbusStatus = "Error opening " + portID + ": " + err.Message;
                return(false);
            }
            modbusStatus = portID + " opened successfully";
            return(true);
        }
示例#20
0
 /// <summary>
 /// A container for the client app to specify its serial communications protocol.
 ///
 /// This class is used by the Host singleton class in the method:
 ///
 ///     public async Task Connect(string deviceId, PortDef portDef)
 ///
 /// The Genie Standard Protocol provides a simple yet effective interface between the display and the host
 /// controller and all communications are reported over this bidirectional link. The protocol utilises only a handful
 /// of commands and is simple and easy to implement.
 ///
 /// Serial data settings are:
 /// 8 Bits, No Parity, 1 Stop Bit.
 ///
 /// Note: RS-232 handshaking signals (i.e., RTS, CTS, DTR, and DSR) are not supported by the ViSi-Genie protocols.
 /// Instead, only the RxD(received data), TxD(transmitted data), and signal ground are used.
 ///
 /// </summary>
 /// <param name="baudRate"></param>
 /// <param name="serialParity"></param>
 /// <param name="serialStopBitCount"></param>
 /// <param name="dataBits"></param>
 public PortDef(BaudRate baudRate, SerialParity serialParity = SerialParity.None, SerialStopBitCount serialStopBitCount = SerialStopBitCount.One, ushort dataBits = 8)
 {
     this.BaudRate           = baudRate;
     this.SerialParity       = serialParity;
     this.SerialStopBitCount = serialStopBitCount;
     this.DataBits           = dataBits;
 }
示例#21
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;
 }