public static async Task <Pn532CommunicationHsu> CreateSerialPort(string deviceName)
        {
            string deviceQuery = SerialDevice.GetDeviceSelector(deviceName);
            var    discovered  = await DeviceInformation.FindAllAsync(deviceQuery);

            var readerInfo = discovered.FirstOrDefault(/*x => x.Name.IndexOf(deviceName, StringComparison.OrdinalIgnoreCase) > -1*/);
            //var readerInfo = discovered.FirstOrDefault();

            SerialDevice reader = null;

            if (readerInfo != null)
            {
                reader = await SerialDevice.FromIdAsync(readerInfo.Id);

                if (reader != null)
                {
                    reader.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                    reader.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                    reader.BaudRate     = 115200;
                    reader.Parity       = SerialParity.None;
                    reader.StopBits     = SerialStopBitCount.One;
                    reader.DataBits     = 8;
                }
                else
                {
                    throw new Exception("Reader Not configured");
                }
            }
            else
            {
                throw new Exception("Reader Not configured");
            }

            return(new Pn532CommunicationHsu(reader));
        }
Exemple #2
0
        private async void SerialPortConfiguration()
        {
            if (portId != null && serialPort == null)
            {
                try
                {
                    serialPort = await SerialDevice.FromIdAsync(portId);

                    serialPort.WriteTimeout     = TimeSpan.FromMilliseconds(100);
                    serialPort.ReadTimeout      = TimeSpan.FromMilliseconds(100);
                    serialPort.BaudRate         = 115200;
                    serialPort.Parity           = SerialParity.None;
                    serialPort.StopBits         = SerialStopBitCount.One;
                    serialPort.DataBits         = 8;
                    serialPort.Handshake        = SerialHandshake.None;
                    ReadCancellationTokenSource = new CancellationTokenSource();
                    Debug.WriteLine("Connection configuration completed");
                    Listen();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message + " - Failed to connect.");
                }
            }
        }
        public async void InitializeReader(Action <string> callback)
        {
            //Selector nadje device
            var selector = SerialDevice.GetDeviceSelector(port);
            //info na onsovu selektora
            var devices = await DeviceInformation.FindAllAsync(selector);

            //nadje se device info
            if (devices.Any())
            {
                var deviceInfo = devices.First();
                //najosjetljivija metoda, vraca null ako nesto nije uredu
                //to moze biti da nije capability naveden u manifestu, da device ne prepoznaje ili da je device zauzet od druge aplikacije
                //da je user blokirao ili sistem
                //moze biti null iako je nadjen device information
                serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);

                //Set up serial device according to device specifications:
                //This might differ from device to device
                //specifikacije com porta, nacin na koj iuredjaj salje bite
                serialDevice.BaudRate = 9600;
                serialDevice.DataBits = 8;
                serialDevice.Parity   = SerialParity.None;
                serialDevice.StopBits = SerialStopBitCount.One;

                serialDevice.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                //ima sekundu izmedju dva citanja, ako se kartica brzo provuce dvaput biti ce 28 bita
                ReadCancellationTokenSource = new CancellationTokenSource();
                //pokretanje uredjaja
                Listen(callback);
            }
        }
Exemple #4
0
        public WinIotPackageManager()
        {
            try
            {
                _sequenceDataList = new List <byte[]>();
                _packetRecived    = new AutoResetEvent(false);
                var deviceSelector = SerialDevice.GetDeviceSelector();
                var devices        = Task.Run(async() => await DeviceInformation.FindAllAsync(deviceSelector)).Result;
                if (devices.Count <= 0)
                {
                    throw new Exception("Device not found -->[WinIotPakcgeManager_Constructor]");
                }

                var entry = devices.Single(x => x.Name.Equals("CP2102 USB to UART Bridge Controller")); //CP2102 USB to UART Bridge Controller

                _serialDevice = SerialDevice.FromIdAsync(entry.Id).AsTask().Result;

                // Configure serial settings
                _serialDevice.WriteTimeout = TimeSpan.FromMilliseconds(250);
                _serialDevice.ReadTimeout  = TimeSpan.FromMilliseconds(250);
                _serialDevice.BaudRate     = 57600;
                _serialDevice.Parity       = SerialParity.None;
                _serialDevice.StopBits     = SerialStopBitCount.One;
                _serialDevice.DataBits     = 8;

                // Create cancellation token object to close I/O operations when closing the device
                _readCancellationTokenSource = new CancellationTokenSource();

                ListenToSerialPort();
            }
            catch (Exception ex)
            {
                throw new Exception($"{ex.Message} -->[WinIotPakcgeManager_Constructor]", ex.InnerException);
            }
        }
        private async Task FindDevice()
        {
            Debug.WriteLine("begintest");
            UInt16 vid = 0x2341;
            UInt16 pid = 0x0001;

            string aqs = SerialDevice.GetDeviceSelectorFromUsbVidPid(vid, pid);

            var myDevices = await DeviceInformation.FindAllAsync(aqs);

            if (myDevices.Count == 0)
            {
                Debug.WriteLine("Device not found!");
                return;
            }

            try
            {
                Debug.WriteLine("testrange");
                Debug.WriteLine(myDevices[0].Id);
                serialPort = await SerialDevice.FromIdAsync(myDevices[0].Id);

                if (serialPort == null)
                {
                    Debug.WriteLine("null2");
                    return;
                }
                Debug.WriteLine("ok");
                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate     = 9600;
                serialPort.Parity       = SerialParity.None;
                serialPort.StopBits     = SerialStopBitCount.One;
                serialPort.DataBits     = 8;
                serialPort.Handshake    = SerialHandshake.None;
                Debug.WriteLine("ok2");

                /*String debugtest = "Serial port configured successfully: ";
                 * debugtest += serialPort.BaudRate + "-";
                 * debugtest += serialPort.DataBits + "-";
                 * debugtest += serialPort.Parity.ToString() + "-";
                 * debugtest += serialPort.StopBits;
                 * debugtest += (DeviceInformation)myDevices[0];
                 *
                 * Debug.WriteLine("debugtest1");
                 * Debug.WriteLine(debugtest);*/
                Debug.WriteLine("debugtest2");
                await Listen();
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.Message.ToString());
                Debug.WriteLine("error");
            }
            finally
            {
                Debug.WriteLine("Opened device for communication.");
            }
            Debug.WriteLine("test2");
        }
        public async Task Initialize()
        {
            var serialSelector = SerialDevice.GetDeviceSelector();
            var serialDevices  = (await DeviceInformation.FindAllAsync(serialSelector)).ToList();
            var hostNames      = NetworkInformation.GetHostNames().Select(hostName => hostName.DisplayName.ToUpper()).ToList(); // So we can ignore inbuilt ports

            foreach (var deviceInfo in serialDevices)
            {
                if (hostNames.FirstOrDefault(hostName => hostName.StartsWith(deviceInfo.Name.ToUpper())) == null)
                {
                    try
                    {
                        var serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);

                        if (serialDevice != null)
                        {
                            _SerialDevices.Add(deviceInfo.Id, serialDevice);
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                }
            }
        }
Exemple #7
0
        private async void SerialPortConfiguration()
        {
            var selection = lstSerialDevices.SelectedItems;

            if (selection.Count <= 0)
            {
                txtMessage.Text = "Select an object for serial connection!";
                return;
            }

            DeviceInformation entry = (DeviceInformation)selection[0];

            try
            {
                serialPort = await SerialDevice.FromIdAsync(entry.Id);

                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate     = 115200;
                serialPort.Parity       = SerialParity.None;
                serialPort.StopBits     = SerialStopBitCount.One;
                serialPort.DataBits     = 8;
                serialPort.Handshake    = SerialHandshake.None;
                txtMessage.Text         = "Serial Port Correctly Configured!";

                ReadCancellationTokenSource = new CancellationTokenSource();

                Listen();
            }

            catch (Exception ex)
            {
                txtMessage.Text = ex.Message;
            }
        }
Exemple #8
0
        public override async Task <bool> Connect(Connection newConnection)
        {
            var deviceInfo = newConnection.Source as DeviceInformation;

            if (deviceInfo != null)
            {
                this.service = await SerialDevice.FromIdAsync(deviceInfo.Id);

                if (this.service == null)
                {
                    return(false);
                }

                this.service.BaudRate  = 115200;
                this.service.StopBits  = SerialStopBitCount.One;
                this.service.Handshake = SerialHandshake.None;
                this.service.DataBits  = 8;

                this.service.ReadTimeout  = TimeSpan.FromSeconds(5);
                this.service.WriteTimeout = TimeSpan.FromSeconds(5);
                this.service.IsDataTerminalReadyEnabled = false;

                return(this.InstrumentSocket(this.service.InputStream, this.service.OutputStream));
            }

            return(false);
        }
        private async Task SetupSerialConnection()
        {
            // get a handle to the serial device specified earlier
            serialPort = await SerialDevice.FromIdAsync(serialDeviceName);

            if (serialPort == null)
            {
                Debug.WriteLine("Oops - cannot connect to serial port");
            }

            Debug.WriteLine("connected to serial port");

            // Configure serial settings
            serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
            serialPort.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
            serialPort.BaudRate     = 9600;
            serialPort.Parity       = SerialParity.None;
            serialPort.StopBits     = SerialStopBitCount.One;
            serialPort.DataBits     = 8;
            serialPort.Handshake    = SerialHandshake.None;

            // Display configured settings
            string status;

            status  = "Serial port configured successfully: ";
            status += serialPort.BaudRate + "-";
            status += serialPort.DataBits + "-";
            status += serialPort.Parity.ToString() + "-";
            status += serialPort.StopBits;
            Debug.WriteLine(status);
        }
Exemple #10
0
        private async void ConnCom_Button_Click(object _, RoutedEventArgs e)
        {
            var devices = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector());

            device_writer = await SerialDevice.FromIdAsync(devices[0].Id);

            device_writer.BaudRate = 57600;
            if (device_writer != null)
            {
                FindDevice_List.Text += $"Connect to  {device_writer.PortName}: {device_writer.BaudRate} \r\n";
            }
            else
            {
                FindDevice_List.Text += $"Connect to  {device_writer.PortName} Failed \r\n";
            }

            /*
             *         device_reader = await SerialDevice.FromIdAsync(devices[1].Id);
             *         if (device_reader != null)
             *         {
             *             FindDevice_List.Text += $"Connect to  {device_reader.PortName}: {device_reader.BaudRate} \r\n";
             *         }
             *         else
             *         {
             *             FindDevice_List.Text += $"Connect to  {device_reader.PortName} Failed \r\n";
             *         }
             */
        }
        /// <summary>
        /// Connects to a serial device.
        /// </summary>
        /// <param name="deviceInfo">The serial device information.</param>
        private async void DeviceConnect(DeviceInformation deviceInfo)
        {
            try {
                // Open serial port
                serialPort = await SerialDevice.FromIdAsync(deviceInfo.Id);

                // Set port settings
                serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate    = DeviceBaudRate;
                serialPort.DataBits    = DeviceDataBits;
                serialPort.StopBits    = DeviceStopBits;
                serialPort.Parity      = DeviceParity;
                serialPort.Handshake   = DeviceHandshake;

                // Update UI to reflect "device connected" state
                serialConnectButton.IsEnabled    = false;
                serialDisconnectButton.IsEnabled = true;
                statusTextBlock.Text             = StatusDeviceConnectSuccess + " " + StatusDeviceWait;

                // Set the cancellation token source
                readCancellationTokenSource = new CancellationTokenSource();

                // Listen on device
                DeviceListen();
            } catch (Exception ex) {
                statusTextBlock.Text             = ex.Message;
                serialPort                       = null;
                serialConnectButton.IsEnabled    = true;
                serialDisconnectButton.IsEnabled = false;
            }
        }
Exemple #12
0
        /// <summary>
        ///     Simple Modbus serial RTU slave example.
        /// </summary>
        public async void StartModbusSerialRtuSlave()

        {
            using (SerialDevice slavePort = await SerialDevice.FromIdAsync("COM2"))

            {
                // configure serial port

                slavePort.BaudRate = 9600;

                slavePort.DataBits = 8;

                slavePort.Parity = SerialParity.None;

                slavePort.StopBits = SerialStopBitCount.One;



                byte unitId = 1;



                var adapter = new SerialPortAdapter(slavePort);

                // create modbus slave

                ModbusSlave slave = ModbusSerialSlave.CreateRtu(unitId, adapter);

                slave.DataStore = DataStoreFactory.CreateDefaultDataStore();



                slave.ListenAsync().GetAwaiter().GetResult();
            }
        }
Exemple #13
0
        public async void GetDevice(string model)
        {
            if (devices == null)
            {
                if (model == "MEGA")
                {
                    string selector = SerialDevice.GetDeviceSelectorFromUsbVidPid(ArduinoDevice.MegaVid, ArduinoDevice.MegaPid);
                    this.devices = await DeviceInformation.FindAllAsync(selector);
                }
                if (model == "UNO")
                {
                    string selector = SerialDevice.GetDeviceSelectorFromUsbVidPid(ArduinoDevice.UnoVid, ArduinoDevice.UnoPid);
                    this.devices = await DeviceInformation.FindAllAsync(selector);
                }
            }
            if (devices.Count > 0)
            {
                try
                {
                    this.deviceInfo   = devices[0];
                    this.serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);

                    this.serialDevice.BaudRate  = 9600;
                    this.serialDevice.Parity    = SerialParity.None;
                    this.serialDevice.StopBits  = SerialStopBitCount.One;
                    this.serialDevice.Handshake = SerialHandshake.None;
                    this.serialDevice.DataBits  = 8;
                }
                finally
                {
                }
            }
        }
        /// <summary>
        /// Initializes _serialGPSDevice based on the DeviceInformation.
        /// </summary>
        /// <param name="DeviceInfo">
        /// The device to be initialized.
        /// </param>
        /// <returns></returns>
        private async Task <SerialPortDevice> InitGPSAsync(DeviceInformation DeviceInfo)
        {
            if (_serialGPSDevice != null && _serialGPSDevice.IsOpen)
            {
                //Close if a device is currently in use.
                CloseAndDisposeSerialGPS();
            }

            SerialDevice serialPort = await SerialDevice.FromIdAsync(DeviceInfo.Id);

            if (serialPort != null)
            {
                serialPort.BaudRate = 4800;
                serialPort.DataBits = 8;
                serialPort.Parity   = SerialParity.None;
                serialPort.StopBits = SerialStopBitCount.One;

                ///IMPORTANT
                ///Makes sure that the serial port parameters are actually set.
                ///https://github.com/dotMorten/NmeaParser/issues/13
                ///
                var _baud = serialPort.BaudRate;
                var _data = serialPort.DataBits;
                var _pair = serialPort.Parity;
                var _stop = serialPort.StopBits;
                ///IMPORTANT

                return(new SerialPortDevice(serialPort));
            }
            return(null);
        }
Exemple #15
0
    private async Task ReconfigurePort(uint baudRate, string deviceId)
    {
        if (serialPort == null)
        {
            serialPort = await SerialDevice.FromIdAsync(deviceId);

            serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
            serialPort.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
            serialPort.BaudRate     = baudRate;
            serialPort.Parity       = SerialParity.None;
            serialPort.StopBits     = SerialStopBitCount.One;
            serialPort.DataBits     = 8;
            serialPort.Handshake    = SerialHandshake.None;
            dataWriteObject         = new DataWriter(serialPort.OutputStream);
        }
        else
        {
            dataWriteObject.DetachStream();
            dataWriteObject.DetachBuffer();
            dataWriteObject.Dispose();
            dataReaderObject.DetachStream();
            dataReaderObject.Dispose();
            serialPort.BaudRate = baudRate;
            dataWriteObject     = new DataWriter(serialPort.OutputStream);
        }
    }
Exemple #16
0
        private async System.Threading.Tasks.Task InitGPIOAsync()
        {
            aqs = SerialDevice.GetDeviceSelector();
            dis = await DeviceInformation.FindAllAsync(aqs);

            using (SerialDevice serialPort = await SerialDevice.FromIdAsync(dis[0].Id))
            {
                /* Configure serial settings */
                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate     = 9600;                                         /* mini UART: only standard baudrates */
                serialPort.Parity       = SerialParity.None;                            /* mini UART: no parities */
                serialPort.StopBits     = SerialStopBitCount.One;                       /* mini UART: 1 stop bit */
                serialPort.DataBits     = 8;

                /* Write a string out over serial */
                // turn on autocalibration
                byte[]     send79Buffer = { 0XFF, 0x01, 0x79, 0xA0, 0x00, 0x00, 0x00, 0x00, 0x79 };
                DataWriter dataWriter   = new DataWriter();
                //dataWriter.WriteString(txBuffer);

                dataWriter.WriteBytes(send79Buffer);

                uint bytesWritten = await serialPort.OutputStream.WriteAsync(dataWriter.DetachBuffer());

                Debug.WriteLine("Autokalibrace vypnuta.");
            }
        }
    public static async void InitializeSerial(ushort vid, ushort pid)
    {
        string aqs       = SerialDevice.GetDeviceSelectorFromUsbVidPid(vid, pid);
        var    myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs, null);

        if (myDevices.Count == 0)
        {
            Debug.Write("No device detected\r\n");
            return;
        }
        else
        {
            try
            {
                Debug.Write("Device connected!\r\n");
                serialDevice = await SerialDevice.FromIdAsync(myDevices[0].Id);

                serialDevice.BaudRate  = 9600;
                serialDevice.StopBits  = SerialStopBitCount.One;
                serialDevice.DataBits  = 8;
                serialDevice.Parity    = SerialParity.None;
                serialDevice.Handshake = SerialHandshake.None;


                Debug.Write(serialDevice.PortName + " open\r\n");
                SendSetupCommands();
            }
            catch
            {
                Debug.Write("No device detected\r\n");
            }

            return;
        }
    }
Exemple #18
0
        /// <summary>
        /// Initialisation du port série
        /// 9600, pas de parité, un bit de stop, 8bits
        /// début de réception
        /// </summary>
        /// <param name="BaudRate"></param>
        /// <returns></returns>
        public async Task Initialise(uint BaudRate)     //NOTE - THIS IS AN ASYNC METHOD!
        {
            try
            {
                // Recherche du port série
                string aqs = SerialDevice.GetDeviceSelector("UART0");
                var    dis = await DeviceInformation.FindAllAsync(aqs);

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

                //Configuration du port série
                //mS before a time-out occurs when a write operation does not finish (default=InfiniteTimeout).
                UartPort.WriteTimeout = TimeSpan.FromMilliseconds(10000);
                //mS before a time-out occurs when a read operation does not finish (default=InfiniteTimeout).
                UartPort.ReadTimeout = TimeSpan.FromMilliseconds(10000);
                UartPort.BaudRate    = 9600;
                UartPort.Parity      = SerialParity.None;
                UartPort.StopBits    = SerialStopBitCount.One;
                UartPort.DataBits    = 8;

                DataReaderObject = new DataReader(UartPort.InputStream);
                DataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
                DataWriterObject = new DataWriter(UartPort.OutputStream);

                // Début de la réception
                StartReceive();
            }
            catch (Exception ex)
            {
                throw new Exception("Uart Initialise Error", ex);
            }
        }
Exemple #19
0
        public async Task InitSerial()
        {
            var devices = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector());

            foreach (var device in devices)
            {
                SerialDevice serialDevice;
                try
                {
                    serialDevice = await SerialDevice.FromIdAsync(device.Id);

                    serialDevice.BaudRate     = 9600;
                    serialDevice.DataBits     = 8;
                    serialDevice.StopBits     = SerialStopBitCount.One;
                    serialDevice.Parity       = SerialParity.None;
                    serialDevice.Handshake    = SerialHandshake.None;
                    serialDevice.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                    serialDevice.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                    serialDevices.Add(serialDevice);
                    dataWriters.Add(new DataWriter(serialDevice.OutputStream));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Serial初期化中のエラー: " + ex.Message);
                    continue;
                }
            }
        }
Exemple #20
0
        // blew up gertbot board, so commenting out
        //private void _gertbot_GertbotInterrupt(object sender, GertbotEventArgs e)
        //{
        //    if (StatusUpdate != null)
        //    {
        //        StatusUpdate(this, new HttpServerStatusArgs(1, "hardware update", 0));
        //    }
        //}

        public async void InitialiseHardware()
        {
            // PI Face intialisation
            await _spiDriver.InitHardware();

            //await _gertbot.InitHardware();

            // bluetooth serial
            string aqs = SerialDevice.GetDeviceSelector();
            DeviceInformationCollection devices_info = await DeviceInformation.FindAllAsync(aqs);

            // making an assumption here that the serial we want is #1
            // this will only work with Windows IOT version Insider Preview Build Number 10556.0
            _serialDevice = await SerialDevice.FromIdAsync(devices_info[0].Id);

            if (_serialDevice != null)
            {
                // Configure serial settings
                _serialDevice.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                _serialDevice.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                _serialDevice.BaudRate     = 115200;
                _serialDevice.Parity       = SerialParity.None;
                _serialDevice.StopBits     = SerialStopBitCount.One;
                _serialDevice.DataBits     = 8;
                _serialDevice.Handshake    = SerialHandshake.None;
                _dw = new DataWriter(_serialDevice.OutputStream);
                _dr = new DataReader(_serialDevice.InputStream);
                _dr.InputStreamOptions = InputStreamOptions.None;

                // start the read thread
                StartReadThread();
            }
            // turn the relay on and power up the motordriver
            SetBitState(MOTOR_POWER, 0);
        }
Exemple #21
0
        public async void Ouvrir()
        {
            Debug.WriteLine("PSERIE " + _infoPeripherique.Name + ", " + _infoPeripherique.Id + "  : Ouvrir()");
            try
            {
                SerialDevice _temp = await SerialDevice.FromIdAsync(_infoPeripherique.Id);

                if (_temp != null)
                {
                    lock (_portSerieLock) { _portSerie = _temp; }
                    Debug.WriteLine("PSERIE " + _infoPeripherique.Name + ", " + _infoPeripherique.Id + "  : Ouvrir()=OK!");
                    _portSerie.BaudRate     = Parametres.Vitesse;
                    _portSerie.Parity       = Parametres.Parite;
                    _portSerie.StopBits     = Parametres.BitsDeStop;
                    _portSerie.DataBits     = Parametres.BitsDeDonnees;
                    _portSerie.Handshake    = Parametres.ControleDeFlux;
                    _portSerie.ReadTimeout  = TimeSpan.FromMilliseconds(Parametres.DureeLectureMs);
                    _portSerie.WriteTimeout = TimeSpan.FromMilliseconds(Parametres.DureeEcritureMs);
                    SurModificationEtat?.Invoke(this, ElementModifie.portOuvert);
                    if (Parametres.DureeLectureMs > 0)
                    {
                        LectureContinue();
                    }
                }
                else
                {
                    Debug.WriteLine("PSERIE " + _infoPeripherique.Name + ", " + _infoPeripherique.Id + "  : Ouvrir()=ECHOUE !");
                }
            }
            catch (Exception ex)
            {
                lock (_portSerieLock) { _portSerie = null; }
                Debug.WriteLine("PSERIE " + _infoPeripherique.Name + ", " + _infoPeripherique.Id + "  : Ouvrir() ERREUR = " + ex.GetType().ToString() + " " + ex.Message);
            }
        }
        public async void Start()
        {
            try
            {
                serialPort = await SerialDevice.FromIdAsync(deviceInfo.Id);

                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(100);
                serialPort.ReadTimeout  = TimeSpan.FromMilliseconds(100);
                serialPort.BaudRate     = 9600;
                serialPort.Parity       = SerialParity.None;
                serialPort.StopBits     = SerialStopBitCount.One;
                serialPort.DataBits     = 8;
                serialPort.Handshake    = SerialHandshake.None;

                cancelToken = new CancellationTokenSource();

                var schedulerForUiContext = TaskScheduler.FromCurrentSynchronizationContext();

                running = true;

                ConfigPort();


                backgroundProcess = Task.Factory.StartNew(delegate { SerialListen(schedulerForUiContext); }, TaskCreationOptions.LongRunning, cancelToken.Token);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <PositionControllerResponse> TryToConnect(string serialDeviceId)
        {
            if (string.IsNullOrWhiteSpace(serialDeviceId))
            {
                this.logger.Error($"'{nameof(serialDeviceId)}' is null, empty or whitespace");
                return(new PositionControllerResponse(PositionControllerStatus.CS_ERR_INVALID_ARGUMENT));
            }

            this.semaphore.WaitOne();

            try
            {
                this.deviceId     = serialDeviceId;
                this.serialDevice = await SerialDevice.FromIdAsync(serialDeviceId);

                if (this.serialDevice == null)
                {
                    this.logger.Error($"'{nameof(serialDeviceId)}' is busy, most likely it is being used by some other application");
                    return(new PositionControllerResponse(PositionControllerStatus.CS_ERR_DEVICE_BUSY));
                }

                this.serialDevice.BaudRate = 230400;
                this.serialDevice.IsDataTerminalReadyEnabled = true;
                this.serialDevice.IsRequestToSendEnabled     = true;
                this.serialDevice.Parity       = SerialParity.None;
                this.serialDevice.StopBits     = SerialStopBitCount.One;
                this.serialDevice.DataBits     = 8;
                this.serialDevice.ReadTimeout  = TimeSpan.FromSeconds(1);
                this.serialDevice.WriteTimeout = TimeSpan.FromSeconds(1);

                using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(1)))
                {
                    Task <IBuffer> readTask = this.serialDevice.InputStream.ReadAsync(this.response.AsBuffer(), RESPONSE_LENGTH, InputStreamOptions.None)
                                              .AsTask(cancellationTokenSource.Token);
                    Task <uint> writeTask = this.serialDevice.OutputStream.WriteAsync(commandsBuffers[PositionControllerCommand.GET_STATUS].AsBuffer())
                                            .AsTask();

                    await Task.WhenAll(writeTask, readTask)
                    .ConfigureAwait(false);
                }

                return(DecodeResponse(this.response));
            }
            catch (TaskCanceledException)
            {
                this.logger.Error($"'{nameof(serialDeviceId)}' get position controller status request timed out");
                DisconnectUnsafe();
                return(new PositionControllerResponse(PositionControllerStatus.CS_ERR_COMMUNICATION_TIMEOUT));
            }
            catch (Exception e)
            {
                this.logger.Error(e, $"unexpected exception while getting '{nameof(serialDeviceId)}' position controller status");
                DisconnectUnsafe();
                return(new PositionControllerResponse(PositionControllerStatus.CS_ERR_UNEXPECTED));
            }
            finally
            {
                this.semaphore.Release();
            }
        }
Exemple #24
0
        internal async Task <SerialDevice> GetSerialDeviceAsync(string identifier, int baudRate, TimeSpan readTimeout, TimeSpan writeTimeout)
        {
            var deviceInformationCollection = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector());

            var selectedPort = deviceInformationCollection.FirstOrDefault(d => d.Id.Contains(identifier) || d.Name.Equals(identifier));

            if (selectedPort == null)
            {
                return(null);
            }

            var serialDevice = await SerialDevice.FromIdAsync(selectedPort.Id);

            if (serialDevice == null)
            {
                return(null);
            }

            serialDevice.ReadTimeout  = readTimeout;
            serialDevice.WriteTimeout = writeTimeout;
            serialDevice.BaudRate     = (uint)baudRate;
            serialDevice.Parity       = SerialParity.None;
            serialDevice.StopBits     = SerialStopBitCount.One;
            serialDevice.DataBits     = 8;
            serialDevice.Handshake    = SerialHandshake.None;

            Debug.WriteLine($"Found - {identifier}");

            return(serialDevice);
        }
Exemple #25
0
        public static async void OpenSerialAsync(string colorValue)
        {
            var selector = SerialDevice.GetDeviceSelector("COM5");
            var devices  = await DeviceInformation.FindAllAsync(selector);

            if (devices.Any())
            {
                var          deviceInfo   = devices.First().Id;
                SerialDevice serialDevice = await SerialDevice.FromIdAsync(deviceInfo);

                if (serialDevice != null)
                {
                    serialDevice.BaudRate  = 9600;
                    serialDevice.DataBits  = 8;
                    serialDevice.StopBits  = SerialStopBitCount.One;
                    serialDevice.Parity    = SerialParity.None;
                    serialDevice.Handshake = SerialHandshake.None;

                    DataWriter dataWriter = new DataWriter(serialDevice.OutputStream);
                    dataWriter.WriteString(colorValue + "\n");
                    await dataWriter.StoreAsync();

                    dataWriter.DetachStream();
                    serialDevice.Dispose();
                }
            }
            else
            {
                MessageDialog popup = new MessageDialog("Sorry, no device found.");
                await popup.ShowAsync();
            }
        }
Exemple #26
0
        public async Task <bool> InitializeConnection()
        {
            var result  = false;
            var filter  = SerialDevice.GetDeviceSelector("UART0");
            var devices = await DeviceInformation.FindAllAsync(filter);

            if (devices.Any())
            {
                var deviceId     = devices.First().Id;
                var serialDevice = await SerialDevice.FromIdAsync(deviceId);

                if (serialDevice != null)
                {
                    serialDevice.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                    serialDevice.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
                    serialDevice.BaudRate     = 9600;
                    serialDevice.StopBits     = SerialStopBitCount.One;
                    serialDevice.DataBits     = 8;
                    serialDevice.Parity       = SerialParity.None;
                    serialDevice.Handshake    = SerialHandshake.None;

                    _reader = new DataReader(serialDevice.InputStream)
                    {
                        InputStreamOptions = InputStreamOptions.Partial
                    };
                    _writer = new DataWriter(serialDevice.OutputStream);

                    result = true;
                }
            }

            return(result);
        }
        //Copied from the below address to connect db 410c using uart1
        //https://docs.microsoft.com/en-us/windows/iot-core/learn-about-hardware/pinmappings/pinmappingsdb
        public async void Serial()
        {
            string aqs = SerialDevice.GetDeviceSelector("UART1");                   /* Find the selector string for the serial device   */
            var    dis = await DeviceInformation.FindAllAsync(aqs);                 /* Find the serial device with our selector string  */

            SerialDevice SerialPort = await SerialDevice.FromIdAsync(dis[0].Id);    /* Create an serial device with our selected device */

            /* Configure serial settings */
            SerialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
            SerialPort.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
            SerialPort.BaudRate     = 9600;
            SerialPort.Parity       = SerialParity.None;
            SerialPort.StopBits     = SerialStopBitCount.One;
            SerialPort.DataBits     = 8;

            /* Write a string out over serial */
            string     txBuffer   = "Hello Serial";
            DataWriter dataWriter = new DataWriter();

            dataWriter.WriteString(txBuffer);
            uint bytesWritten = await SerialPort.OutputStream.WriteAsync(dataWriter.DetachBuffer());

            /* Read data in from the serial port */
            const uint maxReadLength = 1024;
            DataReader dataReader    = new DataReader(SerialPort.InputStream);
            uint       bytesToRead   = await dataReader.LoadAsync(maxReadLength);

            string rxBuffer = dataReader.ReadString(bytesToRead);
        }
Exemple #28
0
        /// <summary>Finds the device and connects to it</summary>
        private static async Task <SerialDevice> GetDevice()
        {
            if (Device == null)
            {
                //It should be the only device that contains "USB"
                var devices = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector());

                var deviceId = devices.FirstOrDefault(x => x.Id.Contains("USB"))?.Id;

                if (deviceId == null)
                {
                    Connected = false;
                    return(null);
                }

                Device = await SerialDevice.FromIdAsync(deviceId);

                if (Device == null)
                {
                    Connected = false;
                    return(null);
                }

                Device.BaudRate     = 115200;
                Device.StopBits     = SerialStopBitCount.One;
                Device.Parity       = SerialParity.None;
                Device.DataBits     = 8;
                Device.Handshake    = SerialHandshake.None;
                Device.ReadTimeout  = TimeSpan.FromMilliseconds(Timeout);
                Device.WriteTimeout = TimeSpan.FromMilliseconds(Timeout);
            }

            Connected = true;
            return(Device);
        }
        public async Task Initialize()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            Device = await SerialDevice.FromIdAsync(DeviceID);

            if (Device == null)
            {
                throw new Exception();
            }

            Device.StopBits     = SerialStopBitCount.Two;
            Device.Parity       = SerialParity.None;
            Device.DataBits     = 8;
            Device.BaudRate     = 9600;
            Device.ReadTimeout  = TimeSpan.FromSeconds(1);
            Device.WriteTimeout = TimeSpan.FromSeconds(1);

            OutputWriter = new DataWriter(Device.OutputStream)
            {
                ByteOrder = ByteOrder.LittleEndian
            };
            InputReader = new DataReader(Device.InputStream)
            {
                ByteOrder = ByteOrder.LittleEndian
            };
        }
Exemple #30
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);
        }