WriteBytes() public method

public WriteBytes ( byte value ) : void
value byte
return void
示例#1
0
        public static void iBeaconSetAdvertisement(this BluetoothLEAdvertisement Advertisment, iBeaconData data)
        {
            BluetoothLEManufacturerData manufacturerData = new BluetoothLEManufacturerData();

            // Set Apple as the manufacturer data
            manufacturerData.CompanyId = 76;

            var writer = new DataWriter();
            writer.WriteUInt16(0x0215); //bytes 0 and 1 of the iBeacon advertisment indicator

            if (data!=null& data.UUID!= Guid.Empty)
            {
                //If UUID is null scanning for all iBeacons
                writer.WriteBytes( data.UUID.ToByteArray());
                if (data.Major!=0)
                {
                    //If Major not null searching with UUID and Major
                    writer.WriteBytes(BitConverter.GetBytes(data.Major).Reverse().ToArray());
                    if (data.Minor != 0)
                    {
                        //If Minor not null we are looking for a specific beacon not a class of beacons
                        writer.WriteBytes(BitConverter.GetBytes(data.Minor).Reverse().ToArray());
                        if (data.TxPower != 0)
                            writer.WriteBytes(BitConverter.GetBytes(data.TxPower));
                    }
                }
            }

            manufacturerData.Data = writer.DetachBuffer();

            Advertisment.ManufacturerData.Clear();
            Advertisment.ManufacturerData.Add(manufacturerData);
        }
        private static byte[] GetDataIn(byte serviceCount, byte[] serviceCodeList, byte blockCount, byte[] blockList)
        {
            DataWriter dataWriter = new DataWriter();

            dataWriter.WriteByte(serviceCount);
            dataWriter.WriteBytes(serviceCodeList);
            dataWriter.WriteByte(blockCount);
            dataWriter.WriteBytes(blockList);

            return dataWriter.DetachBuffer().ToArray();
        }
示例#3
0
        public void Send(string message)
        {
            var ostream = this.streamSocket.OutputStream;
            var dataWriter = new DataWriter(ostream);

            byte[] msgByteArray = Helpers.stringToByteArray(message);
            byte[] msgSizeByteArray = Helpers.intToByteArray(msgByteArray.Length);

            dataWriter.WriteBytes(msgSizeByteArray);
            dataWriter.WriteBytes(msgByteArray);
            dataWriter.StoreAsync().AsTask().Wait();
            dataWriter.FlushAsync().AsTask().Wait();
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (!(value is byte[]))
            {
                return null;
            }

            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                // Writes the image byte array in an InMemoryRandomAccessStream
                // that is needed to set the source of BitmapImage.
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes((byte[])value);

                    // The GetResults here forces to wait until the operation completes
                    // (i.e., it is executed synchronously), so this call can block the UI.
                    writer.StoreAsync().GetResults();
                }

                var image = new BitmapImage();
                image.SetSource(ms);
                return image;
            }
        }
示例#5
0
        private async void Update()
        {
            var writer1 = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE,
                Options = new ZXing.Common.EncodingOptions
                {
                    Height = 200,
                    Width = 200
                },

            };

            var image = writer1.Write(Text);//Write(text);


            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(image);
                    await writer.StoreAsync();
                }

                var output = new BitmapImage();
                await output.SetSourceAsync(ms);
                ImageSource = output;
            }


        }
示例#6
0
		private async Task WriteToOutputStreamAsync(byte[] bytes)
		{

			if (_socket == null) return;
			_writer = new DataWriter(_socket.OutputStream);
			_writer.WriteBytes(bytes);

			var debugString = UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length);

			try
			{
				await _writer.StoreAsync();
				await _socket.OutputStream.FlushAsync();

				_writer.DetachStream();
				_writer.Dispose();
			}
			catch (Exception exception)
			{
				// If this is an unknown status it means that the error if fatal and retry will likely fail.
				if (global::Windows.Networking.Sockets.SocketError.GetStatus(exception.HResult) == global::Windows.Networking.Sockets.SocketErrorStatus.Unknown)
				{
					// TODO abort any retry attempts on Unity side
					throw;
				}
			}
		}
        private async Task Download(string url,StorageFile file,bool cover)
        {
            var http = new HttpClient();
            byte[] response = { };
            string betterUrl = url;
            if(cover)
            {
                var pos = betterUrl.IndexOf(".jpg");
                if (pos != -1)
                    betterUrl = betterUrl.Insert(pos, "l");
            }

            //get bytes
            try
            {
                await Task.Run(async () => response = await http.GetByteArrayAsync(betterUrl));
            }
            catch (Exception)
            {
                await Task.Run(async () => response = await http.GetByteArrayAsync(url));
            }

            var fs = await file.OpenStreamForWriteAsync(); //get stream
            var writer = new DataWriter(fs.AsOutputStream());

            writer.WriteBytes(response); //write
            await writer.StoreAsync();
            await writer.FlushAsync();

            writer.Dispose();
        }
示例#8
0
        public async Task sendCommand(string rconCommand, string gameServerIP, string password, string gameServerPort)
        {
            rconCommand = "rcon " + password + " " + rconCommand;
            using (var stream = await socket.GetOutputStreamAsync(new HostName(gameServerIP), gameServerPort))
            {
                using (var writer = new DataWriter(stream))
                {
                    byte[] bufferTemp = Encoding.UTF8.GetBytes(rconCommand);
                    byte[] bufferSend = new byte[bufferTemp.Length + 5];

                    bufferSend[0] = byte.Parse("255");
                    bufferSend[1] = byte.Parse("255");
                    bufferSend[2] = byte.Parse("255");
                    bufferSend[3] = byte.Parse("255");
                    bufferSend[4] = byte.Parse("02");
                    int j = 5;

                    for (int i = 0; i < bufferTemp.Length; i++)
                    {
                        bufferSend[j++] = bufferTemp[i];
                    }

                    writer.WriteBytes(bufferSend);
                    await writer.StoreAsync();
                }
            }
        }
示例#9
0
       async  void BeginReadCCTV()
        {
            
            IsBeginRead = true;
            ISExit = false;
            tblCCTV cctvinfo=null;
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                   () =>
                   {
                       cctvinfo = this.DataContext as tblCCTV;
                   });

             
           // client=new HttpClient();
            while (!ISExit)
            {
                try
                {
                    Uri uri = new Uri("http://192.192.161.3/" + cctvinfo.REF_CCTV_ID.Trim() + ".jpg?" + rnd.Next(), UriKind.Absolute);

                    using (httpClient = new HttpClient())
                    {
                        httpClient.Timeout = TimeSpan.FromSeconds(0.5);
                        var contentBytes = await httpClient.GetByteArrayAsync(uri);

                   
                        var ims =  new InMemoryRandomAccessStream();

                        var dataWriter = new DataWriter(ims);
                        dataWriter.WriteBytes(contentBytes);
                        await dataWriter.StoreAsync();
                       //ims.seak 0
                     ims.Seek(0 );
                       
                       await Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal,()=>
                            {
                        BitmapImage bitmap = new BitmapImage();
                        bitmap.SetSource(ims );
                       

                        this.imgCCTV.Source = bitmap;
                        imginx = (imginx + 1) % 90000;
                        this.RunFrameRate.Text = imginx.ToString();
                            });
                    }
                    
                }
                catch (Exception ex)
                {
                 //   this.textBlock1.Text = ex.Message;
                }
                // BitmapImage img = new BitmapImage();
                // img.SetSource(stream);

              

               
            }
        
        }
示例#10
0
    public static async Task <Windows.UI.Xaml.Media.Imaging.BitmapImage> GetBitmapAsync(byte[] data)
    {
        if (data is null)
        {
            return(null);
        }

        var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();

        using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
        {
            using (var writer = new Windows.Storage.Streams.DataWriter(stream))
            {
                writer.WriteBytes(data);
                await writer.StoreAsync();

                await writer.FlushAsync();

                writer.DetachStream();
            }

            stream.Seek(0);
            await bitmapImage.SetSourceAsync(stream);
        }
        return(bitmapImage);
    }
示例#11
0
		public static async Task WriteFileAsync(string fileName, byte[] content)
		{
			try
			{
				var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

				using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
				{
					using (var outputStream = fileStream.GetOutputStreamAt(0))
					{
						using (var dataWriter = new DataWriter(outputStream))
						{
							dataWriter.WriteBytes(content);
							await dataWriter.StoreAsync();
							dataWriter.DetachStream();
						}
						await outputStream.FlushAsync();
					}
				}
			}
			catch (Exception exception)
			{
				SnazzyDebug.WriteLine(exception);
			}
		}
      public async Task<bool> LocalStorage(string Path,string fileName,  byte[] bytes)
       {
           try
           {
               StorageFolder localFolderStorage = ApplicationData.Current.LocalFolder;
               var localFolder = await localFolderStorage.CreateFolderAsync(Path, CreationCollisionOption.OpenIfExists);
               var localFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                   using (StorageStreamTransaction transaction = await localFile.OpenTransactedWriteAsync())
                   {
                       //Stream targetStream = await localFile.OpenStreamForWriteAsync(); //localFolderStorage.OpenStreamForWriteAsync(Path+"\\"+fileName,  CreationCollisionOption.OpenIfExists))
                       DataWriter dataWriter = new DataWriter(transaction.Stream);
                       dataWriter.WriteBytes(bytes);
                       await dataWriter.StoreAsync();
                       //stream.CopyTo(targetStream);
                       // stream.Dispose();
                       //targetStream.Close();
                   }

               return true;
           }
           // Use catch blocks to handle errors
           catch (Exception err)
           {
               return false;
           }
       }
示例#13
0
文件: Utility.cs 项目: bdecori/win8
        public async Task<BitmapImage> Base64ToBitmapImage(string base64String)
        {

            BitmapImage img = new BitmapImage();
            if (string.IsNullOrEmpty(base64String))
                return img;

            using (var ims = new InMemoryRandomAccessStream())
            {
                byte[] bytes = Convert.FromBase64String(base64String);
                base64String = "";

                using (DataWriter dataWriter = new DataWriter(ims))
                {
                    dataWriter.WriteBytes(bytes);
                    bytes = null;
                    await dataWriter.StoreAsync();
                                 

                ims.Seek(0);

              
               await img.SetSourceAsync(ims); //not in RC
               
               
                return img;
                }
            }

        }
示例#14
0
文件: ServerTcp.cs 项目: lillo42/IoT
        public async Task SendAsync(string text)
        {
            try
            {
                // DataWriter to send message to client
                var writer = new DataWriter(_socket.OutputStream);
                //Encrypt message
                byte[] data = Cryptographic.Encrypt(text, "123");

                //Write Lenght message in buffer
                writer.WriteInt32(data.Length);
                //Write message in buffer
                writer.WriteBytes(data);

                //Send buffer
                await writer.StoreAsync();
                //Clear buffer
                await writer.FlushAsync();

            }
            catch (Exception e)
            {
                InvokeOnError(e.Message);
            }
        }
示例#15
0
 public async static void GetImageSize(this Stream imageStream)
 {
     var image = new BitmapImage();
     byte[] imageBytes = Convert.FromBase64String(imageStream.ToBase64String());
     MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
     ms.Write(imageBytes, 0, imageBytes.Length);
     using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
     {
         using (DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0)))
         {
             try
             {
                 writer.WriteBytes(imageBytes);
                 await writer.StoreAsync();
             }
             catch (Exception)
             {
                 // ignored
             }
         }
         try
         {
             await image.SetSourceAsync(stream);
         }
         catch (Exception)
         {
             // ignored
         }
     }
     ImageSize = new Size(image.PixelWidth, image.PixelHeight);
 }
示例#16
0
        /// <summary>
        /// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
        /// </summary>
        /// <param name="timeout">Operation timeout.</param>
        /// <returns>Network accurate <see cref="DateTime"/> value.</returns>
        public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
        {
            using (var socket = new DatagramSocket())
            using (var ct = new CancellationTokenSource(timeout))
            {
                ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());

                socket.MessageReceived += OnSocketMessageReceived;
                //The UDP port number assigned to NTP is 123
                await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
                using (var writer = new DataWriter(socket.OutputStream))
                {
                    // NTP message size is 16 bytes of the digest (RFC 2030)
                    var ntpBuffer = new byte[48];

                    // Setting the Leap Indicator, 
                    // Version Number and Mode values
                    // LI = 0 (no warning)
                    // VN = 3 (IPv4 only)
                    // Mode = 3 (Client Mode)
                    ntpBuffer[0] = 0x1B;

                    writer.WriteBytes(ntpBuffer);
                    await writer.StoreAsync();
                    var result = await _resultCompletionSource.Task;
                    return result;
                }
            }
        }
示例#17
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value != null && value is byte[])
            {

                //WriteableBitmap bitmap = new WriteableBitmap(100, 100);

                //System.IO.Stream bitmapStream = null;
                //bitmapStream = bitmap.PixelBuffer.AsStream();
                //bitmapStream.Position = 0;
                //bitmapStream.Write(value as byte[], 0, (value as byte[]).Length);

                //bitmapStream.Flush();

                InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
                writer.WriteBytes(value as byte[]);
                var x = writer.StoreAsync().AsTask().Result;
                BitmapImage image = new BitmapImage();
                image.SetSource(randomAccessStream);

                return image;
            }

            return null;
        }
        /// <summary>
        /// Extension method to SmartCardConnection class to perform a transparent exchange to the ICC
        /// </summary>
        /// <param name="connection">
        /// SmartCardConnection object
        /// </param>
        /// <param name="commandData">
        /// Command object to send to the ICC
        /// </param>
        /// <returns>Response received from the ICC</returns>
        public static async Task<byte[]> TransparentExchangeAsync(this SmartCardConnection connection, byte[] commandData)
        {
            byte[] responseData = null;
            ManageSessionResponse apduRes = await TransceiveAsync(connection, new ManageSession(new byte[2] { (byte)ManageSession.DataObjectType.StartTransparentSession, 0x00 })) as ManageSessionResponse;

            if (!apduRes.Succeeded)
            {
                throw new Exception("Failure to start transparent session, " + apduRes.ToString());
            }

            using (DataWriter dataWriter = new DataWriter())
            {
                dataWriter.WriteByte((byte)TransparentExchange.DataObjectType.Transceive);
                dataWriter.WriteByte((byte)commandData.Length);
                dataWriter.WriteBytes(commandData);

                TransparentExchangeResponse apduRes1 = await TransceiveAsync(connection, new TransparentExchange(dataWriter.DetachBuffer().ToArray())) as TransparentExchangeResponse;

                if (!apduRes1.Succeeded)
                {
                    throw new Exception("Failure transceive with card, " + apduRes1.ToString());
                }

                responseData = apduRes1.IccResponse;
            }

            ManageSessionResponse apduRes2 = await TransceiveAsync(connection, new ManageSession(new byte[2] { (byte)ManageSession.DataObjectType.EndTransparentSession, 0x00 })) as ManageSessionResponse;

            if (!apduRes2.Succeeded)
            {
                throw new Exception("Failure to end transparent session, " + apduRes2.ToString());
            }

            return responseData;
        }
示例#19
0
        private async void ButtonAction2_Click(object sender, RoutedEventArgs e)
        {
            DevicesInformation = string.Empty;
            foreach (var rsCharacteristic in _dicCharacteristics)
            {
                DevicesInformation += $"  Try to write to {rsCharacteristic.Value.CharName}{Environment.NewLine}";
                bool writeOk = true;
                try
                {
                    var charToTest = rsCharacteristic.Value.Characteristic;
                    byte[] arr = { 4, 1, 2, 0, 1, 0 };
                    var writer = new DataWriter();
                    writer.WriteBytes(arr);
                    await charToTest.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);
                    await charToTest.WriteValueAsync(writer.DetachBuffer());
                    DevicesInformation += $"  - OK{Environment.NewLine}";
                }
                catch
                {
                    DevicesInformation += $"  - ERROR{Environment.NewLine}";
                    writeOk = false;
                }

                var msg = $"{rsCharacteristic.Value.CharName}, {writeOk}, {rsCharacteristic.Value.Characteristic.CharacteristicProperties}, {rsCharacteristic.Value.Characteristic.Uuid}";
                Debug.WriteLine(msg);

                await Task.Delay(TimeSpan.FromMilliseconds(100));
            }
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value != null)
            {

                byte[] bytes = (byte[])value;
                BitmapImage myBitmapImage = new BitmapImage();
                if (bytes.Count() > 0)
                {


                    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                    DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0));

                    writer.WriteBytes(bytes);
                    writer.StoreAsync().GetResults();
                    myBitmapImage.SetSource(stream);
                }
                else
                {
                    myBitmapImage.UriSource = new Uri("ms-appx:///Assets/firstBackgroundImage.jpg");
                }

                return myBitmapImage;
            }
            else
            {
                return new BitmapImage();
            }
        }
        // Write function for adding control points to a server
        private async Task HandleSensorControlPoint(string data)
        {
            if (!string.IsNullOrEmpty(data))
            {
                // Get current service from base class.
                var service = await GetService();
                // Get current characteristic from current service using the selected values from the base class.
                var characteristic = service.GetCharacteristics(this.SelectedService.Guid)[this.SelectedIndex];

                //Create an instance of a data writer which will write to the relevent buffer.
                DataWriter writer = new DataWriter();
                byte[] toWrite = System.Text.Encoding.UTF8.GetBytes(data);
                writer.WriteBytes(toWrite);

                // Attempt to write the data to the device, and whist doing so get the status.
                GattCommunicationStatus status = await characteristic.WriteValueAsync(writer.DetachBuffer());

                // Displays a message box to tell user if the write operation was successful or not.
                if (status == GattCommunicationStatus.Success)
                {
                    MessageHelper.DisplayBasicMessage("Sensor control point has been written.");
                }
                else
                {
                    MessageHelper.DisplayBasicMessage("There was a problem writing the sensor control value, Please try again later.");
                }
            }
        }
示例#22
0
 public async Task<bool> Init()
 {
     var res = true;
     ClearExceptions();
     for (int i = 0; i < 20; i++)
     {
         try
         {
             var value = new byte[3];
             value[0] = 0x1;
             value[1] = (byte)(i + 1);
             value[2] = (byte)(i + 1);
             var buffer = new DataWriter();
             buffer.WriteBytes(value);
             await _initCount1To20Char.WriteValueAsync(buffer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);
             await Sleep(50);
         }
         catch (Exception exception)
         {
             res = false;
             AddException(exception);
         }
     }
     return res;
 }
示例#23
0
        public static async Task<bool> ConnectAsync()
        {
            if (imageComparisonServer != null)
                return true;
			
            try
            {
                imageComparisonServer = new StreamSocket();
                await imageComparisonServer.ConnectAsync(new HostName(ParadoxImageServerHost), ParadoxImageServerPort.ToString());
			
                // Send initial parameters
                using (var memoryStream = new MemoryStream())
                {
                    var binaryWriter = new BinaryWriter(memoryStream);
                    ImageTestResultConnection.Write(binaryWriter);

                    var dataWriter = new DataWriter(imageComparisonServer.OutputStream);
                    dataWriter.WriteBytes(memoryStream.ToArray());
                    await dataWriter.StoreAsync();
                    await dataWriter.FlushAsync();
                    dataWriter.DetachStream();
                }

                return true;
            }
            catch (Exception)
            {
                imageComparisonServer = null;
			
                return false;
            }
        }
 public static IBuffer GetBufferFromByteArray(this byte[] payload)
 {
     using (var dw = new DataWriter())
     {
         dw.WriteBytes(payload);
         return dw.DetachBuffer();
     }
 }
示例#25
0
 public async Task<IRandomAccessStream> Stream2IRandomAccessStream(byte[] bytes)
 {
     InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();
     DataWriter datawriter = new DataWriter(memoryStream.GetOutputStreamAt(0));
     datawriter.WriteBytes(bytes);
     await datawriter.StoreAsync();
     return memoryStream;
 }
示例#26
0
		async partial void SendTimeRequest()
		{
			var socket = new Windows.Networking.Sockets.DatagramSocket();
			AsyncUdpResult asyncResult = null;
			try
			{
				var buffer = new byte[48];
				buffer[0] = 0x1B;

				socket.MessageReceived += Socket_Completed_Receive;
				asyncResult = new AsyncUdpResult(socket);
			
				await socket.ConnectAsync(new Windows.Networking.HostName(_ServerAddress), "123").AsTask().ConfigureAwait(false);

				using (var udpWriter = new DataWriter(socket.OutputStream))
				{
					udpWriter.WriteBytes(buffer);
					await udpWriter.StoreAsync().AsTask().ConfigureAwait(false);

					udpWriter.WriteBytes(buffer);
					await udpWriter.StoreAsync().AsTask().ConfigureAwait(false);

					asyncResult.Wait(OneSecond);
				}
			}
			catch (Exception ex)
			{
				try
				{
					if (socket != null)
					{
						ExecuteWithSuppressedExceptions(() => socket.MessageReceived -= this.Socket_Completed_Receive);
						ExecuteWithSuppressedExceptions(() => socket.Dispose());
					}
				}
				finally
				{
					OnErrorOccurred(ExceptionToNtpNetworkException(ex));
				}
			}
			finally
			{
				asyncResult?.Dispose();
			}
		}
        /// <summary>
        /// Attempts to send a magic packet to the desination hostname, on the specified port with the specified MAC address.
        /// </summary>
        /// <param name="destination">Destination hostname or IP address.</param>
        /// <param name="destinationPort">Destination port number.</param>
        /// <param name="targetMac">Destination MAC address. Bytes can be separated by colons, dashes, or nothing.</param>
        /// <returns>True if magic packet is sent successfully, false otherwise.</returns>
        public async Task<bool> SendMagicPacket(Windows.Networking.HostName destination, uint destinationPort, string targetMac)
        {
            try
            {
                DatagramSocket _socket = new DatagramSocket();               

                using (var stream = await _socket.GetOutputStreamAsync(destination, destinationPort.ToString()))
                {
                    //Split on common MAC separators
                    char? splitChar = null;
                    if (targetMac.Contains('-'))
                        splitChar = '-';
                    else if (targetMac.Contains(':'))
                        splitChar = ':';
                    else if (targetMac.Contains(' '))
                        splitChar = ' ';

                    //Turn MAC into array of bytes
                    byte[] macAsArray;
                    if (splitChar != null)
                    {
                        macAsArray = targetMac.Split((char)splitChar)
                            .Select(b => Convert.ToByte(b, 16))
                            .ToArray<byte>();
                    }
                    else
                    {
                        //Jump through MAC-string, reading 2 chars at a time
                        macAsArray = Enumerable.Range(0, targetMac.Length)
                            .Where(x => x % 2 == 0)
                            .Select(x => Convert.ToByte(targetMac.Substring(x, 2), 16)) //16 = hexadecimal
                            .ToArray();
                    }

                    List<byte> magicPacket = new List<byte> { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

                    //A WoLAN magic packet is just FF FF FF FF FF FF, then the target MAC adress repeated 16 times.
                    for (int i = 0; i < 16; i++)
                    {
                        magicPacket = magicPacket.Concat(macAsArray).ToList();
                    }

                    using (DataWriter writer = new DataWriter(stream))
                    {
                        writer.WriteBytes(magicPacket.ToArray<byte>());
                        await writer.StoreAsync();
                        await writer.FlushAsync();
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                return false;
            }
        }       
示例#28
0
		private async void ColorThread()
		{
			try
			{
                var reader = new DataReader( Client.InputStream );
                reader.InputStreamOptions = InputStreamOptions.Partial;
                reader.ByteOrder = ByteOrder.LittleEndian;

                while ( IsConnected ) {
                    await reader.LoadAsync( 4 );
                    var size = reader.ReadUInt32();

                    await reader.LoadAsync( size );
                    byte[] bytes = new byte[size];
                    reader.ReadBytes( bytes );

                    MemoryStream ms = new MemoryStream( bytes );
					BinaryReader br = new BinaryReader(ms);

                    ColorFrameReadyEventArgs args = new ColorFrameReadyEventArgs();
                    ColorFrameData cfd = new ColorFrameData();

                    cfd.Format = (ImageFormat)br.ReadInt32();
					cfd.ImageFrame = br.ReadColorImageFrame();

                    MemoryStream msData = new MemoryStream( bytes, (int)ms.Position, (int)(ms.Length - ms.Position) );
                    if (cfd.Format == ImageFormat.Raw)
                    {
                        cfd.RawImage = ms.ToArray();
                    }
                    else
                    {
                        InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
                        DataWriter dw = new DataWriter(ras.GetOutputStreamAt(0));
                        dw.WriteBytes(msData.ToArray());
                        await dw.StoreAsync();   

                        // Set to the image
                        BitmapImage bImg = new BitmapImage();
                        bImg.SetSource(ras);
                        cfd.BitmapImage = bImg;
                    }

					ColorFrame = cfd;
					args.ColorFrame = cfd;

                    if (ColorFrameReady != null)
                    {
                        ColorFrameReady(this, args);
                    }
				}
			}
			catch(IOException)
			{
				Disconnect();
			}
		}
示例#29
0
        public HidOutputReport GetFilledReport()
        {
            var dataWriter = new DataWriter();
            dataWriter.WriteByte(Id);
            dataWriter.WriteBytes(Data.Array);
            report.Data = dataWriter.DetachBuffer();

            return report;
        }
示例#30
0
 private static async Task<InMemoryRandomAccessStream> ByteArrayToRandomAccessStream(byte[] tile)
 {
     var stream = new InMemoryRandomAccessStream();
     var dataWriter = new DataWriter(stream);
     dataWriter.WriteBytes(tile);
     await dataWriter.StoreAsync();
     stream.Seek(0);
     return stream;
 }
示例#31
0
 public static async Task<IRandomAccessStream> ToRandomAccessStream(this MemoryStream memoryStream)
 {
     var tile = memoryStream.ToArray();
     var stream = new InMemoryRandomAccessStream();
     var dataWriter = new DataWriter(stream);
     dataWriter.WriteBytes(tile);
     await dataWriter.StoreAsync();
     stream.Seek(0);
     return stream;
 }
示例#32
0
 private async System.Threading.Tasks.Task _SendUDPMessage(byte[] data)
 {
     using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(PupilSettings.Instance.connection.pupilRemoteIP), PupilSettings.Instance.connection.pupilRemotePort))
     {
         using (var writer = new Windows.Storage.Streams.DataWriter(stream))
         {
             writer.WriteBytes(data);
             await writer.StoreAsync();
         }
     }
 }
示例#33
0
 private async System.Threading.Tasks.Task _SendUDPMessage(string externalIP, string externalPort, byte[] data)
 {
     using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(externalIP), externalPort))
     {
         using (var writer = new Windows.Storage.Streams.DataWriter(stream))
         {
             writer.WriteBytes(data);
             await writer.StoreAsync();
         }
     }
 }
示例#34
0
 private async System.Threading.Tasks.Task SendMessage(string message, string ip, int port)
 {
     using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(ip), port.ToString()))
     {
         using (var writer = new Windows.Storage.Streams.DataWriter(stream))
         {
             var data = Encoding.UTF8.GetBytes(message);
             writer.WriteBytes(data);
             await writer.StoreAsync();
         }
     }
 }
示例#35
0
        private async Task <int> SendAsync(byte[] inbuffer)
        {
            using (var writer = new Windows.Storage.Streams.DataWriter(socket.OutputStream))
            {
                writer.WriteBytes(inbuffer);
                await writer.StoreAsync();

                writer.DetachStream();
            }
            // hopefully true...
            return(inbuffer.Length);
        }
示例#36
0
        /// <summary>
        /// Restores the applications data using a backup from the current user's OneDrive.
        /// <para>Note: Application requires restart after restoring data</para>
        /// </summary>
        /// <param name="itemId">Unique item identifier within a DriveItem (i.e., a folder/file facet).</param>
        /// <param name="filename">Name of the datafile.</param>
        /// <returns></returns>
        public static async Task RestoreFileFromOneDriveAsync(string itemId, string dataFilename)
        {
            try
            {
                // Local storage folder
                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;

                // Our local ktdatabase.db file
                Windows.Storage.StorageFile originalDataFile =
                    await storageFolder.GetFileAsync(dataFilename);

                // Stream for the backed up data file
                var backedUpFileStream = await GraphClient.Me.Drive.Items[itemId].ItemWithPath(dataFilename).Content
                                         .Request()
                                         .GetAsync();

                // Backed up file
                var backedUpFile = await storageFolder.CreateFileAsync("temp", CreationCollisionOption.ReplaceExisting);

                var newStream = await backedUpFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                // Write data to new file
                using (var outputStream = newStream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        var buffer = backedUpFileStream.ToByteArray();
                        dataWriter.WriteBytes(buffer);

                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }

                // Copy and replace local file
                await backedUpFile.CopyAsync(storageFolder, dataFilename, NameCollisionOption.ReplaceExisting);
            }

            catch (ServiceException ex)
            {
                if (ex.StatusCode == HttpStatusCode.Forbidden)
                {
                    Console.WriteLine($"Access Denied: {ex.Message}");
                }

                Console.WriteLine($"Service Exception, Error uploading file to signed-in users one drive: {ex.Message}");
                // return null;
            }
        }
示例#37
0
    // send to external IP and external port
    private async System.Threading.Tasks.Task SendMessageUDP(string message)
    {
        using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(externalIP), externalPort))
        {
            using (var writer = new Windows.Storage.Streams.DataWriter(stream))
            {
                var data = Encoding.UTF8.GetBytes(message);

                writer.WriteBytes(data);
                await writer.StoreAsync();

                Debug.Log("Sent: " + message);
            }
        }
    }
示例#38
0
        private async void btnColor_Click(object sender, RoutedEventArgs e)
        {
            //Change the color of the NeoPixel by writing the hex color bytes to the Write characteristic
            //that is currently being monitored by our Flora sketch
            Button btnColor = (Button)sender;
            var    color    = ((SolidColorBrush)btnColor.Background).Color;

            var writer = new Windows.Storage.Streams.DataWriter();

            writer.WriteBytes(new byte[] { color.R, color.G, color.B });

            txtProgress.Text = "Writing color to Writable GATT characteristic ...";
            await _writeCharacteristic.WriteValueAsync(writer.DetachBuffer());

            txtProgress.Text = "Writable GATT characteristic written";
        }
示例#39
0
            public static async Task TurnOnSensor(SensorChars sensorCharacteristics)
            {
                SensorServicesCls.SensorIndexes sensor = sensorCharacteristics.Sensor_Index;
                Debug.WriteLine("Begin turn on sensor: " + sensor.ToString());
                // Turn on sensor
                try
                {
                    if (sensor >= 0 && sensor != SensorServicesCls.SensorIndexes.KEYS && sensor != SensorServicesCls.SensorIndexes.IO_SENSOR && sensor != SensorServicesCls.SensorIndexes.REGISTERS)
                    {
                        if (sensorCharacteristics.Charcteristics.Keys.Contains(SensorServicesCls.CharacteristicTypes.Enable))
                        {
                            GattCharacteristic characteristic = sensorCharacteristics.Charcteristics[SensorServicesCls.CharacteristicTypes.Enable];
                            if (characteristic != null)
                            {
                                if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                                {
                                    var writer = new Windows.Storage.Streams.DataWriter();
                                    if (sensor == SensorServicesCls.SensorIndexes.MOVEMENT)
                                    {
                                        byte[] bytes = new byte[] { 0x7f, 0x00 };
                                        writer.WriteBytes(bytes);
                                    }
                                    else
                                    {
                                        writer.WriteByte((Byte)0x01);
                                    }

                                    var status = await characteristic.WriteValueAsync(writer.DetachBuffer());
                                }
                            }
                        }
                        else
                        {
                        }
                    }
                    //IncProgressCounter();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Error: TurnOnSensor() : " + sensor.ToString() + " " + ex.Message);
                }

                Debug.WriteLine("End turn on sensor: " + sensor.ToString());
            }
示例#40
0
    /// <summary>
    /// 指定範囲のキャプチャ画像をSoftwareBitmap型として得る
    /// </summary>
    /// <param name="left">キャプチャ範囲の左端端x座標</param>
    /// <param name="top">キャプチャ範囲の左端端y座標</param>
    /// <param name="height">キャプチャ範囲の高さ</param>
    /// <param name="width">キャプチャ範囲の幅</param>
    /// <returns>指定された範囲のキャプチャ画像</returns>
    public static async Task <SoftwareBitmap> CaptureAsSoftwareBitmap(int left, int top, int height, int width)
    {
        //ビットマップの保持領域を確保
        Bitmap partialCapture = new Bitmap(width, height);
        //描画インターフェイスの設定
        Graphics draw = Graphics.FromImage(partialCapture);

        //画面全体をコピーする
        draw.CopyFromScreen(
            left,
            top,
            0, 0,
            partialCapture.Size
            );

        //解放
        draw.Dispose();

        MemoryStream memStream = new MemoryStream();

        partialCapture.Save(memStream, ImageFormat.Bmp);

        SoftwareBitmap softwareBitmap;

        using (var randomAccessStream = new UwpInMemoryRandomAccessStream())
        {
            using (var outputStream = randomAccessStream.GetOutputStreamAt(0))
                using (var writer = new UwpDataWriter(outputStream))
                {
                    writer.WriteBytes(memStream.ToArray());
                    await writer.StoreAsync();

                    await outputStream.FlushAsync();
                }

            // IRandomAccessStreamをSoftwareBitmapに変換
            // (ここはUWP APIのデコーダーを使う)
            var decoder = await UwpBitmapDecoder.CreateAsync(randomAccessStream);

            softwareBitmap = await decoder.GetSoftwareBitmapAsync(UwpBitmapPixelFormat.Bgra8, UwpBitmapAlphaMode.Premultiplied);
        }

        return(softwareBitmap);
    }
示例#41
0
    // ========================================================================= Class Members =========================================================== //

    /// <summary>
    /// Sends message to destination port
    /// </summary>
    /// <param name="message">string to send</param>
#if NETFX_CORE
    public async Task  Send(string message)
    {
        try
        {
            using (var stream = await _impl.GetOutputStreamAsync(new Windows.Networking.HostName(destIP), destPortStr))
            {
                using (var writer = new Windows.Storage.Streams.DataWriter(stream))
                {
                    var data = Encoding.UTF8.GetBytes(message);

                    writer.WriteBytes(data);
                    await writer.StoreAsync();
                }
            }
        }
        catch (Exception e)
        {
            Debug.Log(TAG + " SendMessageUDP exception:\n" + e.ToString());
        }
示例#42
0
        private async Task updateImage(Image cameraImage, string url)
        {
            // Download the image into memory as a stream
            System.Net.Http.HttpClient          client        = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage imageResponse = await client.GetAsync(url);

            InMemoryRandomAccessStream randomAccess =
                new Windows.Storage.Streams.InMemoryRandomAccessStream();

            DataWriter writer =
                new Windows.Storage.Streams.DataWriter(randomAccess.GetOutputStreamAt(0));

            writer.WriteBytes(await imageResponse.Content.ReadAsByteArrayAsync());
            await writer.StoreAsync();

            BitmapImage bit = new BitmapImage();
            await bit.SetSourceAsync(randomAccess);

            cameraImage.Source = bit;
        }
        public static async void Interact(anki_vehicle vehicle, GattCharacteristic readChar, GattCharacteristic writeChar)
        {
            try
            {
                var    writer   = new Windows.Storage.Streams.DataWriter();
                byte[] rawBytes = null;
                GattCommunicationStatus result;
                readChar.ValueChanged += VehicleResponse;
                if (readChar.CharacteristicProperties == (GattCharacteristicProperties.Read | GattCharacteristicProperties.Notify))
                {
                    result = await readChar.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                }

                while (true)
                {
                    Console.Write("Please enter your command: ");
                    string input = Console.ReadLine();
                    if (input == "exit")
                    {
                        return;
                    }

                    switch (input)
                    {
                    case "ping":
                    {
                        anki_vehicle_msg msg = new anki_vehicle_msg();
                        msg.size   = ANKI_VEHICLE_MSG_BASE_SIZE;
                        msg.msg_id = (byte)AnkiMessage.ANKI_VEHICLE_MSG_C2V_PING_REQUEST;
                        rawBytes   = getBytes(msg);
                        writer.WriteBytes(rawBytes);
                        result = await writeChar.WriteValueAsync(writer.DetachBuffer());

                        break;
                    }

                    case "get-version":
                    {
                        anki_vehicle_msg msg = new anki_vehicle_msg();
                        msg.size   = ANKI_VEHICLE_MSG_BASE_SIZE;
                        msg.msg_id = (byte)AnkiMessage.ANKI_VEHICLE_MSG_C2V_VERSION_REQUEST;
                        rawBytes   = getBytes(msg);
                        writer.WriteBytes(rawBytes);
                        result = await writeChar.WriteValueAsync(writer.DetachBuffer());

                        break;
                    }

                    case "get-battery":
                    {
                        anki_vehicle_msg msg = new anki_vehicle_msg();
                        msg.size   = ANKI_VEHICLE_MSG_BASE_SIZE;
                        msg.msg_id = (byte)AnkiMessage.ANKI_VEHICLE_MSG_C2V_BATTERY_LEVEL_REQUEST;
                        rawBytes   = getBytes(msg);
                        writer.WriteBytes(rawBytes);
                        result = await writeChar.WriteValueAsync(writer.DetachBuffer());

                        break;
                    }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#44
0
        private async Task <bool> WriteSensor(byte[] bytes, ServiceCharacteristicsEnum characteristicEnum)
        {
            bool ret = false;

            Debug.WriteLine("Begin WriteSensor: " + SensorIndex.ToString());
            try
            {
                if (GattService != null)
                {
                    GattCharacteristic           characteristic = null;
                    GattCharacteristicProperties flag           = GattCharacteristicProperties.Write;
                    switch (characteristicEnum)
                    {
                    case ServiceCharacteristicsEnum.Data:
                        characteristic = this.Data;
                        break;

                    case ServiceCharacteristicsEnum.Notification:
                        flag           = GattCharacteristicProperties.Notify;
                        characteristic = this.Notification;
                        break;

                    case ServiceCharacteristicsEnum.Configuration:
                        characteristic = this.Configuration;
                        break;

                    case ServiceCharacteristicsEnum.Period:
                        characteristic = this.GattCharacteristicPeriod;
                        break;

                    case ServiceCharacteristicsEnum.Address:
                        characteristic = this.Address;
                        break;

                    case ServiceCharacteristicsEnum.Device_Id:
                        characteristic = this.Device_Id;
                        break;
                    }
                    if (characteristic != null)
                    {
                        if (characteristic.CharacteristicProperties.HasFlag(flag))
                        {
                            var writer = new Windows.Storage.Streams.DataWriter();
                            writer.WriteBytes(bytes);

                            var status = await characteristic.WriteValueAsync(writer.DetachBuffer());

                            if (status == GattCommunicationStatus.Success)
                            {
                                ret = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: WriteSensor(): " + SensorIndex.ToString() + " " + ex.Message);
            }
            Debug.WriteLine("End WriteSensor " + SensorIndex.ToString());
            return(ret);
        }