コード例 #1
0
        /// <summary>
        /// Called when receive data has completed.
        /// </summary>
        /// <param name="operation">Data about the async operation.</param>
        /// <param name="status">The status of the operation.</param>
        public void DataReadHandler(IAsyncOperation <uint> operation, AsyncStatus status)
        {
            // If we failed, requeue the data and set the deferral time.
            if (status == AsyncStatus.Error)
            {
                // didn't load data
                Debug.Log("Failed to load new data");
            }
            else
            {
                ax = socketDataReader.ReadSingle();              // Substract the offset of 1 and scale from mm to meters
                bx = socketDataReader.ReadSingle();
                //cx = socketDataReader.ReadSingle();
                ay = socketDataReader.ReadSingle();
                by = socketDataReader.ReadSingle();
                //cy = socketDataReader.ReadSingle();
                //Debug.Log("ax " + ax + " bx " + bx + " cx " + cx + " ay " + ay + " by " + by + " cy " + cy);
                interlock = 1;


                //restart reading data in the input stream async
                DataReaderLoadOperation outstandingRead    = socketDataReader.LoadAsync(4 * 4);
                AsyncOperationCompletedHandler <uint> aoch = new AsyncOperationCompletedHandler <uint>(DataReadHandler);
                outstandingRead.Completed = aoch;
            }
        }
コード例 #2
0
        public void ReadAllText(string filename, Action <string> completed)
        {
            StorageFolder localFolder =
                ApplicationData.Current.LocalFolder;
            IAsyncOperation <StorageFile> createOp =
                localFolder.GetFileAsync(filename);

            createOp.Completed = (asyncInfo1, asyncStatus1) =>
            {
                IStorageFile storageFile = asyncInfo1.GetResults();
                IAsyncOperation <IRandomAccessStreamWithContentType>
                openOp = storageFile.OpenReadAsync();
                openOp.Completed = (asyncInfo2, asyncStatus2) =>
                {
                    IRandomAccessStream stream     = asyncInfo2.GetResults();
                    DataReader          dataReader = new DataReader(stream);
                    uint length = (uint)stream.Size;
                    DataReaderLoadOperation loadOp =
                        dataReader.LoadAsync(length);
                    loadOp.Completed = (asyncInfo3, asyncStatus3) =>
                    {
                        string text = dataReader.ReadString(length);
                        dataReader.Dispose();
                        completed(text);
                    };
                };
            };
        }
コード例 #3
0
    // 开始接收坐标的函数,调用在初始化和一次接收完毕后
    public void RevDetectionsHeaderAsync()
    {
        uint count = 136; // 128 + 4 + 4
        DataReaderLoadOperation operation = reader_receiving.LoadAsync(count);

        operation.Completed = new AsyncOperationCompletedHandler <uint>(HeaderRevd);
    }
コード例 #4
0
    /// <summary>
    /// Called when a connection attempt complete, successfully or not.
    /// </summary>
    /// <param name="asyncInfo">Data about the async operation.</param>
    /// <param name="status">The status of the operation.</param>
    public void SocketOpenedHandler(IAsyncAction asyncInfo, AsyncStatus status)
    {
        // Status completed is successful.
        if (status == AsyncStatus.Completed)
        {
            socketOpen = true;
            Debug.Log("Connected! Ready to send and receive data");
            //socketDataWriter = new DataWriter(socketConnection.OutputStream);
            socketDataReader = new DataReader(socketConnection.InputStream);
            socketDataReader.UnicodeEncoding = UnicodeEncoding.Utf8;
            socketDataReader.ByteOrder       = ByteOrder.LittleEndian;

            //Begin reading data in the input stream async
            DataReaderLoadOperation outstandingRead    = socketDataReader.LoadAsync(4 * 16); // Try to load 53 bytes
            AsyncOperationCompletedHandler <uint> aoch = new AsyncOperationCompletedHandler <uint>(DataReadHandler);
            outstandingRead.Completed = aoch;
        }
        else
        {
            Debug.Log("Failed to establish connection. Error Code: " + asyncInfo.ErrorCode);
            // In the failure case we'll requeue the data and wait before trying again.
            socketConnection.Dispose();
            // Setup a callback function that will retry connection after 2 seconds
            if (!socketOpen)               // Redundant but to be safe
            {
                deferredConnection = true; // Defer the connection attempt
            }
        }
    }
コード例 #5
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);
            }
        }
コード例 #6
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;
                }
            }
        }
コード例 #7
0
        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;
                }
            }
        }
コード例 #8
0
        public void NetworkConnectedHandlerBundles(IAsyncAction asyncInfo, AsyncStatus status)
        {
            //Debug.Log("YOU CONNECTED TO: " + networkConnection.Information.RemoteAddress.ToString());

            // Status completed is successful.
            if (status == AsyncStatus.Completed)
            {
                DataReader networkDataReader;

                // Since we are connected, we can send the data we set aside when establishing the connection.
                using (networkDataReader = new DataReader(holoClient.InputStream)) {
                    Debug.Log("PREPARING TO READ DATA");
                    // Then write the data.
                    byte[] bytes = networkDataReader.ReadBytes();
                    this.networkAssets = AssetBundle.LoadFromMemory(bytes);
                    // Again, this is an async operation, so we'll set a callback.
                    DataReaderLoadOperation drlo = networkDataWriter.LoadAsync();
                    drlo.Completed = new AsyncOperationCompletedHandler <uint>(DataSentHandler);
                }
            }
            else
            {
                Debug.LogWarning("Failed to establish connection. Error Code: " + asyncInfo.ErrorCode);
                // In the failure case we'll requeue the data and wait before trying again.
                holoClient.Dispose();
            }
        }
コード例 #9
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);
        }
コード例 #10
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;
        }
コード例 #11
0
ファイル: TcpTransport.cs プロジェクト: pietpukkel/conversa
 private void StopAsyncReads()
 {
     if (this.asyncRead != null)
     {
         this.asyncRead.Close();
         this.asyncRead = null;
     }
 }
コード例 #12
0
    // 读取136后后执行本函数
    private void HeaderRevd(IAsyncOperation <uint> asyncInfo, AsyncStatus asyncStatus)
    {
        if (asyncStatus == AsyncStatus.Error)
        {
            System.Diagnostics.Debug.WriteLine("读取头部数据错误");
            ResetDraw();
        }
        else
        {
            try
            {
                ResetDraw();
                Matrix4x4 ctw = Matrix4x4.zero;
                for (int i = 0; i < 4; i++)
                {
                    for (int j = 0; j < 4; j++)
                    {
                        ctw[i, j] = reader_receiving.ReadSingle();
                    }
                }

                Matrix4x4 projection = Matrix4x4.zero;
                for (int i = 0; i < 4; i++)
                {
                    for (int j = 0; j < 4; j++)
                    {
                        projection[i, j] = reader_receiving.ReadSingle();
                    }
                }

                num = reader_receiving.ReadInt32();
                uint total_size = reader_receiving.ReadUInt32();
                Debug.Log("---------------------------------------\nHeader Received, num: " + num + " total size: " + total_size + "\nCTW:\n" + ctw.ToString() + "\nProjection:\n" + projection.ToString());
                if (num > 0 && total_size > 0)
                {
                    ShowMsg.UpdateCubeMsg($"识别出{num}个目标");
                    Debug.Log("-------------------------\nnum:" + num + "\n-------------------------");
                    DataReaderLoadOperation drlo = reader_receiving.LoadAsync(total_size);
                    drlo.Completed = new AsyncOperationCompletedHandler <uint>(
                        (op, stat) => DetectionBodyRevHandler(op, stat, num, total_size, ctw, projection)

                        );
                }
                else
                {
                    RevDetectionsHeaderAsync();
                }
            }
            catch (Exception e)
            {
                Debug.Log("There was an error reading the recieved detection header:\n" + e);
                ResetDraw();
            }
        }
    }
コード例 #13
0
        private void LoadCompleted(Windows.Foundation.IAsyncOperation <uint> asyncInfo, Windows.Foundation.AsyncStatus asyncStatus)
        {
            switch (asyncStatus)
            {
            case Windows.Foundation.AsyncStatus.Canceled:
                //logger.AddLog("Data load operation canceled");
                break;

            case Windows.Foundation.AsyncStatus.Completed:
                //logger.AddLog("Data load operation completed");
                if (TcpStreamReader.UnconsumedBufferLength.Equals(0))
                {
                    if (IsSocketConnected)
                    {
                        //logger.AddLog("Connection closed by remote host. Exiting");
                        IsSocketConnected = false;
                        IsConnectionClosedByRemoteHost = true;
                        CloseSocket();
                    }
                }
                else
                {
                    IBuffer buffer = TcpStreamReader.DetachBuffer();
                    RaiseDataReceivedEvent(buffer.ToArray());
                    DataReaderLoadOperation loadOperation = TcpStreamReader.LoadAsync(ReadBufferLength);
                    try
                    {
                        loadOperation.Completed = new Windows.Foundation.AsyncOperationCompletedHandler <UInt32>(LoadCompleted);
                    }
                    catch (Exception e)
                    {
                    }
                }
                break;

            case Windows.Foundation.AsyncStatus.Error:
                //logger.AddLog("Exception in data load operation");
                IsSocketConnected = false;
                if (asyncInfo.ErrorCode.HResult.Equals(-2147014842))
                {
                    IsConnectionClosedByRemoteHost = true;
                }
                else
                {
                    RaiseErrorOccuredEvent(asyncInfo.ErrorCode);
                }
                CloseSocket();
                break;

            case Windows.Foundation.AsyncStatus.Started:
                //logger.AddLog("Data load operation started");
                break;
            }
        }
コード例 #14
0
        /// <summary>
        /// When a connection to the server is established and we can start reading the data, this will be called.
        /// </summary>
        /// <param name="asyncInfo">Info about the connection.</param>
        /// <param name="status">Status of the connection</param>
        private async void RcvNetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status)
        {
            // Status completed is successful.
            if (status == AsyncStatus.Completed)
            {
                DataReader networkDataReader;

                // Since we are connected, we can read the data being sent to us.
                using (networkDataReader = new DataReader(networkConnection.InputStream))
                {
                    // read four bytes to get the size.
                    DataReaderLoadOperation drlo = networkDataReader.LoadAsync(4);
                    while (drlo.Status == AsyncStatus.Started)
                    {
                        // just waiting.
                    }

                    int dataSize = networkDataReader.ReadInt32();
                    if (dataSize < 0)
                    {
                        Debug.Log("Super bad super big data size");
                    }

                    // Need to allocate a new buffer with the dataSize.
                    mostRecentDataBuffer = new byte[dataSize];

                    // Read the data.
                    await networkDataReader.LoadAsync((uint)dataSize);

                    networkDataReader.ReadBytes(mostRecentDataBuffer);

                    // And fire our data ready event.
                    DataReadyEvent?.Invoke(mostRecentDataBuffer);
                }
            }
            else
            {
                Debug.Log("Failed to establish connection for rcv. Error Code: " + asyncInfo.ErrorCode);
                // In the failure case we'll requeue the data and wait before trying again.


                // And set the defer time so the update loop can do the 'Unity things'
                // on the main Unity thread.
                DeferredActionQueue.Enqueue(() =>
                {
                    Invoke("RequestDataRetry", timeToDeferFailedConnections);
                });
            }

            networkConnection.Dispose();
            waitingForConnection = false;
        }
コード例 #15
0
ファイル: TcpTransport.cs プロジェクト: pietpukkel/conversa
        //private BackgroundTaskRegistration task;
        //private StreamSocketListener tcpListener;

        //private void RegisterBackgroundTask()
        //{
        //    var socketTaskBuilder = new BackgroundTaskBuilder();

        //    socketTaskBuilder.Name           = "conversa://xmpp/background-tasks/tcp";
        //    socketTaskBuilder.TaskEntryPoint = "Conversa.Net.Xmpp.Client.Transports.TcpTransport, Conversa.Net.Xmpp";

        //    var trigger = new SocketActivityTrigger();
        //    socketTaskBuilder.SetTrigger(trigger);

        //    this.task = socketTaskBuilder.Register();
        //}

        //private void TransferOwnership()
        //{
        //    this.socket.EnableTransferOwnership(this.task.TaskId, SocketActivityConnectedStandbyAction.Wake);
        //}

        //void IBackgroundTask.Run(IBackgroundTaskInstance taskInstance)
        //{
        //    BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();

        //    //
        //    // TODO: Insert code to start one or more asynchronous methods using the
        //    //       await keyword, for example:
        //    //
        //    // await ExampleMethodAsync();
        //    //

        //    _deferral.Complete();
        //}

        private void BeginReadAsync()
        {
            if (!this.CanRead)
            {
                Debug.WriteLine("The transport state doesn't allow reads");
                return;
            }
            if (this.asyncRead != null && this.asyncRead.Status == AsyncStatus.Started)
            {
                Debug.WriteLine("There is a running read operation");
                return;
            }

            this.asyncRead           = this.reader.LoadAsync(this.ConnectionString.PacketSize);
            this.asyncRead.Completed = new AsyncOperationCompletedHandler <uint>(this.ReadBytes);
        }
コード例 #16
0
            /// <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);
            }
コード例 #17
0
        /// <summary>
        /// Load controller models
        /// </summary>
        /// <param name="args">Spatial Interaction Source</param>
        private async void LoadModel(SpatialInteractionSourceEventArgs args)
        {
            SpatialInteractionSource source = args.State.Source;
            IAsyncOperation <IRandomAccessStreamWithContentType> modelTask = source.Controller.TryGetRenderableModelAsync();

            if (modelTask == null)
            {
                Debug.WriteLine("Model task is null.");
                return;
            }

            while (modelTask.Status == AsyncStatus.Started)
            {
                return;
            }

            IRandomAccessStreamWithContentType modelStream = modelTask.GetResults();

            if (modelStream == null)
            {
                Debug.WriteLine("Model stream is null.");
                return;
            }

            if (modelStream.Size == 0)
            {
                Debug.WriteLine("Model stream is empty.");
                return;
            }

            byte[] fileBytes = new byte[modelStream.Size];

            using (DataReader reader = new DataReader(modelStream))
            {
                DataReaderLoadOperation loadModelOp = reader.LoadAsync((uint)modelStream.Size);

                while (loadModelOp.Status == AsyncStatus.Started)
                {
                    return;
                }

                reader.ReadBytes(fileBytes);
            }

            await this.AsStorageFile(fileBytes, "MotionController.gltf");
        }
コード例 #18
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;
                }
            }
        }
コード例 #19
0
    /// <summary>
    /// Obtain the total length of data
    /// </summary>
    private async Task <int> ReadInputStreamSize(DataReader networkDataReader)
    {
        Task <int> task = new Task <int>(() =>
        {
            // read four bytes to get the size.
            DataReaderLoadOperation loadOperation = networkDataReader.LoadAsync(4);
            while (loadOperation.Status == AsyncStatus.Started)
            {
                // just waiting.
            }

            return(networkDataReader.ReadInt32());
        });

        task.Start();
        return(await task);
    }
コード例 #20
0
        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());
        }
コード例 #21
0
        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());
        }
コード例 #22
0
        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());
        }
コード例 #23
0
        public void Load(string filename)
        {
#if !WINDOWS_PHONE // iOS and Android
            string docsPath = Environment.GetFolderPath(
                Environment.SpecialFolder.Personal);
            string filepath = Path.Combine(docsPath, filename);
            string text     = File.ReadAllText(filepath);

            // Break string into Title and Text.
            int index = text.IndexOf('\n');
            this.Title = text.Substring(0, index);
            this.Text  = text.Substring(index + 1);
#else // Windows Phone
            StorageFolder localFolder =
                ApplicationData.Current.LocalFolder;
            IAsyncOperation <StorageFile> createOp =
                localFolder.GetFileAsync(filename);
            createOp.Completed = (asyncInfo1, asyncStatus1) =>
            {
                IStorageFile storageFile = asyncInfo1.GetResults();
                IAsyncOperation <IRandomAccessStreamWithContentType>
                openOp = storageFile.OpenReadAsync();
                openOp.Completed = (asyncInfo2, asyncStatus2) =>
                {
                    IRandomAccessStream stream     = asyncInfo2.GetResults();
                    DataReader          dataReader = new DataReader(stream);
                    uint length = (uint)stream.Size;
                    DataReaderLoadOperation loadOp =
                        dataReader.LoadAsync(length);
                    loadOp.Completed = (asyncInfo3, asyncStatus3) =>
                    {
                        string text = dataReader.ReadString(length);
                        dataReader.Dispose();

                        // Break string into Title and Text.
                        int index = text.IndexOf('\n');
                        this.Title = text.Substring(0, index);
                        this.Text  = text.Substring(index + 1);
                    };
                };
            };
#endif
        }
コード例 #24
0
        /// <summary>
        /// When a connection to the server is established and we can start reading the data, this will be called.
        /// </summary>
        /// <param name="asyncInfo">Info about the connection.</param>
        /// <param name="status">Status of the connection</param>
        private async void RcvNetworkConnectedHandler(IAsyncAction asyncInfo, AsyncStatus status)
        {
            // Status completed is successful.
            if (status == AsyncStatus.Completed)
            {
                DataReader networkDataReader;

                // Since we are connected, we can read the data being sent to us.
                using (networkDataReader = new DataReader(networkConnection.InputStream))
                {
                    // read four bytes to get the size.
                    DataReaderLoadOperation drlo = networkDataReader.LoadAsync(4);
                    while (drlo.Status == AsyncStatus.Started)
                    {
                        // just waiting.
                    }

                    int dataSize = networkDataReader.ReadInt32();
                    if (dataSize < 0)
                    {
                        Debug.Log("Super bad super big datasize");
                    }

                    // Need to allocate a new buffer with the dataSize.
                    mostRecentDataBuffer = new byte[dataSize];

                    // Read the data.
                    await networkDataReader.LoadAsync((uint)dataSize);

                    networkDataReader.ReadBytes(mostRecentDataBuffer);

                    // And fire our data ready event.
                    dataReadyEvent?.Invoke(mostRecentDataBuffer);
                }
            }
            else
            {
                Debug.Log("Failed to establish connection for rcv. Error Code: " + asyncInfo.ErrorCode);
            }

            networkConnection.Dispose();
            waitingForConnection = false;
        }
コード例 #25
0
        public async Task PrepareSocketAsync()
        {
            streamSocket = new StreamSocket();

            //logger.AddLog(String.Format("Connecting {0} socket at IPAddress: {1}, Port: {2}", SocketName, IpAddress, Port));
            try
            {
                await streamSocket.ConnectAsync(new Windows.Networking.HostName(IpAddress), Port);
            }
            catch (Exception ex)
            {
                //logger.AddLog("Unable to connect to remote connection");
                RaiseErrorOccuredEvent(ex);
                return;
            }
            //logger.AddLog("Connected");
            TcpStreamWriter   = new DataWriter(streamSocket.OutputStream);
            IsSocketConnected = true;
            try
            {
                await Task.Factory.StartNew(stream =>
                {
                    TcpStreamReader = new DataReader((IInputStream)stream);
                    TcpStreamReader.InputStreamOptions = InputStreamOptions.Partial;
                    try
                    {
                        DataReaderLoadOperation loadOperation = TcpStreamReader.LoadAsync(ReadBufferLength);
                        loadOperation.Completed = new Windows.Foundation.AsyncOperationCompletedHandler <UInt32>(LoadCompleted);
                    }
                    catch (Exception ex)
                    {
                        RaiseErrorOccuredEvent(ex);
                    }
                }, streamSocket.InputStream);
            }
            catch
            {
                //logger.AddLog("Asynchronous Read Operation Canceled");
            }
            RaiseSocketConnectedEvent();
        }
コード例 #26
0
ファイル: MyNetworkStream-RT.cs プロジェクト: EnergonV/BestCS
        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);
            }
        }
コード例 #27
0
    /// <summary>
    /// Called when receive data has completed.
    /// </summary>
    /// <param name="operation">Data about the async operation.</param>
    /// <param name="status">The status of the operation.</param>
    public void DataReadHandler(IAsyncOperation <uint> operation, AsyncStatus status)
    {
        // If we failed, requeue the data and set the deferral time.
        if (status == AsyncStatus.Error)
        {
            // didn't load data
            Debug.Log("Failed to load new data");
        }
        else
        {
            // Read from the stream all the entries of the transform Matrix H.
            H.m00 = socketDataReader.ReadSingle();
            H.m01 = socketDataReader.ReadSingle();
            H.m02 = socketDataReader.ReadSingle();
            H.m03 = socketDataReader.ReadSingle();
            H.m10 = socketDataReader.ReadSingle();
            H.m11 = socketDataReader.ReadSingle();
            H.m12 = socketDataReader.ReadSingle();
            H.m13 = socketDataReader.ReadSingle();
            H.m20 = socketDataReader.ReadSingle();
            H.m21 = socketDataReader.ReadSingle();
            H.m22 = socketDataReader.ReadSingle();
            H.m23 = socketDataReader.ReadSingle();
            H.m30 = socketDataReader.ReadSingle();
            H.m31 = socketDataReader.ReadSingle();
            H.m32 = socketDataReader.ReadSingle();
            H.m33 = socketDataReader.ReadSingle();

            objAlg.updatePoseMatrix(H);

            interlock = 1;


            //restart reading data in the input stream async
            DataReaderLoadOperation outstandingRead    = socketDataReader.LoadAsync(4 * 16);
            AsyncOperationCompletedHandler <uint> aoch = new AsyncOperationCompletedHandler <uint>(DataReadHandler);
            outstandingRead.Completed = aoch;
        }
    }
コード例 #28
0
        private IEnumerator LoadControllerModel(InteractionSource source)
        {
            loadingControllers.Add(source.id);

            GameObject controllerModelGameObject;

            if (source.handedness == InteractionSourceHandedness.Left && LeftControllerOverride != null)
            {
                controllerModelGameObject = Instantiate(LeftControllerOverride);
            }
            else if (source.handedness == InteractionSourceHandedness.Right && RightControllerOverride != null)
            {
                controllerModelGameObject = Instantiate(RightControllerOverride);
            }
            else
            {
#if !UNITY_EDITOR
                if (GLTFMaterial == null)
                {
                    Debug.Log("If using glTF, please specify a material on " + name + ".");
                    loadingControllers.Remove(source.id);
                    yield break;
                }

                // This API returns the appropriate glTF file according to the motion controller you're currently using, if supported.
                IAsyncOperation <IRandomAccessStreamWithContentType> modelTask = source.TryGetRenderableModelAsync();

                if (modelTask == null)
                {
                    Debug.Log("Model task is null.");
                    loadingControllers.Remove(source.id);
                    yield break;
                }

                while (modelTask.Status == AsyncStatus.Started)
                {
                    yield return(null);
                }

                IRandomAccessStreamWithContentType modelStream = modelTask.GetResults();

                if (modelStream == null)
                {
                    Debug.Log("Model stream is null.");
                    loadingControllers.Remove(source.id);
                    yield break;
                }

                if (modelStream.Size == 0)
                {
                    Debug.Log("Model stream is empty.");
                    loadingControllers.Remove(source.id);
                    yield break;
                }

                byte[] fileBytes = new byte[modelStream.Size];

                using (DataReader reader = new DataReader(modelStream))
                {
                    DataReaderLoadOperation loadModelOp = reader.LoadAsync((uint)modelStream.Size);

                    while (loadModelOp.Status == AsyncStatus.Started)
                    {
                        yield return(null);
                    }

                    reader.ReadBytes(fileBytes);
                }

                controllerModelGameObject = new GameObject();
                GLTFComponentStreamingAssets gltfScript = controllerModelGameObject.AddComponent <GLTFComponentStreamingAssets>();
                gltfScript.ColorMaterial   = GLTFMaterial;
                gltfScript.NoColorMaterial = GLTFMaterial;
                gltfScript.GLTFData        = fileBytes;

                yield return(gltfScript.LoadModel());
#else
                loadingControllers.Remove(source.id);
                yield break;
#endif
            }

            FinishControllerSetup(controllerModelGameObject, source.handedness.ToString(), source.id);
        }
        private IEnumerator LoadSourceControllerModel(InteractionSource source)
        {
            byte[]     fileBytes;
            GameObject controllerModelGameObject;

            if (GLTFMaterial == null)
            {
                Debug.Log("If using glTF, please specify a material on " + name + ".");
                yield break;
            }

#if !UNITY_EDITOR
            // This API returns the appropriate glTF file according to the motion controller you're currently using, if supported.
            IAsyncOperation <IRandomAccessStreamWithContentType> modelTask = source.TryGetRenderableModelAsync();

            if (modelTask == null)
            {
                Debug.Log("Model task is null; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }

            while (modelTask.Status == AsyncStatus.Started)
            {
                yield return(null);
            }

            IRandomAccessStreamWithContentType modelStream = modelTask.GetResults();

            if (modelStream == null)
            {
                Debug.Log("Model stream is null; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }

            if (modelStream.Size == 0)
            {
                Debug.Log("Model stream is empty; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }

            fileBytes = new byte[modelStream.Size];

            using (DataReader reader = new DataReader(modelStream))
            {
                DataReaderLoadOperation loadModelOp = reader.LoadAsync((uint)modelStream.Size);

                while (loadModelOp.Status == AsyncStatus.Started)
                {
                    yield return(null);
                }

                reader.ReadBytes(fileBytes);
            }
#else
            IntPtr controllerModel = new IntPtr();
            uint   outputSize      = 0;

            if (TryGetMotionControllerModel(source.id, out outputSize, out controllerModel))
            {
                fileBytes = new byte[Convert.ToInt32(outputSize)];

                Marshal.Copy(controllerModel, fileBytes, 0, Convert.ToInt32(outputSize));
            }
            else
            {
                Debug.Log("Unable to load controller models; loading alternate.");
                LoadAlternateControllerModel(source);
                yield break;
            }
#endif

            controllerModelGameObject = new GameObject {
                name = "glTFController"
            };
            controllerModelGameObject.transform.Rotate(0, 180, 0);

            var sceneImporter = new GLTFSceneImporter(
                "",
                new MemoryStream(fileBytes, 0, fileBytes.Length, false, true),
                controllerModelGameObject.transform
                );

            sceneImporter.SetShaderForMaterialType(GLTFSceneImporter.MaterialType.PbrMetallicRoughness, GLTFMaterial.shader);
            sceneImporter.SetShaderForMaterialType(GLTFSceneImporter.MaterialType.KHR_materials_pbrSpecularGlossiness, GLTFMaterial.shader);
            sceneImporter.SetShaderForMaterialType(GLTFSceneImporter.MaterialType.CommonConstant, GLTFMaterial.shader);

            yield return(sceneImporter.Load());

            FinishControllerSetup(controllerModelGameObject, source.handedness, GenerateKey(source));
        }
コード例 #30
0
    private IEnumerator LoadSourceControllerModel(InteractionSource source)
    {
        byte[]     fileBytes;
        GameObject controllerModelGameObject;

        if (GLTFMaterial == null)
        {
            Debug.Log("If using glTF, please specify a material on " + name + ".");
            yield break;
        }

#if !UNITY_EDITOR
        // This API returns the appropriate glTF file according to the motion controller you're currently using, if supported.
        IAsyncOperation <IRandomAccessStreamWithContentType> modelTask = source.TryGetRenderableModelAsync();

        if (modelTask == null)
        {
            Debug.Log("Model task is null; loading alternate.");
            LoadAlternateControllerModel(source);
            yield break;
        }

        while (modelTask.Status == AsyncStatus.Started)
        {
            yield return(null);
        }

        IRandomAccessStreamWithContentType modelStream = modelTask.GetResults();

        if (modelStream == null)
        {
            Debug.Log("Model stream is null; loading alternate.");
            LoadAlternateControllerModel(source);
            yield break;
        }

        if (modelStream.Size == 0)
        {
            Debug.Log("Model stream is empty; loading alternate.");
            LoadAlternateControllerModel(source);
            yield break;
        }

        fileBytes = new byte[modelStream.Size];

        using (DataReader reader = new DataReader(modelStream))
        {
            DataReaderLoadOperation loadModelOp = reader.LoadAsync((uint)modelStream.Size);

            while (loadModelOp.Status == AsyncStatus.Started)
            {
                yield return(null);
            }

            reader.ReadBytes(fileBytes);
        }
#else
        IntPtr controllerModel = new IntPtr();
        uint   outputSize      = 0;

        if (TryGetMotionControllerModel(source.id, out outputSize, out controllerModel))
        {
            fileBytes = new byte[Convert.ToInt32(outputSize)];

            Marshal.Copy(controllerModel, fileBytes, 0, Convert.ToInt32(outputSize));
        }
        else
        {
            Debug.Log("Unable to load controller models; loading alternate.");
            LoadAlternateControllerModel(source);
            yield break;
        }
#endif

        controllerModelGameObject = new GameObject {
            name = "glTFController"
        };
        GLTFComponentStreamingAssets gltfScript = controllerModelGameObject.AddComponent <GLTFComponentStreamingAssets>();
        gltfScript.ColorMaterial   = GLTFMaterial;
        gltfScript.NoColorMaterial = GLTFMaterial;
        gltfScript.GLTFData        = fileBytes;

        yield return(gltfScript.LoadModel());

        FinishControllerSetup(controllerModelGameObject, source.handedness, GenerateKey(source));
    }