public static void Main()
        {
            // Set GPIO functions for COM2 (this is UART2 on ESP32)
            Configuration.SetPinFunction(Gpio.IO17, DeviceFunction.COM2_TX);
            Configuration.SetPinFunction(Gpio.IO16, DeviceFunction.COM2_RX);

            // Open COM2 and instantiate player
            serialDevice = SerialDevice.FromId("COM2");
            mp3Player    = new YX5300_NF(serialDevice);

            // Start player and play some files
            mp3Player.Begin();
            Thread.Sleep(1000);
            mp3Player.Volume(YX5300_NF.MAX_VOLUME / 2);

#if false
            // Repeat a folder
            mp3Player.PlayFolderRepeat(FOLDER_NUM);
            mp3Player.PlayStart();
#else
            // Repeat a file
            mp3Player.PlayTrackRepeat(FILE_NUM);
            mp3Player.PlayStart();
#endif

            Thread.Sleep(Timeout.Infinite);
        }
Exemple #2
0
        public static void Main()
        {
            // get available ports
            var serialPorts = SerialDevice.GetDeviceSelector();

            Console.WriteLine("available serial ports: " + serialPorts);

            // COM6 in STM32F769IDiscovery board (Tx, Rx pins exposed in Arduino header CN13: TX->D1, RX->D0)

            // open COM
            _serialDevice = SerialDevice.FromId("COM6");

            // set parameters
            _serialDevice.BaudRate  = 38400;
            _serialDevice.Parity    = SerialParity.None;
            _serialDevice.StopBits  = SerialStopBitCount.One;
            _serialDevice.Handshake = SerialHandshake.None;
            _serialDevice.DataBits  = 8;


            // uncomment the scenario to test (!!note that none of these returns!!)

            // uncomment the following call to transmit data
            Scenario2_StreamWrite.Execute(ref _serialDevice);

            // uncomment the following call to read data using a stream reader
            //Scenario3_StreamRead.Execute(ref _serialDevice);

            // uncomment the following call to wait for a data received event
            //Scenario4_DataReceivedEvent.Execute(ref _serialDevice);


            Thread.Sleep(Timeout.Infinite);
        }
Exemple #3
0
        /// <summary>Constructs a new instance.</summary>
        /// <param name="socketNumber">The socket that this module is plugged in to.</param>
        public SerialCameraL1(string ComId)
        {
            port           = SerialDevice.FromId(ComId);
            port.BaudRate  = 115200;
            port.Parity    = SerialParity.None;
            port.StopBits  = SerialStopBitCount.One;
            port.DataBits  = 8;
            port.Handshake = SerialHandshake.None;
            //port.IsDataTerminalReadyEnabled = true;
            //port.IsRequestToSendEnabled = true;
            //socket, 115200, GTI.SerialParity.None, GTI.SerialStopBits.One, 8, GTI.HardwareFlowControl.NotRequired, this
            _outStream   = port.OutputStream;
            _inStream    = port.InputStream;
            SerialReader = new DataReader(port.InputStream);
            SerialWriter = new DataWriter(port.OutputStream);
            //Socket socket = Socket.GetSocket(socketNumber, true, this, null);
            //socket.EnsureTypeIsSupported('U', this);

            //this.port = GTI.SerialFactory.Create(socket, 115200, GTI.SerialParity.None, GTI.SerialStopBits.One, 8, GTI.HardwareFlowControl.NotRequired, this);
            this.port.ReadTimeout  = new TimeSpan(0, 0, 0, 0, 500);
            this.port.WriteTimeout = new TimeSpan(0, 0, 0, 0, 500);
            //this.port.Open();

            this.ResetCamera();

            this.newImageReady   = false;
            this.updateStreaming = false;
            this.paused          = false;
        }
        /// <summary>Constructs a new instance.</summary>
        /// <param name="socketNumber">The socket that this module is plugged in to.</param>
        public MTK3339(string port, int resetPin, int sleepControlPin)
        {
            var serialPorts = SerialDevice.GetDeviceSelector();
            serialDevice = SerialDevice.FromId(port);
            outputDataWriter = new DataWriter(serialDevice.OutputStream);
            //inputDataReader = new DataReader(serialDevice.InputStream);

            //TODO: to make these work properly, look at: https://xbee.codeplex.com/SourceControl/latest#source/XBee.Gadgeteer_42/XBee.cs
            var gpioController = GpioController.GetDefault();
            //this.resetControl = GTI.DigitalOutputFactory.Create(socket, Socket.Pin.Three, ResetState.NotRunning, this);
            this.resetControl = gpioController.OpenPin(resetPin);
            this.resetControl.SetDriveMode(GpioPinDriveMode.Input);
            //this.sleepControl = GTI.DigitalOutputFactory.Create(socket, Socket.Pin.Eight, SleepState.Awaken, this);
            this.sleepControl = gpioController.OpenPin(sleepControlPin);
            this.sleepControl.SetDriveMode(GpioPinDriveMode.Input);


            //if (this.serialPort != null && this.serialPort.IsOpen)
            //    throw new InvalidOperationException("Configure can only be when the port is closed. Call Disable first");


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

            serialDevice.ReadTimeout = new TimeSpan(0, 0, 4);
            serialPort.DataReceived += serialPort_DataReceived;


        }
Exemple #5
0
        private static void InitSensor()
        {
            // Since we only do a read the sensor on COM6 on pin D1 = PC06 = TX and D0 = PC07 = RX

            //Open the port
            _sds011 = SerialDevice.FromId("COM6");

            // Set the usual stuff required for a serial connection
            _sds011.BaudRate  = 9600;
            _sds011.DataBits  = 8;
            _sds011.Parity    = SerialParity.None;
            _sds011.StopBits  = SerialStopBitCount.One;
            _sds011.Handshake = SerialHandshake.None;

            // Timeouts of 5 secs
            _sds011.ReadTimeout = new TimeSpan(0, 0, 5);

            // Reader for the output/input streams
            DataReader reader = new DataReader(_sds011.InputStream);

            // Set a watch for the return character
            _sds011.WatchChar = (char)0xAB;

            // Now register for the data received event
            _sds011.DataReceived += _sds011_DataReceived;
        }
        public static void Main()
        {
            // get available ports
            var serialPorts = SerialDevice.GetDeviceSelector();

            Console.WriteLine("available serial ports: " + serialPorts);

            // COM6 in STM32F769IDiscovery board (Tx, Rx pins exposed in Arduino header CN13: TX->D1, RX->D0)

            // open COM
            _serialDevice = SerialDevice.FromId("COM1");

            // set parameters
            _serialDevice.BaudRate  = 115200;
            _serialDevice.Parity    = SerialParity.None;
            _serialDevice.StopBits  = SerialStopBitCount.One;
            _serialDevice.Handshake = SerialHandshake.None;
            _serialDevice.DataBits  = 8;

            for (; ;)
            {
                Scenario2_StreamWrite.Execute(ref _serialDevice);
                /*Scenario3_StreamRead.Execute(ref _serialDevice);*/
                Thread.Sleep(20);
            }
        }
Exemple #7
0
        // Constructor for serial WiFi
        // Example:  WiFi ESP8266 = new WiFi();
        public WiFi(int UTCLocalTimeOffSet = -5, int CommandDelayMS = 4000, Boolean UseLeds = true)
        {
            // Init LED's
            LEDUser = GpioController.GetDefault().OpenPin(LedUserNumber);
            LEDUser.SetDriveMode(GpioPinDriveMode.Output);

            LED1 = GpioController.GetDefault().OpenPin(Led1Number);
            LED1.SetDriveMode(GpioPinDriveMode.Output);

            LED2 = GpioController.GetDefault().OpenPin(Led2Number);
            LED2.SetDriveMode(GpioPinDriveMode.Output);

            LED3 = GpioController.GetDefault().OpenPin(Led3Number);
            LED3.SetDriveMode(GpioPinDriveMode.Output);

            // COM6 in Netduino 3, STM32F769IDiscovery (Tx, Rx pins exposed in Arduino header TX->D1, RX->D0)
            // Open port
            Port = SerialDevice.FromId("COM6");

            // Used to set date and time in GetTimeFromString
            LocalTimeOffSet = UTCLocalTimeOffSet;

            CommandDelay = CommandDelayMS;

            // set  device parameters
            Port.BaudRate  = 115200;
            Port.Parity    = SerialParity.None;
            Port.StopBits  = SerialStopBitCount.One;
            Port.Handshake = SerialHandshake.None;
            Port.DataBits  = 8;

            // Create new DataWriter
            outputDataWriter = new DataWriter(Port.OutputStream);

            // Updated in ESPDataReceived
            DataReader inputDataReader = new DataReader(Port.InputStream);

            inputDataReader.InputStreamOptions = InputStreamOptions.Partial;

            // Return char
            Port.WatchChar = '\r';

            //  1 Sec
            Port.ReadTimeout = new TimeSpan(0, 0, 1);

            Port.WriteTimeout = new TimeSpan(0, 0, 5);

            // Received event
            Port.DataReceived += ESPDataReceived;
        }
        public static void Main()
        {
            // get available ports
            var serialPorts = SerialDevice.GetDeviceSelector();

            Console.WriteLine("available serial ports: " + serialPorts);

            ///////////////////////////////////////////////////////////////////////////////////////////////////
            // COM6 in STM32F769IDiscovery board (Tx, Rx pins exposed in Arduino header CN13: TX->D1, RX->D0)
            // open COM6
            //_serialDevice = SerialDevice.FromId("COM6");


            ////////////////////////////////////////////////////////////////////////////////////////////////////
            // COM2 in ESP32-WROVER-KIT mapped to free GPIO pins
            // mind to NOT USE pins shared with other devices, like serial flash and PSRAM
            // also it's MANDATORY to set pin funcion to the appropriate COM before instanciating it

            // set GPIO functions for COM2 (this is UART1 on ESP32)
#if BUIID_FOR_ESP32
            //Configuration.SetPinFunction(Gpio.IO04, DeviceFunction.COM2_TX);
            //Configuration.SetPinFunction(Gpio.IO05, DeviceFunction.COM2_RX);
#endif

            // open COM2
            _serialDevice = SerialDevice.FromId("COM2");

            // set parameters
            _serialDevice.BaudRate  = 9600;
            _serialDevice.Parity    = SerialParity.None;
            _serialDevice.StopBits  = SerialStopBitCount.One;
            _serialDevice.Handshake = SerialHandshake.None;
            _serialDevice.DataBits  = 8;

            // uncomment the scenario to test (!!note that none of these returns!!)

            // uncomment the following call to transmit data
            Scenario2_StreamWrite.Execute(ref _serialDevice);

            // uncomment the following call to read data using a stream reader
            Scenario3_StreamRead.Execute(ref _serialDevice);

            // uncomment the following call to wait for a data received event
            //Scenario4_DataReceivedEvent.Execute(ref _serialDevice);


            Thread.Sleep(Timeout.Infinite);
        }
Exemple #9
0
        /// <summary>
        ///   Set which COM port you want to use and what baudrate
        /// </summary>
        /// <param name="Comuart"></param>
        /// <param name="BaudRate"></param>
        public DebugWritelnToUart(string Comuart, uint BaudRate)
        {
#if DEBUG
            uart           = SerialDevice.FromId(Comuart);
            uart.WatchChar = '\n';

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

            uartoutput        = new DataWriter(uart.OutputStream);
            uart.WriteTimeout = new TimeSpan(0, 0, 5);
#endif
        }
        /// <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);
        }
        /// <summary>Initializes the serial port with the parameters 115200 baud, 8N1, with no flow control.</summary>
        public void Configure(string ComId)
        {
            //this.Configure(115200, GTI.SerialParity.None, GTI.SerialStopBits.One, 8, GTI.HardwareFlowControl.NotRequired);
            this.ComId           = ComId;
            serialPort           = SerialDevice.FromId(ComId);
            serialPort.BaudRate  = 115200;
            serialPort.Parity    = SerialParity.None;
            serialPort.StopBits  = SerialStopBitCount.One;
            serialPort.DataBits  = 8;
            serialPort.Handshake = SerialHandshake.None;
            _outStream           = serialPort.OutputStream;
            _inStream            = serialPort.InputStream;
            SerialWriter         = new DataWriter(_outStream);
            SerialReader         = new DataReader(_inStream);

            //this.serialPort.ReadTimeout = new TimeSpan(0, 0, 0, 0, 500);
            //this.serialPort.WriteTimeout = new TimeSpan(0, 0, 0, 0, 500);
        }
Exemple #12
0
        /// <summary>
        /// Construct Bluetooth module
        /// </summary>
        /// <param name="pinStatus">GpioPin Pin 3 of U Socket</param>
        /// <param name="pinReset">GpioPin Pin 6 of U Socket</param>
        /// <param name="uartId">Uart Id of U Socket</param>
        public Bluetooth(int pinStatus, int pinReset, string uartId)
        {
            // This finds the Socket instance from the user-specified socket number. This will generate user-friendly error messages if the socket is invalid. If there is more than one socket on this
            // module, then instead of "null" for the last parameter, put text that identifies the socket to the user (e.g. "S" if there is a socket type S)
            // Socket socket = Socket.GetSocket(socketNumber, true, this, null);

            //this.reset = GTI.DigitalOutputFactory.Create(socket, Socket.Pin.Six, false, this);
            _reset = GpioController.GetDefault().OpenPin(pinReset);
            _reset.SetDriveMode(GpioPinDriveMode.Output);
            _reset.Write(GpioPinValue.Low);

            // this.statusInt = GTI.InterruptInputFactory.Create(socket, Socket.Pin.Three, GTI.GlitchFilterMode.Off, GTI.ResistorMode.Disabled, GTI.InterruptMode.RisingAndFallingEdge, this);
            _statusInt = GpioController.GetDefault().OpenPin(pinStatus);
            _statusInt.SetDriveMode(GpioPinDriveMode.Input);
            _statusInt.DebounceTimeout = TimeSpan.FromMilliseconds(1);

            // this.serialPort = GTI.SerialFactory.Create(socket, 38400, GTI.SerialParity.None, GTI.SerialStopBits.One, 8, GTI.HardwareFlowControl.NotRequired, this);
            _serialPort             = SerialDevice.FromId(uartId);
            _serialPort.BaudRate    = 38400;
            _serialPort.Parity      = SerialParity.None;
            _serialPort.StopBits    = SerialStopBitCount.One;
            _serialPort.Handshake   = SerialHandshake.None;
            _serialPort.ReadTimeout = TimeSpan.MaxValue;

            //this.statusInt.Interrupt += GTI.InterruptInputFactory.Create.InterruptEventHandler(statusInt_Interrupt);
            //           this.serialPort.ReadTimeout = Timeout.Infinite;
            //           this.serialPort.Open();

            _dataReader = new DataReader(_serialPort.InputStream);
            _dataWriter = new DataWriter(_serialPort.OutputStream);

            Thread.Sleep(5);
            _reset.Write(GpioPinValue.High);

            _readerThread = new Thread(RunReaderThread);
            _readerThread.Start();
            Thread.Sleep(500);
        }
Exemple #13
0
        public Esp8266WIFI(GpioPin enablePin, string portId, uint baudRate = 115200)
        {
            enablePin.SetDriveMode(GpioPinDriveMode.Output);
            _enablePin = enablePin;
            _enablePin.Write(GpioPinValue.Low);
            Thread.Sleep(200);
            _enablePin.Write(GpioPinValue.High);
            Thread.Sleep(20);
            _wifi              = SerialDevice.FromId(portId);
            _wifi.BaudRate     = baudRate;
            _wifi.DataBits     = 8;
            _wifi.StopBits     = SerialStopBitCount.One;
            _wifi.Parity       = SerialParity.None;
            _wifi.ReadTimeout  = TimeSpan.FromMilliseconds(1000);
            _wifi.WriteTimeout = TimeSpan.FromMilliseconds(1000);

            _dataReader       = new DataReader(_wifi.InputStream);
            _dataWriter       = new DataWriter(_wifi.OutputStream);
            _connectionWorker = new Thread(ContinouslyReadWifiInput);

            _connectionWorker.Start();
            WriteCommand("AT");
        }
        /// <summary>Constructs a new instance.</summary>
        /// <param name="socketNumber">The socket that this module is plugged in to.</param>
        public PulseOximeter(string ComId) {
            this.IsProbeAttached = false;
            this.LastReading = null;

            //Socket socket = Socket.GetSocket(socketNumber, true, this, null);
            serialPort = SerialDevice.FromId(ComId);
            //this.serialPort = GTI.SerialFactory.Create(socket, 4800, GTI.SerialParity.Even, GTI.SerialStopBits.One, 8, GTI.HardwareFlowControl.NotRequired, this);

            serialPort.BaudRate = 4800;
            serialPort.Parity = SerialParity.Even;
            serialPort.StopBits = SerialStopBitCount.One;
            serialPort.DataBits = 8;
            serialPort.Handshake = SerialHandshake.None;
            _outStream = serialPort.OutputStream;
            _inStream = serialPort.InputStream;
            SerialWriter = new DataWriter(_outStream);
            SerialReader = new DataReader(_inStream);
            //this.serialPort.ReadTimeout = new TimeSpan(0, 0, 0, 0, 500);
            //this.serialPort.WriteTimeout = new TimeSpan(0, 0, 0, 0, 500);
            //this.serialPort.Open();

            this.workerThread = new Thread(this.DoWork);
            this.workerThread.Start();
        }
Exemple #15
0
        private const string Payload      = "48656c6c6f204c6f526157414e"; // Hello LoRaWAN

        public static void Main()
        {
            SerialDevice serialDevice;
            uint         bytesWritten;
            uint         txByteCount;
            uint         bytesRead;

            Debug.WriteLine("devMobile.IoT.Rak811.NetworkJoinABP starting");

            Debug.WriteLine(Windows.Devices.SerialCommunication.SerialDevice.GetDeviceSelector());

            try
            {
                serialDevice = SerialDevice.FromId(SerialPortId);

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

                serialDevice.ReadTimeout  = new TimeSpan(0, 0, 3);
                serialDevice.WriteTimeout = new TimeSpan(0, 0, 4);

                DataWriter outputDataWriter = new DataWriter(serialDevice.OutputStream);
                DataReader inputDataReader  = new DataReader(serialDevice.InputStream);

                // set a watch char to be notified when it's available in the input stream
                serialDevice.WatchChar = '\n';

                // clear out the RX buffer
                bytesRead = inputDataReader.Load(128);
                while (bytesRead > 0)
                {
                    bytesRead = inputDataReader.Load(128);
                    if (bytesRead > 0)
                    {
                        string response = inputDataReader.ReadString(bytesRead);
                        Debug.WriteLine($"RX :{response}");
                    }
                }

                // Set the Working mode to LoRaWAN
                bytesWritten = outputDataWriter.WriteString("at+set_config=lora:work_mode:0\r\n");
                Debug.WriteLine($"TX: work_mode {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    string response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Set the Region to AS923
                bytesWritten = outputDataWriter.WriteString("at+set_config=lora:region:AS923\r\n");
                Debug.WriteLine($"TX: region {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Set the JoinMode to ABP
                bytesWritten = outputDataWriter.WriteString("at+set_config=lora:join_mode:1\r\n");
                Debug.WriteLine($"TX: join_mode {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Set the device address
                bytesWritten = outputDataWriter.WriteString($"at+set_config=lora:dev_addr:{DevAddress}\r\n");
                Debug.WriteLine($"TX: dev_addr {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Set the network session key
                bytesWritten = outputDataWriter.WriteString($"at+set_config=lora:nwks_key:{NwksKey}\r\n");
                Debug.WriteLine($"TX: nwks_key {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Set the application session key
                bytesWritten = outputDataWriter.WriteString($"at+set_config=lora:apps_key:{AppsKey}\r\n");
                Debug.WriteLine($"TX: apps_key {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Set the Confirm flag
                bytesWritten = outputDataWriter.WriteString("at+set_config=lora:confirm:0\r\n");
                Debug.WriteLine($"TX: confirm {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }


                // Join the network
                bytesWritten = outputDataWriter.WriteString("at+join\r\n");
                Debug.WriteLine($"TX: join {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                while (bytesRead == 0)
                {
                    bytesRead = inputDataReader.Load(128);

                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                while (true)
                {
                    bytesWritten = outputDataWriter.WriteString($"at+send=lora:{MessagePort}:{Payload}\r\n");
                    Debug.WriteLine($"TX: send {outputDataWriter.UnstoredBufferLength} bytes to output stream.");

                    // calling the 'Store' method on the data writer actually sends the data
                    txByteCount = outputDataWriter.Store();
                    Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                    bytesRead = inputDataReader.Load(128);
                    if (bytesRead > 0)
                    {
                        String response = inputDataReader.ReadString(bytesRead);
                        Debug.WriteLine($"RX :{response}");
                    }

                    Thread.Sleep(20000);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        private const string Payload = "01020304"; // AQIDBA==
        //private const string Payload = "04030201"; // BAMCAQ==

        public static void Main()
        {
            SerialDevice serialDevice;
            uint         bytesWritten;
            uint         txByteCount;
            uint         bytesRead;

            Debug.WriteLine("devMobile.IoT.SeeedLoRaE5.NetworkJoinOTAA starting");

            Debug.WriteLine($"Ports available: {Windows.Devices.SerialCommunication.SerialDevice.GetDeviceSelector()}");

            try
            {
                serialDevice = SerialDevice.FromId(SerialPortId);

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

                serialDevice.ReadTimeout  = new TimeSpan(0, 0, 5);
                serialDevice.WriteTimeout = new TimeSpan(0, 0, 4);

                DataWriter outputDataWriter = new DataWriter(serialDevice.OutputStream);
                DataReader inputDataReader  = new DataReader(serialDevice.InputStream);

                // set a watch char to be notified when it's available in the input stream
                serialDevice.WatchChar = '\n';

                // clear out the RX buffer
                bytesRead = inputDataReader.Load(128);
                while (bytesRead > 0)
                {
                    string response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");

                    bytesRead = inputDataReader.Load(128);
                }

                // Set the Region to AS923
                bytesWritten = outputDataWriter.WriteString("AT+DR=AS923\r\n");
                Debug.WriteLine($"TX: region {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Set the Join mode
                bytesWritten = outputDataWriter.WriteString("AT+MODE=LWOTAA\r\n");
                Debug.WriteLine($"TX: mode {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    string response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Set the appEUI
                bytesWritten = outputDataWriter.WriteString($"AT+ID=AppEui,\"{AppEui}\"\r\n");
                Debug.WriteLine($"TX: AppEui {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Set the appKey
                bytesWritten = outputDataWriter.WriteString($"AT+KEY=APPKEY,{AppKey}\r\n");
                Debug.WriteLine($"TX: AppKey {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Set the port number
                bytesWritten = outputDataWriter.WriteString($"AT+PORT={MessagePort}\r\n");
                Debug.WriteLine($"TX: port {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response
                bytesRead = inputDataReader.Load(128);
                if (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");
                }

                // Join the network
                bytesWritten = outputDataWriter.WriteString("AT+JOIN\r\n");
                Debug.WriteLine($"TX: join {outputDataWriter.UnstoredBufferLength} bytes to output stream.");
                txByteCount = outputDataWriter.Store();
                Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                // Read the response, need loop as multi line response
                bytesRead = inputDataReader.Load(128);
                while (bytesRead > 0)
                {
                    String response = inputDataReader.ReadString(bytesRead);
                    Debug.WriteLine($"RX :{response}");

                    bytesRead = inputDataReader.Load(128);
                }

                while (true)
                {
                    bytesWritten = outputDataWriter.WriteString($"AT+MSGHEX=\"{Payload}\"\r\n");
                    Debug.WriteLine($"TX: send {outputDataWriter.UnstoredBufferLength} bytes to output stream.");

                    txByteCount = outputDataWriter.Store();
                    Debug.WriteLine($"TX: {txByteCount} bytes via {serialDevice.PortName}");

                    // Read the response, need loop as multi line response
                    bytesRead = inputDataReader.Load(128);
                    while (bytesRead > 0)
                    {
                        String response = inputDataReader.ReadString(bytesRead);
                        Debug.WriteLine($"RX :{response}");

                        bytesRead = inputDataReader.Load(128);
                    }

                    Thread.Sleep(300000);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }