Esempio n. 1
0
        public async Task <string> ReadStringFromDevice(char stopAt, int maxSeconds)
        {
            byte[] buffer = new byte[1024]; // buffer store for the stream
            int    bytes;                   // bytes returned from read()
            string message = readString;

            if (!_socket.InputStream.CanRead)
            {
                return("");
            }

            try
            {
                DataInputStream mmInStream = new DataInputStream(_socket.InputStream);

                System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();
                TimeSpan maxTime = new TimeSpan(0, 0, maxSeconds);
                while (true)
                {
                    // Delay for 0.1 seconds
                    Thread.Sleep(100);

                    // Read from input string
                    buffer = new byte[1024];
                    bytes  = await mmInStream.ReadAsync(buffer);

                    string chunck = Encoding.ASCII.GetString(buffer, 0, bytes);

                    if (chunck.Contains(stopAt))
                    {
                        int index = chunck.IndexOf(stopAt) + 1;
                        message += chunck.Substring(0, index);

                        if (index < chunck.Length)
                        {
                            readString = chunck.Substring(index);
                        }
                        else
                        {
                            readString = "";
                        }
                        return(message);
                    }
                    else
                    {
                        message += chunck;
                    }

                    if (stopWatch.Elapsed == maxTime)
                    {
                        message = "";
                        stopWatch.Stop();
                        break;
                    }
                }
                stopWatch.Stop();
            }
            catch
            {
                return(message);
            }

            return(message);
        }