ReadByte() public method

public ReadByte ( ) : byte
return byte
コード例 #1
0
        /// <summary>
        /// Reads a 16-bit unsigned integer
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private static long readUint16TI(DataReader reader)
        {
            uint ObjLSB = reader.ReadByte();
            var ObjMSB = (int)reader.ReadByte();

            var result = (ObjMSB << 8) + ObjLSB;
            return result;
        }
コード例 #2
0
        async Task<bool> onewireReset(string deviceId)
        {
            try
            {
                if (serialPort != null)
                    serialPort.Dispose();

                serialPort = await SerialDevice.FromIdAsync(deviceId);

                // Configure serial settings
                serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                serialPort.BaudRate = 9600;
                serialPort.Parity = SerialParity.None;
                serialPort.StopBits = SerialStopBitCount.One;
                serialPort.DataBits = 8;
                serialPort.Handshake = SerialHandshake.None;

                dataWriteObject = new DataWriter(serialPort.OutputStream);
                dataWriteObject.WriteByte(0xF0);
                await dataWriteObject.StoreAsync();

                dataReaderObject = new DataReader(serialPort.InputStream);
                await dataReaderObject.LoadAsync(1);
                byte resp = dataReaderObject.ReadByte();
                if (resp == 0xFF)
                {
                    System.Diagnostics.Debug.WriteLine("Nothing connected to UART");
                    return false;
                }
                else if (resp == 0xF0)
                {
                    System.Diagnostics.Debug.WriteLine("No 1-wire devices are present");
                    return false;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Response: " + resp);
                    serialPort.Dispose();
                    serialPort = await SerialDevice.FromIdAsync(deviceId);

                    // Configure serial settings
                    serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
                    serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
                    serialPort.BaudRate = 115200;
                    serialPort.Parity = SerialParity.None;
                    serialPort.StopBits = SerialStopBitCount.One;
                    serialPort.DataBits = 8;
                    serialPort.Handshake = SerialHandshake.None;
                    dataWriteObject = new DataWriter(serialPort.OutputStream);
                    dataReaderObject = new DataReader(serialPort.InputStream);
                    return true;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
                return false;
            }
        }
コード例 #3
0
 private static async Task<String> StreamReadLine(DataReader reader) {
     int next_char;
     String data = "";
     while (true) {
         await reader.LoadAsync(1);
         next_char = reader.ReadByte();
         if (next_char == '\n') { break; }
         if (next_char == '\r') { continue; }
         data += Convert.ToChar(next_char);
     }
     return data;
 }
コード例 #4
0
        static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                if (IsRobot)
                {
                    DataReader reader = new DataReader(args.Socket.InputStream);
                    String str = "";
                    while (true)
                    {
                        uint len = await reader.LoadAsync(1);
                        if (len > 0)
                        {
                            byte b = reader.ReadByte();
                            str += Convert.ToChar(b);
                            if (b == '.')
                            {
                                Debug.WriteLine("Network Received: '{0}'", str);
                                //Controllers.ParseCtrlMessage(str);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    String lastStringSent;
                    while (true)
                    {
                        DataWriter writer = new DataWriter(args.Socket.OutputStream);
                        lastStringSent = ctrlStringToSend;
                        writer.WriteString(lastStringSent);
                        await writer.StoreAsync();
                        msLastSendTime = Stopwatch.ElapsedMilliseconds;

                        // re-send periodically
                        long msStart = Stopwatch.ElapsedMilliseconds;
                        for (; ;)
                        {
                            long msCurrent = Stopwatch.ElapsedMilliseconds;
                            if ((msCurrent - msStart) > 3000) break;
                            if (lastStringSent.CompareTo(ctrlStringToSend) != 0) break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("OnConnection() - " + e.Message);
            }
        }
コード例 #5
0
        private static byte[] ExtractBytesFromBuffer(Windows.Storage.Streams.IBuffer buffer)
        {
            List <byte> data = new List <byte>(capacity: (int)buffer.Length);

            using (Windows.Storage.Streams.DataReader dr = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
            {
                while (dr.UnconsumedBufferLength > 0)
                {
                    data.Add(dr.ReadByte());
                }
            }

            return(data.ToArray());
        }
コード例 #6
0
ファイル: MainPage.xaml.cs プロジェクト: QQOak/NetworkSockets
        private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {

                DataReader reader = new DataReader(args.Socket.InputStream);
                String str = "";
                while (true)
                {
                    uint len = await reader.LoadAsync(1);
                    if (len > 0)
                    {
                        byte b = reader.ReadByte();
                        str += Convert.ToChar(b);
                        
                        if (b == '.')
                        {
                            //Debug.WriteLine("Network Received: '{0}'", str);
                            //Controllers.ParseCtrlMessage(str);

                            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                            {
                                txbReceived.Text = str;
                            });


                            DataWriter writer = new DataWriter(socket.OutputStream);
                            writer.WriteString(String.Format("Received the following: {0}", str));
                            await writer.StoreAsync();
                            


                            str = string.Empty;
                            break;
                        }
                        
                        

                    }
                        
                }

            }
            catch (Exception e)
            {
                Debug.WriteLine("OnConnection() - " + e.Message);
            }
        }
コード例 #7
0
        // Read in bytes one at a time until we get a newline, then return the whole line
        private async Task<string> readLine(DataReader input)
        {
            string line = "";
            char a = ' ';
            // Keep looping as long as we haven't hit a newline OR line is empty
            while ((a != '\n' && a != '\r') || line.Length == 0 )
            {
                // Wait until we have 1 byte available to read
                await input.LoadAsync(1);
                // Read that one byte, typecasting it as a char
                a = (char)input.ReadByte();

                // If the char is a newline or a carriage return, then don't add it on to the line and quit out
                if( a != '\n' && a != '\r' )
                    line += a;
            }

            // Return the string we've built
            return line;
        }
コード例 #8
0
ファイル: NetworkCmd.cs プロジェクト: NejTech/Ingenuity
 static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     try
     {
         DataReader reader = new DataReader(args.Socket.InputStream);
         while (true)
         {
             uint len = await reader.LoadAsync(1);
             if (len > 0)
             {
                 byte b = reader.ReadByte();
                 Debug.WriteLine("Network Received: '{0}'", Convert.ToString(b,2));
                 MainPage.SendCommand(b);
                 //break;
             }
         }
     }
     catch (Exception e)
     {
         Debug.WriteLine("OnConnection() - " + e.Message);
     }
 }
コード例 #9
0
        private void DoNextRead(byte[] blob)
        {
            DataReader reader = new DataReader(_socket.InputStream);
            reader.InputStreamOptions = InputStreamOptions.Partial;

            var task = Task.Run(() =>
            {
                try
                {
                    reader.LoadAsync((uint)blob.Length).AsTask().Wait();
                    uint bytesRead = 0;
                    while(reader.UnconsumedBufferLength > 0)
                    {
                        blob[bytesRead++] = reader.ReadByte();
                    }

                    if(bytesRead > 0)
                    {
                        OnReceive(blob, bytesRead);
                    }
                }
                catch(Exception)
                {
                }
                finally
                {
                    reader.DetachStream();
                    reader.Dispose();
                }
            });
        }
コード例 #10
0
        private void _serialDevice_PinChanged(SerialDevice sender, PinChangedEventArgs args)
        {
            if (args.PinChange != SerialPinChange.RingIndicator) return;
            _dataReaderObject = new DataReader(_serialDevice.InputStream)
            {
                InputStreamOptions = InputStreamOptions.Partial
            };
            byte response = _dataReaderObject.ReadByte();
            _dataReaderObject.DetachStream();
            _dataReaderObject = null;

            HandleResponse(response);
        }
コード例 #11
0
        private async void OnPerformAction()
        {
            var stream = socket.OutputStream;
            using (var writer = new DataWriter(stream))
            {
                writer.ByteOrder = ByteOrder.LittleEndian;
                //writer.WriteInt16(6);
                //writer.WriteByte(0x00);
                //writer.WriteByte(3);
                //writer.WriteUInt16(1500);
                //writer.WriteUInt16(1000);

                //var bytes = new byte[] { 6, 0, 0, 3, 220, 5, 232, 3 };
                //writer.WriteBytes(bytes);

                writer.WriteInt16(12);
                writer.WriteByte(Byte0);
                writer.WriteByte(Byte1);
                writer.WriteByte(Byte2);
                writer.WriteByte(Byte3);
                writer.WriteByte(Byte4);
                writer.WriteByte(Byte5);
                writer.WriteByte(Byte6);
                writer.WriteByte(Byte7);
                writer.WriteUInt32(FourBytes);

                await writer.StoreAsync();
                writer.DetachStream();
            }
            using (var reader = new DataReader(socket.InputStream))
            {
                reader.ByteOrder = ByteOrder.LittleEndian;
                await reader.LoadAsync(5);
                var length = reader.ReadUInt16();
                var byte1 = reader.ReadByte();
                var byte2 = reader.ReadByte();
                var status = reader.ReadByte();

                reader.DetachStream();
            }
        }
コード例 #12
0
ファイル: Protocol.cs プロジェクト: kreyosopensource/KreyosWP
        private ActivityDataDoc LoadData(DataReader reader)
        {
            //read signature
            int signature = reader.ReadInt32();

            //read head
            ActivityDataDoc ret = new ActivityDataDoc();

            ret.version = (int)reader.ReadByte();
            ret.year = (int)reader.ReadByte();
            ret.month = (int)reader.ReadByte();
            ret.day = (int)reader.ReadByte();

            //read data
            while (reader.UnconsumedBufferLength > 0)
            {
                var row = new ActivityDataRow();

                //row head
                row.mode = reader.ReadByte();
                row.hour = reader.ReadByte();
                row.minute = reader.ReadByte();

                //row meta
                int size = (int)reader.ReadByte();
                byte[] meta = new byte[4];
                reader.ReadBytes(meta);

                //row data
                for (int i = 0, j = 0; meta[i] != 0 && i < 4 && j < size; ++i)
                {
                    int lvalue = meta[i] >> 4;
                    int rvalue = meta[i] & 0x0f;

                    if (j < size)
                    {
                        int rawValue = reader.ReadInt32();
                        ActivityDataRow.DataType dtype = dataTypeMap[lvalue];
                        double value = GetValue(rawValue, dtype);
                        row.data.Add(dtype, value);
                        j++;
                    }

                    if (j < size)
                    {
                        int rawValue = reader.ReadInt32();
                        ActivityDataRow.DataType dtype = dataTypeMap[rvalue];
                        double value = GetValue(rawValue, dtype);
                        row.data.Add(dtype, value);
                        j++;
                    }
                }
                ret.data.Add(row);

            }
            return ret;
        }
コード例 #13
0
ファイル: MainPage.xaml.cs プロジェクト: Wam1q/SerialScope
        // Read in iBuffLength number of samples
        private async Task<bool> bReadSource(DataReader input)
        {
            UInt32 k;
            byte byteInput;
            uint iErrorCount = 0;

            // Read in the data
            for (k = 0; k < iStreamBuffLength; k++)
            {

                // Wait until we have 1 byte available to read
                await input.LoadAsync(1);

                // Read in the byte
                byteInput = input.ReadByte();

                // Save to the ring buffer and see if the frame can be parsed
                if (++idxCharCount < iFrameSize)
                {
                    mbus.writeRingBuff(byteInput);
                }
                else
                {
                    iUnsignedShortArray = mbus.writeRingBuff(byteInput, iShortCount);
                    iErrorCount = mbus.iGetErrorCount();
                }

                if (iErrorCount == 0 && idxCharCount >= iFrameSize)
                {
                    // The frame was valid
                    rectFrameOK.Fill = new SolidColorBrush(Colors.Green);

                    // Was it the next one in the sequence?
                    if( ++byteAddress == Convert.ToByte(mbus.iGetAddress()))
                    {
                        rectFrameSequence.Fill = new SolidColorBrush(Colors.Green);
                    }
                    else
                    {
                        rectFrameSequence.Fill = new SolidColorBrush(Colors.Red);
                        byteAddress = Convert.ToByte(mbus.iGetAddress());
                    }


                    AddScopeData( Convert.ToSingle(iUnsignedShortArray[0]) * fScope1ScaleADC, Convert.ToSingle(iUnsignedShortArray[1]) * fScope2ScaleADC);
                    AddScopeData(Convert.ToSingle(iUnsignedShortArray[2]) * fScope1ScaleADC, Convert.ToSingle(iUnsignedShortArray[3]) * fScope2ScaleADC);

                    // Reset the character counter
                    idxCharCount = 0;
                }

                if(idxCharCount>(iFrameSize>>1))
                {
                    rectFrameOK.Fill = new SolidColorBrush(Colors.Black);

                }


            }

            // Success, return a true
            return true;
        }
コード例 #14
0
ファイル: Reader.cs プロジェクト: CareWB/WeX5
        /// <summary>
        /// Perform image capture from mediaCapture object
        /// </summary>
        /// <param name="cancelToken">
        /// The cancel Token.
        /// </param>
        /// <returns>
        /// Decoded barcode string.
        /// </returns>
        private async Task<Result> GetCameraImage(CancellationToken cancelToken)
        {
            Result result = null;
            await Task.Run(
                async () =>
                    {
                        this.imageStream = new InMemoryRandomAccessStream();
                        await this.capture.CapturePhotoToStreamAsync(this.encodingProps, this.imageStream);
                        await this.imageStream.FlushAsync();

                        this.datareader = new DataReader(this.imageStream);
                        await this.datareader.LoadAsync((uint)this.imageStream.Size);
                        var bitmap = new byte[this.encodingProps.Width * this.encodingProps.Height * 4];
                        uint index = 0;
                        while (this.datareader.UnconsumedBufferLength > 0)
                        {
                            bitmap[index] = datareader.ReadByte();
                            index++;
                        }

                        result = await this.DecodeBitmap(bitmap);

                        if (result != null)
                        {
                            this.barcodeFound = true;
                        }
                    },
                cancelToken).ConfigureAwait(false);
            return result;
        }
コード例 #15
0
        /// <summary>
        /// Creates NDEF records based on the data in the given buffer.
        /// </summary>
        /// <param name="buf">The data buffer as input.</param>
        /// <param name="list">The list of new NDEF records as output.</param>
        /// <param name="isFirstRecordSp">Defines whether the first record is smart poster or not.</param>
        private static void ReadNdefRecord(DataReader buf, List<NdefRecord> list, bool isFirstRecordSp)
        {
            var record = new NdefRecord();
            byte header = buf.ReadByte();
            record.Mb = IsBitSet(header, 7);
            record.Me = IsBitSet(header, 6);
            record.Cf = IsBitSet(header, 5);
            record.Sr = IsBitSet(header, 4);
            record.Il = IsBitSet(header, 3);
            record.Tnf = (byte)(header & 0x07);
            record.TypeLength = buf.ReadByte();
            record.IsSpRecord = isFirstRecordSp;

            if (record.Il)
            {
                record.IdLength = buf.ReadByte();
            }
            else
            {
                record.IdLength = 0;
            }

            if (record.Sr)
            {
                record.PayloadLength = buf.ReadByte();
            }
            else
            {
                var lengthBuf = new byte[4];
                buf.ReadBytes(lengthBuf);
                record.PayloadLength = BitConverter.ToUInt32(lengthBuf, 0);
            }

            if (record.TypeLength > 0)
            {
                record.Type = new byte[record.TypeLength];
                buf.ReadBytes(record.Type);
            }

            if ((record.Il) && (record.IdLength > 0))
            {
                record.Id = new byte[record.IdLength];
                buf.ReadBytes(record.Id);
            }

            if (record.PayloadLength > 0)
            {
                if ((record.Tnf == 0x01)
                    && (System.Text.Encoding.UTF8.GetString(record.Type, 0, record.TypeLength) == "Sp"))
                {
                    ReadNdefRecord(buf, list, true);
                    record.Payload = null;
                }
                else
                {
                    record.Payload = new byte[record.PayloadLength];
                    buf.ReadBytes(record.Payload);
                }
            }

            list.Add(record);

            if (!record.Me)
            {
                ReadNdefRecord(buf, list, isFirstRecordSp);
            }
        }
コード例 #16
0
ファイル: Server.cs プロジェクト: Hannsen94/RaspberryCopter
        /// <summary>
        /// Method used for the "Collection Thread"
        /// </summary>
        /// <param name="operation"></param>
        private async void CollectTelemetryData(IAsyncAction operation)
        {
            DataReader reader;
            uint unconsumedBufferLength = 0;
            lock (m_pConnectedSocket)
            {
                reader = new DataReader(m_pConnectedSocket.InputStream);
            }

            while (IsClientConnected | (unconsumedBufferLength > 0))
            {
                await m_pTelemetryReaderSemaphoreSlim.WaitAsync();
                try
                {
                    await reader.LoadAsync(sizeof (byte));
                    unconsumedBufferLength = reader.UnconsumedBufferLength;
                }
                finally
                {
                    m_pTelemetryReaderSemaphoreSlim.Release();
                }
                if (reader.UnconsumedBufferLength <= 0) continue;
                await m_pTelemetryReaderSemaphoreSlim.WaitAsync();
                try
                {
                    byte b;
                    var e = new OnTelemetryDataReceivedEventArgs();
                    b = reader.ReadByte();
                    var commandInformation = (CommandInformation) b;
                    switch (commandInformation)
                    {
                        case CommandInformation.Information:
                            await reader.LoadAsync(sizeof (uint));
                            var n = reader.ReadUInt32();
                            await reader.LoadAsync(n*sizeof (char));
                            e.CommandData = reader.ReadString(n);
                            e.CommandType = CommandInformation.Information;
                            break;
                        case CommandInformation.Gyroscope:
                            float angleX, angleY, angleZ;
                            long gyroTime;
                            await reader.LoadAsync(3*sizeof (double));
                            await reader.LoadAsync(sizeof (long));
                            angleX = Convert.ToSingle(reader.ReadDouble());
                            angleY = Convert.ToSingle(reader.ReadDouble());
                            angleZ = Convert.ToSingle(reader.ReadDouble());
                            gyroTime = reader.ReadInt64();
                            e.CommandData = new GyroscopeData()
                            {
                                Angle = new Vector3(angleX, angleY, angleZ),
                                TimeStamp = new DateTime(gyroTime)
                            };
                            e.CommandType = CommandInformation.Gyroscope;
                            break;
                        case CommandInformation.Accelerometer:
                            float accX, accY, accZ;
                            long accTime;
                            await reader.LoadAsync(3*sizeof (double));
                            await reader.LoadAsync(sizeof (long));
                            accX = Convert.ToSingle(reader.ReadDouble());
                            accY = Convert.ToSingle(reader.ReadDouble());
                            accZ = Convert.ToSingle(reader.ReadDouble());
                            accTime = reader.ReadInt64();
                            e.CommandData = new AccelerometerData()
                            {
                                Acceleration = new Vector3(accX, accY, accZ),
                                TimeStamp = new DateTime(accTime)
                            };
                            e.CommandType = CommandInformation.Accelerometer;
                            break;
                        case CommandInformation.Servo:
                            byte id, velocity;
                            long servoTime;
                            await reader.LoadAsync(2*sizeof (byte));
                            await reader.LoadAsync(sizeof (long));
                            id = reader.ReadByte();
                            velocity = reader.ReadByte();
                            servoTime = reader.ReadInt64();
                            e.CommandData = new ServoControllerData() {ServoId = id, VelocityValue = velocity, TimeStamp = new DateTime(servoTime)};
                            e.CommandType = CommandInformation.Servo;
                            break;
                    }
                    var handler = OnTelemetryDataReceived;
                    handler?.Invoke(this, e);
                }
                finally
                {
                    m_pTelemetryReaderSemaphoreSlim.Release();
                }
            }
        }
コード例 #17
0
        public override void Run()
        {
            #if WINRT
            StorageFile file = Package.Current.InstalledLocation.GetFileAsync(_path).AsTask().Result;
            using(var raStream = file.OpenReadAsync().AsTask().Result)
            {
                byte[] blob = new byte[CHUNK_SIZE];

                while (IsRunning && raStream.CanRead)
                {
                    DataReader reader = new DataReader(raStream.GetInputStreamAt(0));
                    reader.InputStreamOptions = InputStreamOptions.Partial;
                    try
                    {
                        reader.LoadAsync((uint)blob.Length).AsTask().Wait();
                        int bytesRead = 0;
                        while (reader.UnconsumedBufferLength > 0)
                        {
                            blob[bytesRead++] = reader.ReadByte();
                        }

                        if (bytesRead > 0)
                        {
                            HandleData(blob, bytesRead);
                        }
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        reader.DetachStream();
                        reader.Dispose();
                    }

                    if (raStream.Position >= raStream.Size)
                    {
                        Terminate();
                        break;
                    }

                    Task.Delay(INTERVAL).Wait();
                }
            }
            #else
            byte [] blob = new byte[CHUNK_SIZE];

            while(IsRunning && _fileStream.CanRead)
            {
                int read = _fileStream.Read(blob, 0, CHUNK_SIZE);

                if( read > 0 )
                {
                    HandleData(blob, read);
                }

                if(_fileStream.CanSeek && _fileStream.Position >= _fileStream.Length)
                {
                    Terminate();
                    break;
                }

                Thread.Sleep(INTERVAL);
            }
            #endif
        }
コード例 #18
0
ファイル: TvConnection.cs プロジェクト: parnic/samsungremote
 private byte GetLengthHeader(DataReader reader)
 {
     var length = reader.ReadByte();
     var delimiter = reader.ReadByte();
     if (delimiter != 0)
     {
         throw new Exception("Unexpected input " + delimiter);
     }
     return length;
 }
コード例 #19
0
ファイル: TvConnection.cs プロジェクト: parnic/samsungremote
 private void ReadResponseHeader(DataReader reader)
 {
     reader.ReadByte();
     /*var appName = */GetString(reader);
 }
コード例 #20
0
ファイル: FrameParser.cs プロジェクト: rwecho/WebSocket.UWP
        /**
         *  Read and parse frame
         */
        public async static Task<Frame> ReadFrame(DataReader dataReader)
        {
            Frame frame = new Frame();

            // read the first byte (op code)

            //var dataReader = new DataReader(stream);

            var DataReaderLoadOperation = await dataReader.LoadAsync(sizeof(byte));

            //if (DataReaderLoadOperation != sizeof(byte))
            //{
            //    throw new Exception("DataReaderLoadOperation is zero");//抛出异常
            //}

            int data = dataReader.ReadByte();


            frame.isFinal = (data & FIN) != 0;
            bool isReserved = (data & RSV) != 0;
            if (isReserved)
            {
                throw new Exception("RSV not zero");
            }

            frame.opCode = (data & OPCODE);



            if (Array.BinarySearch<int>(OPCODES, frame.opCode) < 0)
            {
                throw new Exception("Bad opcode");
            }

            if (Array.BinarySearch<int>(CTRL_OPCODES, frame.opCode) >= 0 && !frame.isFinal)
            {
                throw new Exception("In control opcode, must set FIN");
            }

            // read the second byte (mask and payload length)

            await dataReader.LoadAsync(sizeof(byte));

            data = dataReader.ReadByte();

            frame.isMasked = (data & MASK) != 0;
            int length = (data & LENGTH);

            // read extended length if need
            if (length < 126)
            {
                // short length is already read.
            }
            else if (length == 126)
            {
                await dataReader.LoadAsync(sizeof(UInt16));
                var b1 = dataReader.ReadByte();
                var b2 = dataReader.ReadByte();

                //length = b1 * 256 + b2;

                length = (((b1 & 0xff) << 8) | (b2 & 0xff));
                //  length = dataReader.ReadUInt16(); // read 2 bytes length
            }
            else if (length == 127)
            {
                await dataReader.LoadAsync(sizeof(Int64));
                byte[] longByte = new byte[8];
                //     long length8 = dataReader.ReadInt64();  // read 8 bytes length

                dataReader.ReadBytes(longByte);

                long length8 = byte2Long(longByte);
                if (length8 > int.MaxValue)
                {
                    throw new IOException("too big frame length");
                }
                length = (int)length8;
            }

            byte[] mask = null;
            if (frame.isMasked)
            {
                mask = new byte[4];
                await dataReader.LoadAsync(4);
                dataReader.ReadBytes(mask);
                //stream.readFully(mask);
            }

            frame.payload = new byte[length]; // can be optimized.
            //stream.readFully(frame.payload);

            if (length > 0)
            {
                await dataReader.LoadAsync((uint)length);
                dataReader.ReadBytes(frame.payload);
            }

            if (frame.isMasked)
            {
                UseMask(frame.payload, mask, 0);
            }


            return frame;
        }
コード例 #21
0
ファイル: Movement.cs プロジェクト: traceyt/SensorTag-Azure
 protected short ReadBigEndian16bit(DataReader reader)
 {
     byte lo = reader.ReadByte();
     byte hi = reader.ReadByte();
     return (short)(((short)hi << 8) + (short)lo);
 }
コード例 #22
0
ファイル: Comms.cs プロジェクト: QQOak/NetworkSockets
        private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {

                DataReader reader = new DataReader(args.Socket.InputStream);
                String str = "";
                while (true)
                {
                    uint len = await reader.LoadAsync(1);
                    if (len > 0)
                    {
                        byte b = reader.ReadByte();
                        if (b == '.')
                        {
                            //Debug.WriteLine(string.Format("Network Received: '{0}'", str));
                            //ParseCtrlMessage(str);
                            _CommandReceived(this, str);
                            str = "";
                            break;
                        }
                        else
                        {

                            str += Convert.ToChar(b);
                        }
                    }

                }

            }
            catch (Exception e)
            {
                Debug.WriteLine("OnConnection() - " + e.Message);
            }
        }
コード例 #23
0
        private async Task<string> ReadResponse(StreamSocket socket)
        {
            //txtSerialNo.Text = "Reading response ...";

            using (DataReader reader = new DataReader(socket.InputStream))
            {
                reader.InputStreamOptions = InputStreamOptions.Partial;

                reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;

                reader.ByteOrder = ByteOrder.LittleEndian;

                StringBuilder command = new StringBuilder();

                string commandString = string.Empty;

                bool commandRetrieved = false;

                await reader.LoadAsync(1);

                while (reader.UnconsumedBufferLength > 0)
                {
                    byte b = reader.ReadByte();

                    switch (b)
                    {
                        case 0x02:
                            command.Clear();
                            break;

                        case 0x03:

                            try
                            {
                                // Case the boolean values correctly
                                commandString = command.Replace("False", "false").Replace("True", "true").ToString();

                                commandRetrieved = true;
                            }
                            catch (Exception ex)
                            {
                                //txtResult.Text = command.ToString();
                            }

                            command.Clear();

                            break;

                        default:
                            command.Append(Convert.ToChar(b));
                            break;
                    }

                    if (commandRetrieved)
                    {
                        break;
                    }

                    await reader.LoadAsync(1);
                }

                reader.DetachStream();

                return commandString;
            }
        }
コード例 #24
0
ファイル: WebSocket.cs プロジェクト: rwecho/WebSocket.UWP
        private async Task<string> ReadLine(DataReader reader)
        {
            StringBuilder stringBuilder = new StringBuilder();
            await reader.LoadAsync(sizeof(byte));

            int readChar = reader.ReadByte();
            if (readChar == -1)
            {
                return null;
            }
            while (readChar != '\n')
            {
                if (readChar != '\r')
                {
                    stringBuilder.Append((char)readChar);
                }
                await reader.LoadAsync(sizeof(byte));
                readChar = reader.ReadByte();
                if (readChar == -1)
                {
                    return null;
                }
            }
            return stringBuilder.ToString();
        }
コード例 #25
0
        private async Task<string> ReadData(DataReader reader)
        {
            string length = string.Empty;
            bool lengthFound = false;
            while (!lengthFound)
            {
                await reader.LoadAsync(1);
                byte character = reader.ReadByte();
                if (character == ':')
                {
                    lengthFound = true;
                }
                else
                {
                    length += Convert.ToChar(character);
                }
            }

            if (string.IsNullOrEmpty(length))
            {
                return string.Empty;
            }
            
            int dataLength = int.Parse(length);
            byte[] dataBuffer = new byte[dataLength];
            await reader.LoadAsync(Convert.ToUInt32(dataLength));
            reader.ReadBytes(dataBuffer);
            return System.Text.Encoding.UTF8.GetString(dataBuffer, 0, dataLength);
        }
コード例 #26
0
        private async Task<UInt32> serialReadAsync(uint read_size)
        {
            try
            {
                if (serialPort == null)
                {
                    printLog("No port selected");
                    return 0;
                }
                //TODO handle cancelationTokens
                using (DataReader dataReaderObject = new DataReader(serialPort.InputStream))
                {

                    // Launch the task and wait
                    UInt32 bytesRead = await dataReaderObject.LoadAsync(read_size);

                    for (int i = 0; i < bytesRead; i++)
                    {
                        serialReceive[i] = dataReaderObject.ReadByte();
                    }
                    dataReaderObject.DetachStream();
                    return bytesRead;
                }
            }
            catch (Exception ex)
            {
                printLog(ex.Message);
                return 0;
            }
        }
コード例 #27
0
        private async Task deviceReaderAsync()
        {
            Packet currentPacket = new Packet();

            using (DataReader dataReader = new DataReader(serialDevice.InputStream))
            {
                dataReader.InputStreamOptions = InputStreamOptions.Partial;

                try
                {
                    while (true)
                    {
                        await dataReader.LoadAsync(kReadBufferSize).AsTask(readCancellation.Token);
                        while (dataReader.UnconsumedBufferLength > 0)
                        {
                            if (currentPacket.ByteCount == 0)
                            {
                                currentPacket.receivedFromPortStart = DateTime.Now;
                            }
                            if (processByte(currentPacket, dataReader.ReadByte()))
                            {
                                currentPacket.receivedFromPortEnd = DateTime.Now;
                                //if it's an empty receive, drop it.
                                if(currentPacket.ByteCount == 2)
                                {
                                    if (currentPacket.GetData()[0] == kCodeReceive)
                                    {
                                        currentPacket = new Packet();
                                        continue;
                                    }
                                }
                                incomingPacketQueue.Post(currentPacket);
                                currentPacket = new Packet();
                            }
                        }
                    }
                }
                catch (TaskCanceledException tce)
                {
                    System.Diagnostics.Debug.WriteLine("Read cancelled " + tce.ToString());
                }
                finally
                {
                    dataReader.DetachStream();
                }

            }
        }
コード例 #28
0
ファイル: Chip8.cs プロジェクト: erin100280/Emunator
        public async void LoadRomFromFile(StorageFile file)
        {
            IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
            IInputStream inputStream = readStream.GetInputStreamAt(0);
            DataReader dataReader = new DataReader(inputStream);

            uint nbBytesLoaded = await dataReader.LoadAsync((uint)readStream.Size);
            int length = (int)nbBytesLoaded;

            ushort position = 0;
            byte[] romBin = new byte[length];

            while (position < length)
            {
                romBin[position] = dataReader.ReadByte();
                position += sizeof(byte);
            }

            LoadRomInMemory(romBin);
        }
コード例 #29
0
        public async void SendToAgent(Slide slide, StreamSocket TCPClient)
        {
            var content = slide.Content as ScreenCapture;
            var writer = new DataWriter(TCPClient.OutputStream);
            var reader = new DataReader(TCPClient.InputStream);
            Timer timer = new Timer(async (client) =>
            {
                try
                {
                    var tcpClient = client as StreamSocket;
                    var writerCB = new DataWriter(tcpClient.OutputStream);
                    writerCB.WriteString("::STOP::");
                    await writerCB.StoreAsync();
                    await writerCB.FlushAsync();
                    tcpClient.Dispose();
                }
                catch(Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }, TCPClient, slide.AppearanceDuration, Timeout.Infinite);
            try
            {
                var length = writer.WriteString(content.ProcessName);
                await writer.StoreAsync();
                await writer.FlushAsync();

                var byteList = new List<byte>();
                try
                {
                    while (true)
                    {
                        reader.InputStreamOptions = InputStreamOptions.Partial;
                        uint sizeFieldCount = await reader.LoadAsync(1);
                        if (sizeFieldCount != 1)
                        {
                            // The underlying socket was closed before we were able to read the whole data. 
                            throw new Exception("Connection was closed from Agent with IP: " + content.IPTargetAgent);
                        }

                        // Read the message. 
                        uint messageLength = reader.ReadByte();
                        uint actualMessageLength = await reader.LoadAsync(4);
                        var buffer = new byte[actualMessageLength];
                        reader.ReadBytes(buffer);
                        var msgLength = System.BitConverter.ToUInt32(buffer, 0);
                        byteList.Clear();
                        byteList.Capacity = (int)msgLength;
                        uint remainingLength = msgLength;
                        while (remainingLength > 0)
                        {
                            if (actualMessageLength == 0)
                            {
                                throw new Exception("Connection was closed from Agent with IP: " + content.IPTargetAgent);
                            }
                            actualMessageLength = await reader.LoadAsync(remainingLength);
                            remainingLength -= actualMessageLength;
                            buffer = new byte[actualMessageLength];
                            reader.ReadBytes(buffer);
                            byteList.AddRange(buffer);
                        }
                        this.FireOnDataReceived(byteList.ToArray());
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex.Message);
                this.FireOnConnectionFailed();
            }
        }