Пример #1
0
        private void ReadDataFromSerialPort()
        {
            lock (buffer)
            {
                int amount = serialPort.Read(staticBuffer, 0, MAXIMUM_BUFFER_SIZE);
                // var bytesReceived = serialPort.Read(rxBuffer, 0, e.Count);
                //Console.WriteLine($"Data amount: {amount}");

                if (amount > 0)
                {
                    for (var index = 0; index < amount; index++)
                    {
                        buffer += (char)staticBuffer[index];
                    }
                }
                var eolMarkerPosition = buffer.IndexOf(LINE_END);

                while (eolMarkerPosition >= 0)
                {
                    var line = buffer.Substring(0, eolMarkerPosition);
                    buffer            = buffer.Substring(eolMarkerPosition + 2);
                    eolMarkerPosition = buffer.IndexOf(LINE_END);

                    // Console.WriteLine($"Line: {line}");

                    OnLineReceived?.Invoke(this, line);
                }
            }
        }
Пример #2
0
            /// <summary>
            ///     Reads all immediately available bytes, as binary data, in both the stream and the input buffer of the SerialPort
            ///     object.
            /// </summary>
            /// <returns>
            ///    System.Byte[]
            /// </returns>
            internal Byte[] ReadExistingBinary()
            {
                Int32 arraySize = _serial.BytesToRead;

                Byte[] received = new Byte[arraySize];
                _serial.Read(received, 0, arraySize);
                return(received);
            }
Пример #3
0
        public static void Main()
        {
            Debug.WriteLine("devMobile.IoT.Rak811.ShieldSerial starting");

            try
            {
                serialDevice = UartController.FromName(SerialPortId);

                serialDevice.SetActiveSettings(new UartSetting()
                {
                    BaudRate    = 9600,
                    Parity      = UartParity.None,
                    StopBits    = UartStopBitCount.One,
                    Handshaking = UartHandshake.None,
                    DataBits    = 8
                });

                serialDevice.Enable();

#if SERIAL_ASYNC_READ
                serialDevice.DataReceived += SerialDevice_DataReceived;
#endif

                while (true)
                {
                    byte[] txBuffer = UTF8Encoding.UTF8.GetBytes(ATCommand);

                    int txByteCount = serialDevice.Write(txBuffer);
                    Debug.WriteLine($"TX: {txByteCount} bytes");

#if SERIAL_SYNC_READ
                    while (serialDevice.BytesToWrite > 0)
                    {
                        Debug.WriteLine($" BytesToWrite {serialDevice.BytesToWrite}");
                        Thread.Sleep(100);
                    }

                    int rxByteCount = serialDevice.BytesToRead;
                    if (rxByteCount > 0)
                    {
                        byte[] rxBuffer = new byte[rxByteCount];

                        serialDevice.Read(rxBuffer);

                        Debug.WriteLine($"RX sync:{rxByteCount} bytes read");
                        String response = UTF8Encoding.UTF8.GetString(rxBuffer);
                        Debug.WriteLine($"RX sync:{response}");
                    }
#endif

                    Thread.Sleep(20000);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Пример #4
0
        private void Sp_DataReceived(UartController sender, GHIElectronics.TinyCLR.Devices.Uart.DataReceivedEventArgs e)
        {
            var nb  = _sp.BytesToRead;
            var buf = new Byte[nb];

            _sp.Read(buf, 0, nb);
            DataReceivedEventHandler tempEvent = DataReceived;

            tempEvent(this, new DataReceivedEventArgs(buf, nb));
        }
Пример #5
0
        private void Sp_DataReceived(UartController sender, DataReceivedEventArgs e)
        {
            var nb  = _sp.BytesToRead;
            var buf = new Byte[nb];

            _sp.Read(buf, 0, nb);

            SpeakUpEventHandler speakEvent = SpeakDetected;

            speakEvent(this, new SpeakUpEventArgs(buf[0]));
        }
Пример #6
0
        private static void SerialDevice_DataReceived(UartController sender, DataReceivedEventArgs e)
        {
            byte[] rxBuffer = new byte[e.Count];

            sender.Read(rxBuffer, 0, e.Count);

            Debug.WriteLine($"RX Async:{e.Count} bytes read");
            String response = UTF8Encoding.UTF8.GetString(rxBuffer);

            Debug.WriteLine($"RX Async:{response}");
        }
Пример #7
0
        private void Gnss_DataReceived(UartController sender, DataReceivedEventArgs e)
        {
            var btr = _gnss.BytesToRead;

            while (btr != 0)
            {
                var _buffer = new Byte[btr];
                _gnss.Read(_buffer, 0, btr);
                _sl.Add(_buffer);
                _buffer = null;
                btr     = _gnss.BytesToRead;
            }
        }
Пример #8
0
        private byte[] ReadExistingBinary()
        {
            int arraySize = _port.BytesToRead;

            byte[] received = new byte[arraySize];

            _port.Read(received, 0, arraySize);
            if (_enableVerboseOutput)
            {
                Dump("RECV:", received);
            }

            return(received);
        }
Пример #9
0
        protected int ReadFrameSegment(int segmentLength, byte[] frameBuffer, int frameAddress)
        {
            RunCommand(Command.READ_FBUF,
                       new byte[] { 0x0, 0x0A,
                                    (byte)((frameAddress >> 24) & 0xFF), (byte)((frameAddress >> 16) & 0xFF), (byte)((frameAddress >> 8) & 0xFF), (byte)(frameAddress & 0xFF),
                                    (byte)((segmentLength >> 24) & 0xFF), (byte)((segmentLength >> 16) & 0xFF), (byte)((segmentLength >> 8) & 0xFF), (byte)(segmentLength & 0xFF),
                                    (byte)((CameraDelayMilliSec >> 8) & 0xFF), (byte)(CameraDelayMilliSec & 0xFF) }, 5);

            var totalBytesRead = 0;

            while (segmentLength > 0)
            {
                if (WaitForIncomingData(GetTimeoutMilliSec(segmentLength)) == false)
                {
                    throw new ApplicationException("Timeout");
                }
                var bytesToRead = System.Math.Min(_serialPort.BytesToRead, segmentLength);
                var bytesRead   = _serialPort.Read(frameBuffer, 0, bytesToRead);
                segmentLength  -= bytesRead;
                totalBytesRead += bytesRead;
            }

            return(totalBytesRead);
        }
Пример #10
0
        //private void PortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
        //{

        //    if (serialDataReceivedEventArgs.EventType == SerialData.Chars)
        //    {
        //        // Keep doing this while there are bytes to read - don't rely on just event notification
        //        // The ESP8266 is very timing sensitive and subject to buffer overrun - keep the loop tight.
        //        var newInput = ReadExistingBinary();
        //        if (newInput != null && newInput.Length > 0)
        //        {
        //            _buffer.Put(newInput);
        //        }

        //        ProcessBufferedInput();
        //    }
        //}

        private void _port_DataReceived(UartController sender, DataReceivedEventArgs e)
        {
            byte[] newInput      = new byte[sender.BytesToRead];
            int    bytesReceived = 0;

            if (sender.BytesToRead > 0)
            {
                bytesReceived = sender.Read(newInput, 0, sender.BytesToRead);
            }

            if (bytesReceived > 0)
            {
                _buffer.Put(newInput);
            }

            ProcessBufferedInput();
        }
Пример #11
0
        private void SerialPort_DataReceived(UartController sender, DataReceivedEventArgs e)
        {
            var bytesReceived = serialPort.Read(rxBuffer, 0, e.Count);
            var msg           = Encoding.UTF8.GetString(rxBuffer, 0, bytesReceived);

            if (msg.IndexOf("\r\n") > -1)
            {
                var msgs = Regex.Split(msg, "\r\n", RegexOptions.IgnoreCase);
                ReadBuffer += msgs[0];
                nmeaProcessor?.ProcessNmeaMessage(ReadBuffer.Trim());
                ReadBuffer = msgs[1];
            }
            else
            {
                ReadBuffer += msg;
            }
            Debug.WriteLine($"Message arrived:{msg}");
        }
Пример #12
0
        private static void Serial_DataReceived(UartController sender, DataReceivedEventArgs e)
        {
            var data  = new byte[serial.BytesToRead];
            var count = serial.Read(data);

            for (var i = 0; i < count; i++)
            {
                var s = new string((char)data[i], 1);
                screen.DrawString(s, font, new SolidBrush(Color.Teal), cx, cy);
                cx += 6;
                if (cx > 150)
                {
                    cx  = 0;
                    cy += 8;
                    if (cy > 110)
                    {
                        cx = 0;  cy = 0;
                        screen.Clear(Color.Black);
                    }
                }
            }
            screen.Flush();
        }
        private void SerialDevice_DataReceived(UartController sender, DataReceivedEventArgs e)
        {
            if (e.Count == 0)
            {
                return;
            }

            byte[] rxBuffer = new byte[e.Count];

            // read all available bytes from the Serial Device input stream
            sender.Read(rxBuffer, 0, e.Count);

            response.Append(UTF8Encoding.UTF8.GetString(rxBuffer));

            int eolPosition;

            do
            {
                // extract a line
                eolPosition = response.ToString().IndexOf(EndOfLineMarker);

                if (eolPosition != -1)
                {
                    string line = response.ToString(0, eolPosition);
                    response = response.Remove(0, eolPosition + EndOfLineMarker.Length);
#if DIAGNOSTICS
                    Debug.WriteLine($" Line :{line} ResponseExpected:{atCommandExpectedResponse} Response:{response}");
#endif
                    int errorIndex = line.IndexOf(ErrorMarker);
                    if (errorIndex != -1)
                    {
                        string errorNumber = line.Substring(errorIndex + ErrorMarker.Length);

                        result = ModemErrorParser(errorNumber.Trim());
                        atExpectedEvent.Set();
                    }

                    if (atCommandExpectedResponse != string.Empty)
                    {
                        int successIndex = line.IndexOf(atCommandExpectedResponse);
                        if (successIndex != -1)
                        {
                            result = Result.Success;
                            atExpectedEvent.Set();
                        }
                    }

                    int receivedMessageIndex = line.IndexOf(ReplyMarker);
                    if (receivedMessageIndex != -1)
                    {
                        string[] fields = line.Split("=,:".ToCharArray());

                        int port   = int.Parse(fields[1]);
                        int rssi   = int.Parse(fields[2]);
                        int snr    = int.Parse(fields[3]);
                        int length = int.Parse(fields[4]);

                        if (this.OnMessageConfirmation != null)
                        {
                            OnMessageConfirmation(rssi, snr);
                        }
                        if (length > 0)
                        {
                            string payload = fields[5];

                            if (this.OnReceiveMessage != null)
                            {
                                OnReceiveMessage(port, rssi, snr, payload);
                            }
                        }
                    }
                }
            }while (eolPosition != -1);
        }
Пример #14
0
        private void SerialDevice_DataReceived(UartController sender, DataReceivedEventArgs e)
        {
            if (e.Count == 0)
            {
                return;
            }

            try
            {
                byte[] rxBuffer = new byte[e.Count];

                // read all available bytes from the Serial Device input stream
                sender.Read(rxBuffer, 0, e.Count);

                response.Append(UTF8Encoding.UTF8.GetString(rxBuffer));

                int eolPosition;
                do
                {
                    // extract a line
                    eolPosition = response.ToString().IndexOf(EndOfLineMarker);

                    if (eolPosition != -1)
                    {
                        string line = response.ToString(0, eolPosition);

                        response = response.Remove(0, eolPosition + EndOfLineMarker.Length);
#if DIAGNOSTICS
                        Debug.WriteLine($" Line :{line} ResponseExpected:{atCommandExpectedResponse} Response:{response}");
#endif
                        int joinFailIndex = line.IndexOf(JoinFailedMarker);
                        if (joinFailIndex != -1)
                        {
                            result = Result.JoinFailed;
                            atExpectedEvent.Set();
                        }

                        int errorIndex = line.IndexOf(ErrorMarker);
                        if (errorIndex != -1)
                        {
                            string errorNumber = line.Substring(errorIndex + ErrorMarker.Length);

                            result = ModemErrorParser(errorNumber.Trim());
                            atExpectedEvent.Set();
                        }

                        if (atCommandExpectedResponse != string.Empty)
                        {
                            int successIndex = line.IndexOf(atCommandExpectedResponse);
                            if (successIndex != -1)
                            {
                                result = Result.Success;
                                atExpectedEvent.Set();
                            }
                        }

                        // If a downlink message payload then stored ready for metrics
                        if ((line.IndexOf(DownlinkPayloadMarker) != -1) || (line.IndexOf(DownlinkConfirmedPayloadMarker) != -1))
                        {
                            string receivedMessageLine = line.Substring(DownlinkPayloadMarker.Length);

                            string[] fields = receivedMessageLine.Split(':', ';');
                            DownlinkPort    = byte.Parse(fields[0]);
                            DownlinkPayload = fields[2].Trim(' ', '"');
                        }

                        //
                        if ((line.IndexOf(DownlinkMetricsMarker) != -1) || (line.IndexOf(DownlinkConfirmedMetricsMarker) != -1))
                        {
                            string receivedMessageLine = line.Substring(DownlinkMetricsMarker.Length);

                            string[] fields = receivedMessageLine.Split(' ', ',');
                            int      rssi   = int.Parse(fields[3]);
                            double   snr    = double.Parse(fields[6]);

                            if (DownlinkPort != 0)
                            {
                                if (this.OnReceiveMessage != null)
                                {
                                    OnReceiveMessage(DownlinkPort, rssi, snr, DownlinkPayload);
                                }
                                DownlinkPort = 0;
                            }

                            if (line.IndexOf(DownlinkConfirmedMetricsMarker) != -1)
                            {
                                if (this.OnMessageConfirmation != null)
                                {
                                    OnMessageConfirmation(rssi, snr);
                                }
                            }
                        }
                    }
                }while (eolPosition != -1);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"SerialDevice_DataReceived {ex.Message}");
                response.Clear();
                result = Result.Undefined;
                atExpectedEvent.Set();
            }
        }