Beispiel #1
0
        private async Task PollInputAsync()
        {
            while (_socket != null)
            {
                try
                {
                    DataReaderLoadOperation drlo = _reader.LoadAsync(2);
                    await drlo.AsTask(_tokenSource.Token);

                    short  size = _reader.ReadInt16();
                    byte[] data = new byte[size];

                    drlo = _reader.LoadAsync((uint)size);
                    await drlo.AsTask(_tokenSource.Token);

                    _reader.ReadBytes(data);

                    RaiseDataReceived(data);
                }
                catch (TaskCanceledException)
                {
                    return;
                }
            }
        }
        private async void PollInput(IAsyncAction operation)
        {
            while (_socket != null)
            {
                try
                {
                    DataReaderLoadOperation drlo = _reader.LoadAsync(2);
                    await drlo.AsTask(_tokenSource.Token);

                    short  size = _reader.ReadInt16();
                    byte[] data = new byte[size];

                    drlo = _reader.LoadAsync((uint)size);
                    await drlo.AsTask(_tokenSource.Token);

                    _reader.ReadBytes(data);

                    if (ReportReceived != null)
                    {
                        ReportReceived(this, new ReportReceivedEventArgs {
                            Report = data
                        });
                    }
                }
                catch (TaskCanceledException)
                {
                    return;
                }
            }
        }
Beispiel #3
0
        public bool Receive(int length, out byte[] receiveBuffer)
        {
            receiveBuffer = null;
            uint lengthUnsigned = Convert.ToUInt32(length);

            try {
                _dataReaderOperation = _dataReader.LoadAsync(lengthUnsigned);
                _dataReaderOperation.AsTask().Wait();
                if (_dataReaderOperation.ErrorCode != null)
                {
                    OnErrorOccured(new SocketErrorEventArgs(SocketErrorEventArgs.SocketMethod.Connect, SocketError.GetStatus(_dataReaderOperation.ErrorCode.HResult).ToString()));
                    _dataReaderOperation = null;
                    return(false);
                }

                _dataReaderOperation = null;

                if (_dataReader.UnconsumedBufferLength <= 0)
                {
                    return(true);
                }

                receiveBuffer = new byte[_dataReader.UnconsumedBufferLength];
                _dataReader.ReadBytes(receiveBuffer);
                return(true);
            }
            catch (Exception ex) {
                OnErrorOccured(new SocketErrorEventArgs(SocketErrorEventArgs.SocketMethod.Receive, SocketError.GetStatus(ex.HResult).ToString()));
                ReCreateSocket();
                return(false);
            }
        }
Beispiel #4
0
        private async Task ReadAsync(CancellationToken cancellationToken)
        {
            Task <UInt32> loadAsyncTask;


            readText = string.Empty;
            // Don't start any IO if we canceled the task
            lock (ReadCancelLock)
            {
                cancellationToken.ThrowIfCancellationRequested();

                // Cancellation Token will be used so we can stop the task operation explicitly
                // The completion function should still be called so that we can properly handle a canceled task
                DataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
                readerOperation = DataReaderObject.LoadAsync(ReadBufferLength);

                loadAsyncTask = readerOperation.AsTask(cancellationToken);
            }

            UInt32 bytesRead = await loadAsyncTask;

            if (bytesRead > 0)
            {
                readText         = DataReaderObject.ReadString(bytesRead);
                ReadBytesCounter = bytesRead;
            }
            else
            {
                readText = null;
            }
            rootPage.NotifyUser("Read completed - " + bytesRead.ToString() + " bytes were read", NotifyType.StatusMessage);
        }
Beispiel #5
0
        internal virtual async void BindAsync(StreamSocket socketStream)
        {
            this.ConnectionStatus = ConnectionStatus.Connecting;
            this.streamSocket     = socketStream;
            try
            {
                cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(socketObject.CancellationTokenSource.Token);
                using (DataReader dataReader = new DataReader(socketStream.InputStream))
                {
                    CancellationToken cancellationToken = cancellationTokenSource.Token;
                    //setup
                    cancellationToken.ThrowIfCancellationRequested();
                    dataReader.InputStreamOptions = InputStreamOptions.Partial;
                    this.ConnectionStatus         = ConnectionStatus.Connected;

                    //Send a Hello message across
                    await Parse("Hello" + Environment.NewLine).ConfigureAwait(false);

                    loadOperation = dataReader.LoadAsync(bufferSize);
                    uint bytesAvailable = await loadOperation.AsTask(cancellationToken).ConfigureAwait(false);

                    while (bytesAvailable > 0 && loadOperation.Status == Windows.Foundation.AsyncStatus.Completed)
                    {
                        await streamAccess.WaitAsync().ConfigureAwait(false);

                        if (streamWritePosition == streamReadPosition)
                        {
                            streamReadPosition  = 0;
                            streamWritePosition = 0;
                            memoryStream.SetLength(0);
                        }
                        memoryStream.Position = streamWritePosition;
                        byte[] buffer = dataReader.ReadBuffer(bytesAvailable).ToArray();
                        await memoryStream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

                        streamWritePosition = memoryStream.Position;
                        streamAccess.Release();

                        await ParseStream().ConfigureAwait(false);

                        bytesRead     += bytesAvailable;
                        loadOperation  = dataReader.LoadAsync(bufferSize);
                        bytesAvailable = await loadOperation.AsTask(cancellationToken).ConfigureAwait(false);
                    }
                    dataReader.DetachBuffer();
                    dataReader.DetachStream();
                }
            }
            catch (TaskCanceledException) { }
            catch (Exception exception)
            {
                socketObject.ConnectionStatus = ConnectionStatus.Failed;
                Debug.WriteLine(string.Format("Error receiving data: {0}", exception.Message));
            }
            await socketObject.CloseSession(this.sessionId).ConfigureAwait(false);

            this.ConnectionStatus   = ConnectionStatus.Disconnected;
            this.OnMessageReceived -= socketObject.Instance_OnMessageReceived;
        }
            /// <summary>
            /// Blocking read implementation
            /// </summary>
            /// <param name="socket"></param>
            /// <param name="size"></param>
            /// <returns></returns>
            public byte[] ReadBlocking(Connection c, uint size)
            {
                try
                {
                    // determine number of bytes to load, if any
                    byte[] res = null;

                    if (size > c.input.UnconsumedBufferLength)
                    {
                        uint len = size - c.input.UnconsumedBufferLength;

                        var t = Task <uint> .Run(async() =>
                        {
                            DataReaderLoadOperation read = c.input.LoadAsync(len);
                            return(await read.AsTask <uint>(this.cts.Token));
                        });

                        t.Wait();
                        if (t.Status == TaskStatus.RanToCompletion)
                        {
                            if (t.Result > 0)
                            {
                                res = new byte[size];
                                for (var i = 0; i < res.Length; i++)
                                {
                                    res[i] = c.input.ReadByte();
                                }
                            }
                        }
                        return(res);
                    }

                    res = new byte[size];
                    for (var i = 0; i < res.Length; i++)
                    {
                        res[i] = c.input.ReadByte();
                    }

                    return(res);
                }
                catch (Exception e)
                {
                    OneWireEventSource.Log.Debug("ReadBlocking(): " + e.ToString());
                }

                return(null);
            }
        public float GetCurrentTime()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            OutputWriter.WriteByte(2);
            DataWriterStoreOperation WriteOperation = OutputWriter.StoreAsync();

            WriteOperation.AsTask().Wait();

            DataReaderLoadOperation ReadOperation = InputReader.LoadAsync(4);

            ReadOperation.AsTask().Wait();
            return(InputReader.ReadSingle());
        }
        public (float TimeStamp, float BMPValue) GetFirstEntry()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            OutputWriter.WriteByte(1);
            DataWriterStoreOperation WriteOperation = OutputWriter.StoreAsync();

            WriteOperation.AsTask().Wait();

            DataReaderLoadOperation ReadOperation = InputReader.LoadAsync(8);

            ReadOperation.AsTask().Wait();
            return(InputReader.ReadSingle(), InputReader.ReadSingle());
        }
        public ushort GetEntryCount()
        {
            if (Disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            OutputWriter.WriteByte(0);
            DataWriterStoreOperation WriteOperation = OutputWriter.StoreAsync();

            WriteOperation.AsTask().Wait();

            DataReaderLoadOperation ReadOperation = InputReader.LoadAsync(2);

            ReadOperation.AsTask().Wait();
            return(InputReader.ReadUInt16());
        }
Beispiel #10
0
        public async Task <int> Read(byte[] buffer, int offset, int count)
        {
            if (serial == null)
            {
                return(-1);
            }

            try
            {
                uint ReadBufferLength = 1024;
                dataReaderObject = new DataReader(serial.InputStream);
                dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;

                CancellationTokenSource cts = new CancellationTokenSource(2000); // cancel after 5000ms
                DataReaderLoadOperation op  = dataReaderObject.LoadAsync(ReadBufferLength);
                uint bytesAvailable         = await op.AsTask <uint>(cts.Token);

                Debug.WriteLine("get data from  serial port {1} ,length is : {0} \r\n", bytesAvailable, serial.PortName);

                if (bytesAvailable <= 0)
                {
                    return(-1);
                }

                byte[] dataReceived = new byte[bytesAvailable];
                dataReaderObject.ReadBytes(dataReceived);

                Array.Copy(dataReceived, buffer, (int)bytesAvailable);

                return((int)bytesAvailable);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("error , get data to serial port \r\n");
                return(-1);  //数据接收失败
            }
            finally
            {
                // Cleanup once complete
                if (dataReaderObject != null)
                {
                    dataReaderObject.DetachStream();
                    dataReaderObject = null;
                }
            }
        }
Beispiel #11
0
        public override int Read(byte[] buffer, int offset, int count)
        {
            dataReader.InputStreamOptions = InputStreamOptions.Partial;

            try
            {
                CancellationTokenSource cts  = new CancellationTokenSource(readTimeout);
                DataReaderLoadOperation op   = dataReader.LoadAsync((uint)count);
                Task <uint>             read = op.AsTask <uint>(cts.Token);
                read.Wait();
                // here we need to put the bytes read into the buffer
                dataReader.ReadBuffer(read.Result).CopyTo(0, buffer, offset, (int)read.Result);
                return((int)read.Result);
            }
            catch (TaskCanceledException)
            {
                streamSocket.Dispose();
                streamSocket = null;
                throw new TimeoutException(Resources.Timeout);
            }
        }
Beispiel #12
0
#pragma warning disable 1998
        /// <summary>
        /// Helper to read the information into a buffer.
        /// </summary>
        private async Task <Tuple <string, int> > ReadIntoBufferAsync(StreamSocket socket)
        {
            DataReaderLoadOperation loadTask = null;
            string data;

            try
            {
                var reader = new DataReader(socket.InputStream);
                // Set the DataReader to only wait for available data
                reader.InputStreamOptions = InputStreamOptions.Partial;

                loadTask = reader.LoadAsync(0xffff);
                bool succeeded = loadTask.AsTask().Wait(20000);
                if (!succeeded)
                {
                    throw new TimeoutException("Timed out long polling, re-trying.");
                }

                var count = loadTask.GetResults();
                if (count == 0)
                {
                    throw new Exception("No results loaded from reader.");
                }

                data = reader.ReadString(count);
                if (data == null)
                {
                    throw new Exception("ReadString operation failed.");
                }
            }
            catch (TimeoutException ex)
            {
                Debug.WriteLine(ex.Message);
                if (loadTask != null && loadTask.Status == Windows.Foundation.AsyncStatus.Started)
                {
                    loadTask.Cancel();
                }
                return(null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("[Error] Signaling: Failed to read from socket. " + ex.Message);
                if (loadTask != null && loadTask.Status == Windows.Foundation.AsyncStatus.Started)
                {
                    loadTask.Cancel();
                }
                return(null);
            }

            int  content_length = 0;
            bool ret            = false;
            int  i = data.IndexOf("\r\n\r\n");

            if (i != -1)
            {
                Debug.WriteLine("Signaling: Headers received [i=" + i + " data(" + data.Length + ")" /*=" + data*/ + "]");
                if (GetHeaderValue(data, false, "\r\nContent-Length: ", out content_length))
                {
                    int total_response_size = (i + 4) + content_length;
                    if (data.Length >= total_response_size)
                    {
                        ret = true;
                    }
                    else
                    {
                        // We haven't received everything.  Just continue to accept data.
                        Debug.WriteLine("[Error] Singaling: Incomplete response; expected to receive " + total_response_size + ", received" + data.Length);
                    }
                }
                else
                {
                    Debug.WriteLine("[Error] Signaling: No content length field specified by the server.");
                }
            }
            return(ret ? Tuple.Create(data, content_length) : null);
        }
        /// <summary>
        /// read with timeout implementation
        /// </summary>
        /// <param name="size"></param>
        /// <returns>byte[]</returns>
        public virtual byte[] readWithTimeout(uint size)
        {
            try
            {
                // determine number of bytes to load, if any
                byte[] res = null;

                if (size > reader.UnconsumedBufferLength)
                {
                    uint len = size - reader.UnconsumedBufferLength;

                    var t = Task <uint> .Run(async() =>
                    {
                        CancellationTokenSource cts  = new CancellationTokenSource(1000);
                        DataReaderLoadOperation read = reader.LoadAsync(len);
                        return(await read.AsTask <uint>(cts.Token));
                    });

                    t.Wait();
                    if (t.Status == TaskStatus.RanToCompletion)
                    {
                        if (t.Result > 0)
                        {
                            res = new byte[size];
                            for (var i = 0; i < size; i++)
                            {
                                if (reader.UnconsumedBufferLength > 0)
                                {
                                    res[i] = reader.ReadByte();
                                }
                                else
                                {
                                    byte[] tmp = new byte[i + 1];
                                    Array.Copy(res, 0, tmp, 0, i + 1);
                                    return(tmp);
                                }
                            }
                            //debug.Debug.debug(serialPort.PortName + " Rx", result);
                            //OneWireEventSource.Log.Debug(serialPort.PortName + " Rx: " + com.dalsemi.onewire.utils.Convert.toHexString(result, " "));
                        }
                    }
                    return(res);
                }

                res = new byte[size];
                for (var i = 0; i < size; i++)
                {
                    if (reader.UnconsumedBufferLength > 0)
                    {
                        res[i] = reader.ReadByte();
                    }
                    else
                    {
                        byte[] tmp = new byte[i + 1];
                        Array.Copy(res, 0, tmp, 0, i + 1);
                        return(tmp);
                    }
                }
                //debug.Debug.debug(serialPort.PortName + " Rx", result);
                //OneWireEventSource.Log.Debug(serialPort.PortName + " Rx: " + com.dalsemi.onewire.utils.Convert.toHexString(result, " "));

                return(res);
            }
            catch (System.Threading.Tasks.TaskCanceledException e)
            {
                OneWireEventSource.Log.Debug("readWithTimeout() Timeout!\r\n" + e.ToString());
            }
            catch (Exception e)
            {
                OneWireEventSource.Log.Debug("readWithTimeout(): " + e.ToString());
            }

            return(null);
        }