예제 #1
0
        public static async Task <UwpSoftwareBitmap> ConvertFrom(BitmapFrame sourceBitmap)
        {
            // BitmapFrameをBMP形式のバイト配列に変換
            byte[] bitmapBytes;
            var    encoder = new BmpBitmapEncoder(); // .NET用のエンコーダーを使う

            encoder.Frames.Add(sourceBitmap);
            using (var memoryStream = new MemoryStream())
            {
                encoder.Save(memoryStream);
                bitmapBytes = memoryStream.ToArray();
            }

            // バイト配列をUWPのIRandomAccessStreamに変換
            using (var randomAccessStream = new UwpInMemoryRandomAccessStream())
            {
                using (var outputStream = randomAccessStream.GetOutputStreamAt(0))
                    using (var writer = new UwpDataWriter(outputStream))
                    {
                        writer.WriteBytes(bitmapBytes);
                        await writer.StoreAsync();

                        await outputStream.FlushAsync();
                    }

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

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

                return(softwareBitmap);
            }
        }
예제 #2
0
        private IEnumerator     AsyncSendPing()
        {
#if !NETFX_CORE
            AsyncCallback callback = new AsyncCallback(this.SendPresence);
#endif
            WaitForSeconds wait = new WaitForSeconds(this.pingInterval);

            while (true)
            {
                for (int i = 0; i < this.BroadcastEndPoint.Length; i++)
#if NETFX_CORE
                {
                    var action = this.Client.GetOutputStreamAsync(new Windows.Networking.HostName("127.0.0.1"), this.BroadcastEndPoint[i].Port.ToString());
                    //var action = this.Client.GetOutputStreamAsync(this.Client.Information.LocalAddress, this.BroadcastEndPoint[i].Port.ToString());
                    action.AsTask().Wait();
                    var outputStream = action.GetResults();
                    var writer       = new Windows.Storage.Streams.DataWriter(outputStream);
                    writer.WriteBytes(AutoDetectUDPClient.UDPPingMessage);
                    writer.StoreAsync().AsTask().Wait();
                }
#else
                { this.Client.BeginSend(this.pingContent, this.pingContent.Length, this.BroadcastEndPoint[i], callback, null); }
#endif

                yield return(wait);
            }
        }
예제 #3
0
        private async void _baseWebView_ScriptNotify(object sender, NotifyEventArgs e)
        {
            try
            {
                var bmp        = new BitmapImage();
                var base64     = e.Value.Substring(e.Value.IndexOf(",") + 1);
                var imageBytes = Convert.FromBase64String(base64);

#if WINDOWS_APP || WINDOWS_PHONE_APP
                using (var ms = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    using (var writer = new Windows.Storage.Streams.DataWriter(ms.GetOutputStreamAt(0)))
                    {
                        writer.WriteBytes(imageBytes);
                        await writer.StoreAsync();
                    }

                    bmp.SetSource(ms);
                }
#elif WINDOWS_PHONE
                using (var ms = new System.IO.MemoryStream(imageBytes))
                {
                    ms.Position = 0;
                    bmp.SetSource(ms);
                }
#endif

                imageBytes      = null;
                _img.Source     = bmp;
                _img.Visibility = Visibility.Visible;
            }
            catch { }
        }
예제 #4
0
        /// <summary>
        /// Gửi một gói tin đi
        /// </summary>
        /// <param name="data">gói tin cần gửi</param>
        /// <returns>true nếu gửi thành công, false nếu thất bại</returns>
        public async Task <bool> SendAsync(byte[] data)
        {
            // Monitor.Enter(nstreamlock);
            try
            {
                byte[] senddata = new byte[data.Length + sizeof(int)];
                // đưa độ dài của data về dạng bytes rồi copy vào send
                Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, senddata, 0, sizeof(int));

                // copy dữ liệu còn lại vào send
                Buffer.BlockCopy(data, 0, senddata, sizeof(int), data.Length);

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

                // Monitor.Exit(nstreamlock);
                return(true);
            }
            catch
            {
                Disconnect();
                //  Monitor.Exit(nstreamlock);
                return(false);
            }
        }
예제 #5
0
        public async Task TurnOnSensor()
        {
            Debug.WriteLine("Begin turn on sensor: " + SensorIndex.ToString());
            // Turn on sensor
            if (SensorIndex >= 0 && SensorIndex != SensorIndexes.KEYS && SensorIndex != SensorIndexes.IO_SENSOR && SensorIndex != SensorIndexes.REGISTERS)
            {
                if (Configuration != null)
                {
                    if (Configuration.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                    {
                        var writer = new Windows.Storage.Streams.DataWriter();
                        // Special value for Gyroscope to enable all 3 axes
                        ////////if (sensor == GYROSCOPE)
                        ////////    writer.WriteByte((Byte)0x07);
                        ////////else
                        // Special value for Gyroscope to enable all 3 axes
                        if (SensorIndex == SensorIndexes.MOVEMENT)
                        {
                            byte[] bytes = new byte[] { 0x7f, 0x00 };
                            writer.WriteBytes(bytes);
                        }
                        else
                        {
                            writer.WriteByte((Byte)0x01);
                        }

                        var status = await Configuration.WriteValueAsync(writer.DetachBuffer());
                    }
                }
            }
            Debug.WriteLine("End turn on sensor: " + SensorIndex.ToString());
        }
예제 #6
0
        /// <summary>
        /// Publish and subscribe a dealcards -message.
        /// </summary>
        public void DealCards()
        {
            state = ProtoState.DealCard;

            if (IsMaster())
            {
                opponentsCards = App.CardModel.SuffleCards();
                Message msg = new Message(Message.TypeEnum.EDealCards);
                msg.CardIds = opponentsCards;

                // Construct and serialize a dealcards -message.
                MemoryStream mstream = _nfcMessage.SerializeMessage(msg);

                var dataWriter = new Windows.Storage.Streams.DataWriter();
                dataWriter.WriteBytes(mstream.GetBuffer());


                // Publish the message
                _publishedMsgId = _proximityDevice.PublishBinaryMessage("Windows.CarTrumps",
                                                                        dataWriter.DetachBuffer(), NfcWriteCallback);
            }
            else
            {
                // subscribe for a reply
                _subscribedMsgId = _proximityDevice.SubscribeForMessage("Windows.CarTrumps",
                                                                        NfcMessageReceived);
            }
        }
예제 #7
0
        public async Task TurnOffSensor()
        {
            try {
                Debug.WriteLine("Begin turn off sensor: " + SensorIndex.ToString());
                // Turn on sensor
                if (SensorIndex >= 0 && SensorIndex != SensorIndexes.KEYS && SensorIndex != SensorIndexes.IO_SENSOR && SensorIndex != SensorIndexes.REGISTERS)
                {
                    if (Configuration != null)
                    {
                        if (Configuration.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                        {
                            var writer = new Windows.Storage.Streams.DataWriter();
                            if (SensorIndex == SensorIndexes.MOVEMENT)
                            {
                                byte[] bytes = new byte[] { 0x00, 0x00 };//Fixed
                                writer.WriteBytes(bytes);
                            }
                            else
                            {
                                writer.WriteByte((Byte)0x00);
                            }

                            var status = await Configuration.WriteValueAsync(writer.DetachBuffer());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: TurnOffSensor(): " + SensorIndex.ToString() + " " + ex.Message);
            }
            Debug.WriteLine("End turn off sensor: " + SensorIndex.ToString());
        }
예제 #8
0
        public void     Stop()
        {
            this.behaviour.StopCoroutine(this.pingCoroutine);

            for (int i = 0; i < this.BroadcastEndPoint.Length; i++)
#if NETFX_CORE
            {
                var action = this.Client.GetOutputStreamAsync(new Windows.Networking.HostName("127.0.0.1"), this.BroadcastEndPoint[i].Port.ToString());
                //var action = this.Client.GetOutputStreamAsync(this.Client.Information.LocalAddress, this.BroadcastEndPoint[i].Port.ToString());
                action.AsTask().Wait();
                var outputStream = action.GetResults();
                var writer       = new Windows.Storage.Streams.DataWriter(outputStream);
                writer.WriteBytes(AutoDetectUDPClient.UDPEndMessage);
                writer.StoreAsync().AsTask().Wait();
            }
#else
            { this.Client.Send(AutoDetectUDPClient.UDPEndMessage, AutoDetectUDPClient.UDPEndMessage.Length, this.BroadcastEndPoint[i]); }
#endif

#if NETFX_CORE
            this.Client.Dispose();
#else
            this.Client.Close();
#endif
        }
예제 #9
0
        private async Task <bool> WriteSensor(byte[] bytes, ServiceCharacteristicsEnum character)
        {
            Debug.WriteLine("Begin write sensor: " + SensorIndex.ToString());
            bool ret = false;

            if (GattService != null)
            {
                GattCharacteristic           characteristic = null;
                GattCharacteristicProperties flag           = GattCharacteristicProperties.Write;
                switch (character)
                {
                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.Period;
                    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;
                        }
                    }
                }
            }
            Debug.WriteLine("End write sensor: " + SensorIndex.ToString());
            return(ret);
        }
예제 #10
0
 private Windows.Storage.Streams.IBuffer GetBufferFromBytes(byte[] str)
 {
     using (Windows.Storage.Streams.InMemoryRandomAccessStream memoryStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
     {
         using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(memoryStream))
         {
             dataWriter.WriteBytes(str);
             return(dataWriter.DetachBuffer());
         }
     }
 }
예제 #11
0
        public async Task SendData(byte[] data)
        {
            Task <UInt32> storeAsyncTask;

            // Load the text from the sendText input text box to the dataWriter object
            dataWriteObject.WriteBytes(data);

            // Launch an async task to complete the write operation
            storeAsyncTask = dataWriteObject.StoreAsync().AsTask();

            UInt32 bytesWritten = await storeAsyncTask;
        }
예제 #12
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 async Task RestoreFileAsync(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;
            }
        }
예제 #13
0
        private async System.Threading.Tasks.Task SendMessage(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);
                }
            }
        }
        private BitmapImage GetBitmap(byte[] bytes)
        {
            var bmp = new BitmapImage();

              using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
              {
            using (var writer = new Windows.Storage.Streams.DataWriter(stream.GetOutputStreamAt(0)))
            {
              writer.WriteBytes(bytes);
              writer.StoreAsync().GetResults();
              bmp.SetSource(stream);
            }
              }
              return bmp;
        }
예제 #15
0
        private static Windows.UI.Xaml.Media.Imaging.BitmapImage GetBitmap(byte[] bytes)
        {
            var bmp = new Windows.UI.Xaml.Media.Imaging.BitmapImage();

            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                using (var writer = new Windows.Storage.Streams.DataWriter(stream.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(bytes);
                    writer.StoreAsync().GetResults();
                    bmp.SetSource(stream);
                }
            }
            return(bmp);
        }
예제 #16
0
        public void     Send(Packet packet)
        {
            this.sendBuffer.Clear();
            this.packetBuffer.Clear();

            packet.Out(this.packetBuffer);
            this.sendBuffer.Append(packet.packetId);
            this.sendBuffer.Append((uint)this.packetBuffer.Length);
            this.sendBuffer.Append(this.packetBuffer);
            //Debug.Log("Sending " + packet.GetType().Name + " of " + this.sendBuffer.Length + " bytes.");

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

            writer.WriteBytes(this.sendBuffer.Flush());
            writer.StoreAsync().AsTask().Wait();
        }
예제 #17
0
        /// <summary>
        /// Sends a broadcast message searching for available Webservices
        /// </summary>
        private async Task SendMessage(DatagramSocket socket)
        {
            HostName hostName = new HostName("255.255.255.255"); // to all listeners

            using (var stream = await socket.GetOutputStreamAsync(hostName, m_SendPort.ToString()))
            {
                using (var writer = new Windows.Storage.Streams.DataWriter(stream))
                { // <Command>;<Timeout>
                    string sendstr = String.Format("{0};{1}", "OnVifUniversal.SEARCHWS", this.m_timeOut);

                    var data = Encoding.UTF8.GetBytes(sendstr);
                    writer.WriteBytes(data);
                    writer.WriteByte(0); // String 0
                    await writer.StoreAsync();
                }
            }
        }
        async System.Threading.Tasks.Task <BitmapImage> GetBitapImage(MemoryStream ms)
        {
            // The implementation below follows
            // http://iamabhik.wordpress.com/2012/10/31/display-image-from-stream-in-windows-8-and-windows-phone-8/
            var   image = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
            var   ras   = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var   os    = ras.GetOutputStreamAt(0);
            var   dw    = new Windows.Storage.Streams.DataWriter(os);
            var   task  = System.Threading.Tasks.Task.Factory.StartNew(() => dw.WriteBytes(ms.ToArray()));
            await task;
            await dw.StoreAsync();

            await os.FlushAsync();

            await image.SetSourceAsync(ras);

            return(image);
        }
        private static async Task <bool> WriteCharacteristic(GattCharacteristic characteristic, byte[] data)
        {
            var writer = new Windows.Storage.Streams.DataWriter();

            writer.WriteBytes(data);
            var result = await characteristic.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithResponse);

            if (result == GattCommunicationStatus.Success)
            {
                Console.WriteLine("Characteristic value was written successfully");
                return(true);
            }
            else
            {
                Console.WriteLine("connect error: Transport endpoint is not connected (107)");
                return(false);
            }
        }
예제 #20
0
        private async void _baseWebView_ScriptNotify(object sender, NotifyEventArgs e)
        {
            var bmp        = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
            var base64     = e.Value.Substring(e.Value.IndexOf(",") + 1);
            var imageBytes = Convert.FromBase64String(base64);

            using (var ms = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                using (var writer = new Windows.Storage.Streams.DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(imageBytes);
                    await writer.StoreAsync();
                }

                bmp.SetSource(ms);
            }

            _img.Source     = bmp;
            _img.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }
예제 #21
0
        private void buttonWriteBulkOut_Click(object sender, RoutedEventArgs e)
        {
            if (this.SerialPortInfo != null)
            {
                var dataToWrite = this.textBoxDataToWrite.Text;

                var dispatcher = this.Dispatcher;
                ((Action)(async() =>
                {
                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async() =>
                    {
                        // Unicode to ASCII.
                        var encoder = System.Text.Encoding.UTF8.GetEncoder();
                        var utf8bytes = new byte[dataToWrite.Length];
                        int bytesUsed, charsUsed;
                        bool completed;
                        encoder.Convert(dataToWrite.ToCharArray(), 0, dataToWrite.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed);

                        var writer = new Windows.Storage.Streams.DataWriter();
                        writer.WriteBytes(utf8bytes);
                        var isChecked = checkBoxSendNullTerminateCharToBulkOut.IsChecked;
                        if (isChecked.HasValue && isChecked.Value == true)
                        {
                            writer.WriteByte(0x00); // NUL
                        }
                        var buffer = writer.DetachBuffer();
                        await this.SerialPortInfo.Port.Write(buffer, 0, buffer.Length);

                        var temp = this.textBoxWriteLog.Text;
                        temp += "Write completed: \"" + dataToWrite + "\" (" + buffer.Length.ToString() + " bytes)\n";
                        this.textBoxWriteLog.Text = temp;

                        this.textBoxDataToWrite.Text = "";
                    }));
                }
                          )).Invoke();
            }
        }
예제 #22
0
        /// <summary>
        /// Publish and subscribe a showcard -message.
        /// </summary>
        public void ShowCard()
        {
            state = ProtoState.ShowCard;

            StopAll();

            // Construct and serialize a showcard -message.
            Message msg = new Message(Message.TypeEnum.EShowCard);

            msg.CardId = (ushort)App.CardModel.ActiveCard.CardId;
            msg.SelectedCardProperty = App.CardModel.SelectedCardPropertyName;
            MemoryStream mstream = _nfcMessage.SerializeMessage(msg);

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

            dataWriter.WriteBytes(mstream.GetBuffer());

            // Publish the message
            _publishedMsgId = _proximityDevice.PublishBinaryMessage("Windows.CarTrumps",
                                                                    dataWriter.DetachBuffer(), NfcWriteCallback);
            // and subscribe for a reply
            _subscribedMsgId = _proximityDevice.SubscribeForMessage("Windows.CarTrumps",
                                                                    NfcMessageReceived);
        }
예제 #23
0
        private async void BaseWebViewScriptNotify(object sender, NotifyEventArgs e)
        {
            try
            {
                var bmp        = new BitmapImage();
                var imageBytes = HeatMapHelper.GetHeatMapImageBytes(e.Value);

                using (var ms = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    using (var writer = new Windows.Storage.Streams.DataWriter(ms.GetOutputStreamAt(0)))
                    {
                        writer.WriteBytes(imageBytes);
                        await writer.StoreAsync();
                    }

                    await bmp.SetSourceAsync(ms);
                }

                imageBytes      = null;
                _img.Source     = bmp;
                _img.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
            catch { }
        }
        private void buttonWriteBulkOut_Click(object sender, RoutedEventArgs e)
        {
            if (this.SerialPortInfo != null)
            {
                var dataToWrite = this.textBoxDataToWrite.Text;

                var dispatcher = this.Dispatcher;
                ((Action)(async () =>
                {
                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () =>
                    {
                        // Unicode to ASCII.
                        var encoder = System.Text.Encoding.UTF8.GetEncoder();
                        var utf8bytes = new byte[dataToWrite.Length];
                        int bytesUsed, charsUsed;
                        bool completed;
                        encoder.Convert(dataToWrite.ToCharArray(), 0, dataToWrite.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed);

                        var writer = new Windows.Storage.Streams.DataWriter();
                        writer.WriteBytes(utf8bytes);
                        var isChecked = checkBoxSendNullTerminateCharToBulkOut.IsChecked;
                        if (isChecked.HasValue && isChecked.Value == true)
                        {
                            writer.WriteByte(0x00); // NUL
                        }
                        var buffer = writer.DetachBuffer();
                        await this.SerialPortInfo.Port.Write(buffer, 0, buffer.Length);

                        var temp = this.textBoxWriteLog.Text;
                        temp += "Write completed: \"" + dataToWrite + "\" (" + buffer.Length.ToString() + " bytes)\n";
                        this.textBoxWriteLog.Text = temp;

                        this.textBoxDataToWrite.Text = "";
                    }));
                }
                )).Invoke();
            }
        }
예제 #25
0
        /// <summary>
        /// Publish and subscribe a dealcards -message.
        /// </summary>
        public void DealCards()
        {
            state = ProtoState.DealCard;

            if (IsMaster())
            {
                opponentsCards = App.CardModel.SuffleCards();
                Message msg = new Message(Message.TypeEnum.EDealCards);
                msg.CardIds = opponentsCards;

                // Construct and serialize a dealcards -message.
                MemoryStream mstream = _nfcMessage.SerializeMessage(msg);

                var dataWriter = new Windows.Storage.Streams.DataWriter();
                dataWriter.WriteBytes(mstream.GetBuffer());

                // Publish the message
                _publishedMsgId = _proximityDevice.PublishBinaryMessage("Windows.CarTrumps",
                    dataWriter.DetachBuffer(), NfcWriteCallback);
            }
            else
            {
                // subscribe for a reply
                _subscribedMsgId = _proximityDevice.SubscribeForMessage("Windows.CarTrumps",
                    NfcMessageReceived);
            }
        }
예제 #26
0
        /// <summary>
        /// Publish and subscribe a showcard -message.
        /// </summary>
        public void ShowCard()
        {
            state = ProtoState.ShowCard;

            StopAll();

            // Construct and serialize a showcard -message.
            Message msg = new Message(Message.TypeEnum.EShowCard);
            msg.CardId = (ushort)App.CardModel.ActiveCard.CardId;
            msg.SelectedCardProperty = App.CardModel.SelectedCardPropertyName;
            MemoryStream mstream = _nfcMessage.SerializeMessage(msg);

            var dataWriter = new Windows.Storage.Streams.DataWriter();
            dataWriter.WriteBytes(mstream.GetBuffer());

            // Publish the message
            _publishedMsgId = _proximityDevice.PublishBinaryMessage("Windows.CarTrumps",
                dataWriter.DetachBuffer(), NfcWriteCallback);
            // and subscribe for a reply
            _subscribedMsgId = _proximityDevice.SubscribeForMessage("Windows.CarTrumps",
                NfcMessageReceived);
        }
예제 #27
0
 private Windows.Storage.Streams.IBuffer GetBufferFromBytes(byte[] str)
 {
     using (Windows.Storage.Streams.InMemoryRandomAccessStream memoryStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
     {
         using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(memoryStream))
         {
             dataWriter.WriteBytes(str);
             return dataWriter.DetachBuffer();
         }
     }
 }
예제 #28
0
        private BitmapSource ReadDeviceIndependantBitmap(BinaryReader wmfReader, uint dibSize, out int width, out int height)
        {
            #if NETFX_CORE
            var bmp = new BitmapImage();
            var memStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var dibBytes = wmfReader.ReadBytes((int)dibSize);
            // int imageBytesOffset = 14;

            //System.Runtime.InteropServices.GCHandle pinnedDib = System.Runtime.InteropServices.GCHandle.Alloc(dibBytes, System.Runtime.InteropServices.GCHandleType.Pinned);

            //if (dibBytes[3] == 0x0C)
            //{
            //    imageBytesOffset += 12;
            //}
            //else
            //{
            //    var infoHeader = (BITMAPINFOHEADER)System.Runtime.InteropServices.Marshal.PtrToStructure(pinnedDib.AddrOfPinnedObject(), typeof(BITMAPINFOHEADER));

            //    imageBytesOffset += (int)infoHeader.biSize;

            //    switch ((BitCount)infoHeader.biBitCount)
            //    {
            //        case BitCount.BI_BITCOUNT_1:
            //            // 1 bit - Two colors
            //            imageBytesOffset += 4 * (colorUsed == 0 ? 2 : Math.Min(colorUsed, 2));
            //            break;

            //        case BitCount.BI_BITCOUNT_2:
            //            // 4 bit - 16 colors
            //            imageBytesOffset += 4 * (colorUsed == 0 ? 16 : Math.Min(colorUsed, 16));
            //            break;

            //        case BitCount.BI_BITCOUNT_3:
            //            // 8 bit - 256 colors
            //            imageBytesOffset += 4 * (colorUsed == 0 ? 256 : Math.Min(colorUsed, 256));
            //            break;
            //    }

            //    if ((Compression)infoHeader.biCompression == Compression.BI_BITFIELDS)
            //    {
            //        imageBytesOffset += 12;
            //    }
            //}

            //pinnedDib.Free();

            using (Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter(memStream.GetOutputStreamAt(0)))
            {
                writer.WriteBytes(new byte[] { 66, 77 }); // BM
                writer.WriteUInt32(dibSize + 14);
                writer.WriteBytes(new byte[] { 0, 0, 0, 0 }); // Reserved
                writer.WriteUInt32((UInt32)0);

                writer.WriteBytes(dibBytes);
                var t = writer.StoreAsync();
                t.GetResults();
            }

            // bmp.ImageFailed += bmp_ImageFailed;
            // bmp.ImageOpened += bmp_ImageOpened;
            bmp.SetSource(memStream);
            width = bmp.PixelWidth;
            height = bmp.PixelHeight;
            return bmp;
            #else
            var bmp = new BitmapImage();
            var memStream = new MemoryStream();
            var dibBytes = wmfReader.ReadBytes((int)dibSize);

            BinaryWriter writer = new BinaryWriter(memStream);
            writer.Write(new byte[] { 66, 77 }); // BM
            writer.Write(dibSize + 14);
            writer.Write(new byte[] { 0, 0, 0, 0 }); // Reserved
            writer.Write((UInt32)0);

            writer.Write(dibBytes);
            writer.Flush();

            memStream.Position = 0;
            try
            {
                bmp.BeginInit();
                bmp.StreamSource = memStream;
                bmp.EndInit();
                width = bmp.PixelWidth;
                height = bmp.PixelHeight;

                return bmp;
            }
            catch
            {
                // Bad image;
                width = 0;
                height = 0;

                return null;
            }
            #endif
        }
        /// <summary>
        /// Sends DHCP reply
        /// </summary>
        /// <param name="msgType">Type of DHCP message to send</param>
        /// <param name="ip">IP for client</param>
        /// <param name="replyData">Reply options (will be sent if requested)</param>
        /// <param name="otherForceOptions">Force reply options (will be sent anyway)</param>
        private async void SendDHCPReply(DHCPMsgType msgType, IPAddress ip, DHCPReplyOptions replyData, Dictionary <DHCPOption, byte[]> otherForceOptions, IEnumerable <DHCPOption> forceOptions)
        {
            var replyBuffer = requestData;

            replyBuffer.op     = 2;                    // Reply
            replyBuffer.yiaddr = ip.GetAddressBytes(); // Client's IP
            if (replyData.ServerIpAddress != null)
            {
                replyBuffer.siaddr = replyData.ServerIpAddress.GetAddressBytes();
            }
            replyBuffer.options = CreateOptionStruct(msgType, replyData, otherForceOptions, forceOptions); // Options
            if (!string.IsNullOrEmpty(dhcpServer.ServerName))
            {
                var serverNameBytes = Encoding.ASCII.GetBytes(dhcpServer.ServerName);
                int len             = (serverNameBytes.Length > 63) ? 63 : serverNameBytes.Length;
                Array.Copy(serverNameBytes, replyBuffer.sname, len);
                replyBuffer.sname[len] = 0;
            }
            //lock (requestSocket)
            {
                var DataToSend = BuildDataStructure(replyBuffer);
                if (DataToSend.Length < 300)
                {
                    var sendArray = new byte[300];
                    Array.Copy(DataToSend, 0, sendArray, 0, DataToSend.Length);
                    DataToSend = sendArray;
                }

                if ((replyBuffer.giaddr[0] == 0) && (replyBuffer.giaddr[1] == 0) &&
                    (replyBuffer.giaddr[2] == 0) && (replyBuffer.giaddr[3] == 0))
                {
                    //requestSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
                    //endPoint = new IPEndPoint(dhcpServer.BroadcastAddress, PORT_TO_SEND_TO_CLIENT);

                    //var udp = new UdpClient();
                    //udp.EnableBroadcast = true;
                    //udp.Send(DataToSend, DataToSend.Length, new IPEndPoint(dhcpServer.BroadcastAddress, 68));
                    //udp.Close();

                    var datagramsocket = new Windows.Networking.Sockets.DatagramSocket();

                    using (var stream = await datagramsocket.GetOutputStreamAsync(new Windows.Networking.HostName(dhcpServer.BroadcastAddress), PORT_TO_SEND_TO_CLIENT.ToString()))
                    {
                        using (var datawriter = new Windows.Storage.Streams.DataWriter(stream))
                        {
                            datawriter.WriteBytes(DataToSend);
                            await datawriter.StoreAsync();
                        }
                    }
                }
                else
                {
                    //requestSocket .SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);
                    //endPoint = new IPEndPoint(new IPAddress(replyBuffer.giaddr), PORT_TO_SEND_TO_RELAY);
                    //requestSocket.SendTo(DataToSend, endPoint);

                    using (var stream = await requestSocket.GetOutputStreamAsync(new Windows.Networking.HostName(new IPAddress(replyBuffer.giaddr).ToString()), PORT_TO_SEND_TO_RELAY.ToString()))
                    {
                        using (var datawriter = new Windows.Storage.Streams.DataWriter(stream))
                        {
                            datawriter.WriteBytes(DataToSend);
                            await datawriter.StoreAsync();
                        }
                    }
                }
            }
        }
        private void buttonLoopbackTest_Click(object sender, RoutedEventArgs e)
        {
            // Unicode to ASCII.
            String textToSend = this.textBoxForLoopback.Text;                    
            var encoder = System.Text.Encoding.UTF8.GetEncoder();
            var utf8bytes = new byte[textToSend.Length];
            int bytesUsed, charsUsed;
            bool completed;
            encoder.Convert(textToSend.ToCharArray(), 0, textToSend.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed);

            var writer = new Windows.Storage.Streams.DataWriter();
            writer.WriteBytes(utf8bytes);
            writer.WriteByte(0x00); // NUL
            var buffer = writer.DetachBuffer();

            this.buttonLoopbackTest.IsEnabled = false;
            this.buttonStopLoopback.IsEnabled = true;
            SDKTemplate.MainPage.Current.NotifyUser("", SDKTemplate.NotifyType.StatusMessage);

            var dispatcher = this.Dispatcher;
            ((Action)(async () =>
            {
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async () =>
                {
                    // serialport1 to serialport2

                    var readBuffer = new Windows.Storage.Streams.Buffer(buffer.Length);
                    readBuffer.Length = buffer.Length;

                    var writeTask = this.SerialPortInfo1.Port.Write(buffer, 0, buffer.Length).AsTask();
                    var readTask = this.Read(this.SerialPortInfo2.Port, readBuffer, Constants.InfiniteTimeout).AsTask();

                    try
                    {
                        await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] {writeTask, readTask});
                        readBuffer.Length = (uint)readTask.Result;
                    }
                    catch (System.OperationCanceledException)
                    {
                        // canceled.
                        SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage);
                        this.buttonLoopbackTest.IsEnabled = true;
                        this.buttonStopLoopback.IsEnabled = false;
                        return;
                    }
                    finally
                    {
                        this.cancelTokenSrcOpRead = null;
                        writeTask.AsAsyncAction().Cancel(); // just in case.
                        readTask.AsAsyncAction().Cancel(); // just in case.
                    }

                    var isSame = Util.CompareTo(buffer, readBuffer) == 0;
                    String statusMessage = "";
                    if (isSame)
                    {
                        statusMessage += "CDC device 2 received \"" + textToSend + "\" from CDC device 1. ";
                    }
                    else
                    {
                        statusMessage += "Loopback failed: CDC device 1 to CDC device 2. ";
                    }

                    // serialport2 to serialport1

                    readBuffer.Length = buffer.Length;

                    writeTask = this.SerialPortInfo2.Port.Write(buffer, 0, buffer.Length).AsTask();
                    readTask = this.Read(this.SerialPortInfo1.Port, readBuffer, Constants.InfiniteTimeout).AsTask();

                    try
                    {
                        await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] { writeTask, readTask });
                        readBuffer.Length = (uint)readTask.Result;
                    }
                    catch (System.OperationCanceledException)
                    {
                        // canceled.
                        SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage);
                        this.buttonLoopbackTest.IsEnabled = true;
                        this.buttonStopLoopback.IsEnabled = false;
                        return;
                    }
                    finally
                    {
                        this.cancelTokenSrcOpRead = null;
                        writeTask.AsAsyncAction().Cancel(); // just in case.
                        readTask.AsAsyncAction().Cancel(); // just in case.
                    }

                    isSame = Util.CompareTo(buffer, readBuffer) == 0;
                    if (isSame)
                    {
                        statusMessage += "CDC device 1 received \"" + textToSend + "\" from CDC device 2. ";
                    }
                    else
                    {
                        statusMessage += "Loopback failed: CDC device 2 to CDC device 1. ";
                    }

                    this.buttonLoopbackTest.IsEnabled = true;
                    this.buttonStopLoopback.IsEnabled = false;
                    SDKTemplate.MainPage.Current.NotifyUser(statusMessage, SDKTemplate.NotifyType.StatusMessage);
                }));
            }
            )).Invoke();
        }
예제 #31
0
        private void buttonLoopbackTest_Click(object sender, RoutedEventArgs e)
        {
            // Unicode to ASCII.
            String textToSend = this.textBoxForLoopback.Text;
            var    encoder = System.Text.Encoding.UTF8.GetEncoder();
            var    utf8bytes = new byte[textToSend.Length];
            int    bytesUsed, charsUsed;
            bool   completed;

            encoder.Convert(textToSend.ToCharArray(), 0, textToSend.Length, utf8bytes, 0, utf8bytes.Length, true, out bytesUsed, out charsUsed, out completed);

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

            writer.WriteBytes(utf8bytes);
            writer.WriteByte(0x00); // NUL
            var buffer = writer.DetachBuffer();

            this.buttonLoopbackTest.IsEnabled = false;
            this.buttonStopLoopback.IsEnabled = true;
            SDKTemplate.MainPage.Current.NotifyUser("", SDKTemplate.NotifyType.StatusMessage);

            var dispatcher = this.Dispatcher;

            ((Action)(async() =>
            {
                await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler(async() =>
                {
                    // serialport1 to serialport2

                    var readBuffer = new Windows.Storage.Streams.Buffer(buffer.Length);
                    readBuffer.Length = buffer.Length;

                    var writeTask = this.SerialPortInfo1.Port.Write(buffer, 0, buffer.Length).AsTask();
                    var readTask = this.Read(this.SerialPortInfo2.Port, readBuffer, Constants.InfiniteTimeout).AsTask();

                    try
                    {
                        await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] { writeTask, readTask });
                        readBuffer.Length = (uint)readTask.Result;
                    }
                    catch (System.OperationCanceledException)
                    {
                        // canceled.
                        SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage);
                        this.buttonLoopbackTest.IsEnabled = true;
                        this.buttonStopLoopback.IsEnabled = false;
                        return;
                    }
                    finally
                    {
                        this.cancelTokenSrcOpRead = null;
                        writeTask.AsAsyncAction().Cancel(); // just in case.
                        readTask.AsAsyncAction().Cancel();  // just in case.
                    }

                    var isSame = Util.CompareTo(buffer, readBuffer) == 0;
                    String statusMessage = "";
                    if (isSame)
                    {
                        statusMessage += "CDC device 2 received \"" + textToSend + "\" from CDC device 1. ";
                    }
                    else
                    {
                        statusMessage += "Loopback failed: CDC device 1 to CDC device 2. ";
                    }

                    // serialport2 to serialport1

                    readBuffer.Length = buffer.Length;

                    writeTask = this.SerialPortInfo2.Port.Write(buffer, 0, buffer.Length).AsTask();
                    readTask = this.Read(this.SerialPortInfo1.Port, readBuffer, Constants.InfiniteTimeout).AsTask();

                    try
                    {
                        await System.Threading.Tasks.Task.WhenAll(new System.Threading.Tasks.Task[] { writeTask, readTask });
                        readBuffer.Length = (uint)readTask.Result;
                    }
                    catch (System.OperationCanceledException)
                    {
                        // canceled.
                        SDKTemplate.MainPage.Current.NotifyUser("Canceled", SDKTemplate.NotifyType.ErrorMessage);
                        this.buttonLoopbackTest.IsEnabled = true;
                        this.buttonStopLoopback.IsEnabled = false;
                        return;
                    }
                    finally
                    {
                        this.cancelTokenSrcOpRead = null;
                        writeTask.AsAsyncAction().Cancel(); // just in case.
                        readTask.AsAsyncAction().Cancel();  // just in case.
                    }

                    isSame = Util.CompareTo(buffer, readBuffer) == 0;
                    if (isSame)
                    {
                        statusMessage += "CDC device 1 received \"" + textToSend + "\" from CDC device 2. ";
                    }
                    else
                    {
                        statusMessage += "Loopback failed: CDC device 2 to CDC device 1. ";
                    }

                    this.buttonLoopbackTest.IsEnabled = true;
                    this.buttonStopLoopback.IsEnabled = false;
                    SDKTemplate.MainPage.Current.NotifyUser(statusMessage, SDKTemplate.NotifyType.StatusMessage);
                }));
            }
                      )).Invoke();
        }
예제 #32
0
        public virtual async System.Threading.Tasks.Task <IServiceResponse> PostAsyncWindowsWeb(Uri uri, byte[] audioBytes, apiArgs)
        {
            IServiceResponse response = new IServiceResponse(service);

            try
            {
                // Using HttpClient to grab chunked encoding (partial) responses.
                using (Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient())
                {
                    Log.WriteLine("before requestContent");
                    Log.WriteLine("after requestContent");
                    // rate must be specified but doesn't seem to need to be accurate.

                    Windows.Web.Http.IHttpContent requestContent = null;
                    if (Options.options.APIs.preferChunkedEncodedRequests)
                    {
                        // using chunked transfer requests
                        Log.WriteLine("Using chunked encoding");
                        Windows.Storage.Streams.InMemoryRandomAccessStream contentStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
                        // TODO: obsolete to use DataWriter? use await Windows.Storage.FileIO.Write..(file);
                        Windows.Storage.Streams.DataWriter dw = new Windows.Storage.Streams.DataWriter(contentStream);
                        dw.WriteBytes(audioBytes);
                        await dw.StoreAsync();

                        // GetInputStreamAt(0) forces chunked transfer (sort of undocumented behavior).
                        requestContent = new Windows.Web.Http.HttpStreamContent(contentStream.GetInputStreamAt(0));
                    }
                    else
                    {
                        requestContent = new Windows.Web.Http.HttpBufferContent(audioBytes.AsBuffer());
                    }
                    requestContent.Headers.Add("Content-Type", "audio/l16; rate=" + sampleRate.ToString()); // must add header AFTER contents are initialized

                    Log.WriteLine("Before Post: Elapsed milliseconds:" + stopWatch.ElapsedMilliseconds);
                    response.RequestElapsedMilliseconds = stopWatch.ElapsedMilliseconds;
                    using (Windows.Web.Http.HttpResponseMessage hrm = await httpClient.PostAsync(uri, requestContent))
                    {
                        response.RequestElapsedMilliseconds = stopWatch.ElapsedMilliseconds - response.RequestElapsedMilliseconds;
                        response.StatusCode = (int)hrm.StatusCode;
                        Log.WriteLine("After Post: StatusCode:" + response.StatusCode + " Total milliseconds:" + stopWatch.ElapsedMilliseconds + " Request milliseconds:" + response.RequestElapsedMilliseconds);
                        if (hrm.StatusCode == Windows.Web.Http.HttpStatusCode.Ok)
                        {
                            string responseContents = await hrm.Content.ReadAsStringAsync();

                            string[] responseJsons = responseContents.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                            foreach (string rj in responseJsons)
                            {
                                response.ResponseJson = rj;
                                Newtonsoft.Json.Linq.JToken ResponseBodyToken = Newtonsoft.Json.Linq.JObject.Parse(response.ResponseJson);
                                response.ResponseJsonFormatted = Newtonsoft.Json.JsonConvert.SerializeObject(ResponseBodyToken, new Newtonsoft.Json.JsonSerializerSettings()
                                {
                                    Formatting = Newtonsoft.Json.Formatting.Indented
                                });
                                if (Options.options.debugLevel >= 4)
                                {
                                    Log.WriteLine(response.ResponseJsonFormatted);
                                }
                                Newtonsoft.Json.Linq.JToken tokResult = ProcessResponse(ResponseBodyToken);
                                if (tokResult == null || string.IsNullOrEmpty(tokResult.ToString()))
                                {
                                    response.ResponseResult = Options.options.Services.APIs.SpeechToText.missingResponse;
                                    if (Options.options.debugLevel >= 3)
                                    {
                                        Log.WriteLine("ResponseResult:" + response.ResponseResult);
                                    }
                                }
                                else
                                {
                                    response.ResponseResult = tokResult.ToString();
                                    if (Options.options.debugLevel >= 3)
                                    {
                                        Log.WriteLine("ResponseResult:" + tokResult.Path + ": " + response.ResponseResult);
                                    }
                                }
                            }
                        }
                        else
                        {
                            response.ResponseResult = hrm.ReasonPhrase;
                            Log.WriteLine("PostAsync Failed: StatusCode:" + hrm.ReasonPhrase + "(" + response.StatusCode.ToString() + ")");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine("Exception:" + ex.Message);
                if (ex.InnerException != null)
                {
                    Log.WriteLine("InnerException:" + ex.InnerException);
                }
            }
            return(response);
        }
예제 #33
0
        private async void SaveDocument(IPlotModel model, String newDocument)
        {
            if (model == null)
            {
                var msg = new MessageDialog("График не создан, рассчитайте распределение", "Ошибка сохранения");
                await msg.ShowAsync();
                return;
            }

            var savePicker = new Windows.Storage.Pickers.FileSavePicker
            {
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary
            };
            savePicker.FileTypeChoices.Add("PDF Document", new List<string>() { ".pdf" });
            savePicker.SuggestedFileName = newDocument;
            StorageFile file = await savePicker.PickSaveFileAsync();
            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                var stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            var pdf = new PdfExporter();
                            PdfExporter.Export(model, memoryStream, 1000, 400);
                            var bt = memoryStream.ToArray();
                            dataWriter.WriteBytes(bt);
                            await dataWriter.StoreAsync();
                            await outputStream.FlushAsync();
                        }
                    }
                }
                var status = await CachedFileManager.CompleteUpdatesAsync(file);
                if (status == FileUpdateStatus.Complete)
                {
                    var msg = new MessageDialog("По пути " + file.Path, "Файл сохранен");
                    await msg.ShowAsync();
                }
                else
                {
                    var msg = new MessageDialog("Произошла ошибка сохранения");
                    await msg.ShowAsync();
                }
            }
        }