private void PublishLaunchApp()
        {
            proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

            if (proximityDevice != null)
            {
                // The format of the app launch string is: "<args>\tWindows\t<AppName>".
                // The string is tab or null delimited.

                // The <args> string can be an empty string ("").
                string launchArgs = "user=default";

                // The format of the AppName is: PackageFamilyName!PRAID.
                string praid = "{b8c21b6b-2f16-49f6-9ee9-b3a713c54500}"; // The Application Id value from your package.appxmanifest.

                string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;

                string launchAppMessage = launchArgs + "\tWindows\t" + appName;

                var dataWriter = new Windows.Storage.Streams.DataWriter();
                dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                dataWriter.WriteString(launchAppMessage);
                var launchAppPubId =
                proximityDevice.PublishBinaryMessage(
                    "LaunchApp:WriteTag", dataWriter.DetachBuffer());
            }
        }
예제 #2
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());
        }
        async void InitializeBluetooth()
        {
            try
            {
                var service_id = RfcommServiceId.FromUuid(Guid.Parse("ff1477c2-7265-4d55-bb08-c3c32c6d635c"));
                provider = await RfcommServiceProvider.CreateAsync(service_id);

                StreamSocketListener listener = new StreamSocketListener();
                listener.ConnectionReceived += OnConnectionReceived;
                await listener.BindServiceNameAsync(
                    provider.ServiceId.AsString(),
                    SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

                // InitializeServiceSdpAttributes
                var writer = new Windows.Storage.Streams.DataWriter();
                writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE);
                writer.WriteUInt32(SERVICE_VERSION);
                var data = writer.DetachBuffer();
                provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data);

                provider.StartAdvertising(listener, true);
            }
            catch (Exception error)
            {
                Debug.WriteLine(error.ToString());
            }
        }
예제 #4
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());
        }
예제 #5
0
        private void PublishLaunchApp()
        {
            proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

            if (proximityDevice != null)
            {
                // The format of the app launch string is: "<args>\tWindows\t<AppName>".
                // The string is tab or null delimited.

                // The <args> string must have at least one character.
                string launchArgs = "user=default";

                // The format of the AppName is: PackageFamilyName!PRAID.
                string praid = "MyAppId"; // The Application Id value from your package.appxmanifest.

                string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;

                string launchAppMessage = launchArgs + "\tWindows\t" + appName;

                var dataWriter = new Windows.Storage.Streams.DataWriter();
                dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                dataWriter.WriteString(launchAppMessage);
                var launchAppPubId =
                    proximityDevice.PublishBinaryMessage(
                        "LaunchApp:WriteTag", dataWriter.DetachBuffer());
            }
        }
            /// <summary>
            /// SET_LINE_CODING CDC request.
            /// </summary>
            /// <param name="index">Interface index.</param>
            /// <param name="dteRate">Data terminal rate, in bits per second.</param>
            /// <param name="charFormat">Stop bits.</param>
            /// <param name="parityType">Parity.</param>
            /// <param name="dataBits">Data bits.</param>
            /// <returns>
            /// The result of Task contains a length of bytes actually sent to the serial port.
            /// </returns>
            private Task <uint> SetLineCoding(
                uint index,
                uint dteRate,
                byte charFormat,
                byte parityType,
                byte dataBits
                )
            {
                // SetLineCoding
                var writer = new Windows.Storage.Streams.DataWriter();

                writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;
                writer.WriteUInt32(dteRate);
                writer.WriteByte(charFormat);
                writer.WriteByte(parityType);
                writer.WriteByte(dataBits);
                var buffer = writer.DetachBuffer();

                var requestType = new UsbControlRequestType();

                requestType.AsByte = RequestType.Set;

                return(UsbControlRequestForSet(
                           index,
                           requestType,
                           RequestCode.SetLineCoding,
                           0,
                           buffer));
            }
예제 #7
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);
            }
        }
예제 #8
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);
        }
예제 #9
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());
         }
     }
 }
예제 #10
0
        /// <summary>
        /// This is the click handler for the 'scenario3BtnBuffer' button.  You would replace this with your own handler
        /// if you have a button or buttons on this page.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Scenario3BtnBuffer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get load settings
                var loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings();
                if (true == scenario3RB1.IsChecked)
                {
                    loadSettings.ProhibitDtd      = true;   // DTD is prohibited
                    loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
                }
                else if (true == scenario3RB2.IsChecked)
                {
                    loadSettings.ProhibitDtd      = false;  // DTD is not prohibited
                    loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
                }
                else if (true == scenario3RB3.IsChecked)
                {
                    loadSettings.ProhibitDtd      = false;  // DTD is not prohibited
                    loadSettings.ResolveExternals = true;   // Enable the resolve to external definitions such as external DTD
                }

                String xml;

                scenario3OriginalData.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml);

                // Set external dtd file path
                if (loadSettings.ResolveExternals == true && loadSettings.ProhibitDtd == false)
                {
                    Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("loadExternaldtd");

                    String dtdPath = storageFolder.Path + "\\dtd.txt";
                    xml = xml.Replace("dtd.txt", dtdPath);
                }

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

                dataWriter.WriteString(xml);

                Windows.Storage.Streams.IBuffer ibuffer = dataWriter.DetachBuffer();

                var doc = new Windows.Data.Xml.Dom.XmlDocument();

                doc.LoadXmlFromBuffer(ibuffer, loadSettings);

                Scenario.RichEditBoxSetMsg(scenario3Result, doc.GetXml(), true);
            }
            catch (Exception)
            {
                // After loadSettings.ProhibitDtd is set to true, the exception is expected as the sample XML contains DTD
                Scenario.RichEditBoxSetError(scenario3Result, "Error: DTD is prohibited");
            }
        }
예제 #11
0
        static void InitializeServiceSdpAttributes(RfcommServiceProvider provider)
        {
            var writer = new Windows.Storage.Streams.DataWriter();

            // First write the attribute type
            writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE);
            // Then write the data
            writer.WriteUInt32(SERVICE_VERSION);

            var data = writer.DetachBuffer();

            provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data);
        }
        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);
            }
        }
예제 #13
0
        private void radioButtonDataFormat_Checked(object sender, RoutedEventArgs e)
        {
            if (sender.Equals(this.radioButtonAscii))
            {
                var binary    = this.textBoxReadBulkInLogger.Text;
                var separator = new String[1];
                separator[0] = " ";
                var byteArray = binary.Split(separator, StringSplitOptions.None);

                // Binary to Unicode.
                uint strlen = 0;
                var  writer = new Windows.Storage.Streams.DataWriter();
                writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                foreach (var onebyte in byteArray)
                {
                    if (onebyte.Length < 2)
                    {
                        continue;
                    }
                    writer.WriteByte(byte.Parse(onebyte, System.Globalization.NumberStyles.HexNumber));
                    strlen++;
                }

                var reader = Windows.Storage.Streams.DataReader.FromBuffer(writer.DetachBuffer());
                this.textBoxReadBulkInLogger.Text = reader.ReadString(strlen);
            }
            else if (sender.Equals(this.radioButtonBinary))
            {
                var ascii = this.textBoxReadBulkInLogger.Text;

                // Unicode to ASCII.
                var chars  = ascii.ToCharArray(0, ascii.Length);
                var writer = new Windows.Storage.Streams.DataWriter();
                writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                foreach (var onechar in chars)
                {
                    writer.WriteByte((byte)onechar);
                }

                var str = Util.BinaryBufferToBinaryString(writer.DetachBuffer());
                this.textBoxReadBulkInLogger.Text = str;
            }
        }
예제 #14
0
        private async Task<int> send_command_async (string command, bool use_send_characteristic = true)
        {
            if (ganglion_device == null)
            {
                return (int) CustomExitCodes.GANGLION_IS_NOT_OPEN_ERROR;
            }
            if (send_characteristic == null)
            {
                return (int) CustomExitCodes.SEND_CHARACTERISTIC_NOT_FOUND_ERROR;
            }

            var writer = new Windows.Storage.Streams.DataWriter ();
            writer.WriteString (command);
            try
            {
                GattWriteResult result = null;
                if (use_send_characteristic)
                {
                    result = await send_characteristic.WriteValueWithResultAsync (writer.DetachBuffer ()).AsTask ().TimeoutAfter (timeout);
                }
                else
                {
                    result = await disconnect_characteristic.WriteValueWithResultAsync (writer.DetachBuffer ()).AsTask ().TimeoutAfter (timeout);
                }
                if (result.Status == GattCommunicationStatus.Success)
                {
                    return (int) CustomExitCodes.STATUS_OK;
                }
                else
                {
                    return (int) CustomExitCodes.STOP_ERROR;
                }
            }
            catch (TimeoutException e)
            {
                return (int) CustomExitCodes.TIMEOUT_ERROR;
            }
            catch (Exception e)
            {
                return (int) CustomExitCodes.GENERAL_ERROR;
            }
            return (int) CustomExitCodes.STATUS_OK;
        }
예제 #15
0
        private async void findDevices()
        {
            //var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess));
            var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(new Guid("19B10000-E8F2-537E-4F6C-D104768A1214")));

            if (devices.Count == 0)
            {
                textBox.Text = "Devices not found!";
                return;
            }

            //Connect to the service
            var service = await GattDeviceService.FromIdAsync(devices[0].Id);

            if (service == null)
            {
                return;
            }
            //Obtain the characteristic we want to interact with
            //var characteristics = service.GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(0x2A00));
            var characteristics = service.GetCharacteristics(new Guid("19B10001-E8F2-537E-4F6C-D104768A1214"));

            characteristic = characteristics[0];
            //Read the value
            var writer = new Windows.Storage.Streams.DataWriter();

            writer.WriteByte(12);
            await characteristic.WriteValueAsync(writer.DetachBuffer());

            var valueBytes = (await characteristic.ReadValueAsync()).Value.ToArray();
            var value      = await characteristic.ReadValueAsync();

            //Convert to string
            //var deviceName = System.Text.Encoding.UTF8.GetString(deviceNameBytes, 0, deviceNameBytes.Length);
            characteristic.ValueChanged += Characteristic_ValueChanged;

            await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

            textBox.Text = valueBytes[0].ToString();
        }
예제 #16
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();
            }
        }
예제 #17
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);
        }
예제 #18
0
        // Handles PeerFinder_AdvertiseButton click
        void PeerFinder_StartAdvertising(object sender, RoutedEventArgs e)
        {
            // If PeerFinder is started, stop it, so that new properties
            // selected by the user (Role/DiscoveryData) can be updated.
            PeerFinder_StopAdvertising(sender, e);

            rootPage.NotifyUser("", NotifyType.ErrorMessage);
            if (!_peerFinderStarted)
            {
                // attach the callback handler (there can only be one PeerConnectProgress handler).
                PeerFinder.TriggeredConnectionStateChanged += new TypedEventHandler<object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler);
                // attach the incoming connection request event handler
                PeerFinder.ConnectionRequested += new TypedEventHandler<object, ConnectionRequestedEventArgs>(PeerConnectionRequested);

                // Set the PeerFinder.Role property
                switch (PeerFinder_SelectRole.SelectionBoxItem.ToString())
                {
                    case "Peer":
                        PeerFinder.Role = PeerRole.Peer;
                        break;
                    case "Host":
                        PeerFinder.Role = PeerRole.Host;
                        break;
                    case "Client":
                        PeerFinder.Role = PeerRole.Client;
                        break;
                }

                // Set DiscoveryData property if the user entered some text
                if ((PeerFinder_DiscoveryData.Text.Length > 0) && (PeerFinder_DiscoveryData.Text != "What's happening today?"))
                {
                    using (var discoveryDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream()))
                    {
                        discoveryDataWriter.WriteString(PeerFinder_DiscoveryData.Text);
                        PeerFinder.DiscoveryData = discoveryDataWriter.DetachBuffer();
                    }
                }

                // start listening for proximate peers
                PeerFinder.Start();
                _peerFinderStarted = true;
                PeerFinder_StopAdvertiseButton.Visibility = Visibility.Visible;
                PeerFinder_ConnectButton.Visibility = Visibility.Visible;

                if (_browseConnectSupported && _triggeredConnectSupported)
                {
                    rootPage.NotifyUser("Click Browse for Peers button or tap another device to connect to a peer.", NotifyType.StatusMessage);
                    PeerFinder_BrowseGrid.Visibility = Visibility.Visible;
                }
                else if (_triggeredConnectSupported)
                {
                    rootPage.NotifyUser("Tap another device to connect to a peer.", NotifyType.StatusMessage);
                }
                else if (_browseConnectSupported)
                {
                    rootPage.NotifyUser("Click Browse for Peers button.", NotifyType.StatusMessage);
                    PeerFinder_BrowseGrid.Visibility = Visibility.Visible;
                }
            }
        }
        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();
        }
예제 #20
0
        private void PublishLaunchApp(ProximityDevice proximityDevice)
        {
            //var proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

            if (proximityDevice != null)
            {
                                // The format of the app launch string is:
                                // <args>\tWindows\t<AppFamilyBasedName>\tWindowsPhone\t<AppGUID>
                                // The string is tab delimited.

                                // The <args> string must have at least one character.
                                string launchArgs = "user=default";


                                                      // The format of the AppFamilyBasedName is: PackageFamilyName!PRAID.
                                string praid = "App"; // The Application Id value from your package.appxmanifest.
                                string appFamilyBasedName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;


                // GUID is PhoneProductId value from you package.appxmanifest
                // NOTE: The GUID will change after you associate app to the app store
                // Consider using windows.applicationmodel.store.currentapp.appid after the app is associated to the store.
                string appGuid = "{55d006ef-be06-4019-bc6d-ec38f28a5304}";

                string launchAppMessage = launchArgs +
                                          "\tWindows\t" + appFamilyBasedName +
                                          "\tWindowsPhone\t" + appGuid;

                var dataWriter = new Windows.Storage.Streams.DataWriter();
                dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                dataWriter.WriteString(launchAppMessage);
                var launchAppPubId = proximityDevice.PublishBinaryMessage("LaunchApp:WriteTag", dataWriter.DetachBuffer());
            }
        }
예제 #21
0
        private void radioButtonDataFormat_Checked(object sender, RoutedEventArgs e)
        {
            if (sender.Equals(this.radioButtonAscii))
            {
                var binary = this.textBoxReadBulkInLogger.Text;
                var separator = new String[1];
                separator[0] = " ";
                var byteArray = binary.Split(separator, StringSplitOptions.None);

                // Binary to Unicode.
                uint strlen = 0;
                var writer = new Windows.Storage.Streams.DataWriter();
                writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                foreach (var onebyte in byteArray)
                {
                    if (onebyte.Length < 2)
                    {
                        continue;
                    }
                    writer.WriteByte(byte.Parse(onebyte, System.Globalization.NumberStyles.HexNumber));
                    strlen++;
                }
                
                var reader = Windows.Storage.Streams.DataReader.FromBuffer(writer.DetachBuffer());
                this.textBoxReadBulkInLogger.Text = reader.ReadString(strlen);
            }
            else if (sender.Equals(this.radioButtonBinary))
            {
                var ascii = this.textBoxReadBulkInLogger.Text;

                // Unicode to ASCII.
                var chars = ascii.ToCharArray(0, ascii.Length);
                var writer = new Windows.Storage.Streams.DataWriter();
                writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                foreach (var onechar in chars)
                {
                    writer.WriteByte((byte)onechar);
                }

                var str = Util.BinaryBufferToBinaryString(writer.DetachBuffer());
                this.textBoxReadBulkInLogger.Text = str;
            }
        }
        public async Task <AsyncHandleListResult> DiscoverServicesAsync(string serviceName, bool fExpectResults = true, string serviceInfo = "")
        {
            List <WFDSvcWrapperHandle> results = new List <WFDSvcWrapperHandle>();
            Exception error   = null;
            bool      success = false;

            try
            {
                ThrowIfDisposed();

                WiFiDirectTestLogger.Log("Discover Services... (ServiceName={0}, ServiceInfo={1})", serviceName, serviceInfo);

                string serviceSelector = "";
                if (serviceInfo == "")
                {
                    serviceSelector = WiFiDirectService.GetSelector(serviceName);
                }
                else
                {
                    using (var serviceInfoDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream()))
                    {
                        serviceInfoDataWriter.WriteString(serviceInfo);
                        serviceSelector = WiFiDirectService.GetSelector(serviceName, serviceInfoDataWriter.DetachBuffer());
                    }
                }

                WiFiDirectTestLogger.Log("FindAllAsync... Using Selector: {0}", serviceSelector);

                List <string> additionalProperties = new List <string>();
                additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceAddress");
                additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceName");
                additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceInformation");
                additionalProperties.Add("System.Devices.WiFiDirectServices.AdvertisementId");
                additionalProperties.Add("System.Devices.WiFiDirectServices.ServiceConfigMethods");

                DeviceInformationCollection deviceInfoCollection = await DeviceInformation.FindAllAsync(serviceSelector, additionalProperties);

                WiFiDirectTestLogger.Log(
                    "FindAllAsync...DONE Got {0} results",
                    (deviceInfoCollection == null) ? 0 : deviceInfoCollection.Count
                    );

                if (deviceInfoCollection == null || deviceInfoCollection.Count == 0)
                {
                    if (fExpectResults)
                    {
                        WiFiDirectTestLogger.Error("No services found!");
                        throw new Exception("Expected services discovered, found none!");
                    }
                    else
                    {
                        WiFiDirectTestLogger.Log("No services found (expected)");
                    }
                }
                else
                {
                    if (!fExpectResults)
                    {
                        WiFiDirectTestLogger.Error("Services found, none expected!");
                        throw new Exception("Expected no services discovered, found at least 1!");
                    }
                    else
                    {
                        // NOTE: we don't clear this list
                        // Possible to discover A, discover B, then connect to A because its entry still exists
                        foreach (DeviceInformation deviceInfo in deviceInfoCollection)
                        {
                            WiFiDirectTestLogger.Log(
                                "Adding discovered service (Id={0}, Name={1})",
                                deviceInfo.Id,
                                deviceInfo.Name
                                );

                            DiscoveredService discovered = new DiscoveredService(deviceInfo, this, this, this);
                            discoveryCollection.Add(discovered.Handle, discovered);

                            results.Add(discovered.Handle);
                        }
                    }
                }

                success = true;
            }
            catch (Exception ex)
            {
                WiFiDirectTestLogger.Error("Exception in DiscoverServicesAsync");
                error = ex;
            }

            return(new AsyncHandleListResult(results, success, error));
        }
        /// <summary>
        /// Start advertising a service
        /// </summary>
        /// <param name="serviceName"></param>
        /// <param name="autoAccept"></param>
        /// <param name="preferGO"></param>
        /// <param name="configMethods"></param>
        /// <param name="status"></param>
        /// <param name="customStatus"></param>
        /// <param name="serviceInfo"></param>
        /// <param name="deferredServiceInfo"></param>
        /// <returns></returns>
        public WFDSvcWrapperHandle PublishService(
            string serviceName,
            bool autoAccept = true,
            bool preferGO   = true,
            List <WiFiDirectServiceConfigurationMethod> configMethods = null,
            WiFiDirectServiceStatus status = WiFiDirectServiceStatus.Available,
            uint customStatus          = 0,
            string serviceInfo         = "",
            string deferredServiceInfo = "",
            List <String> prefixList   = null
            )
        {
            ThrowIfDisposed();

            WiFiDirectTestLogger.Log("Creating Service: \"{0}\"", serviceName);

            WiFiDirectServiceAdvertiser advertiser = new WiFiDirectServiceAdvertiser(serviceName);

            advertiser.AutoAcceptSession       = autoAccept;
            advertiser.PreferGroupOwnerMode    = preferGO;
            advertiser.ServiceStatus           = status;
            advertiser.CustomServiceStatusCode = customStatus;

            if (serviceInfo != null && serviceInfo.Length > 0)
            {
                using (var serviceInfoDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream()))
                {
                    serviceInfoDataWriter.WriteString(serviceInfo);
                    advertiser.ServiceInfo = serviceInfoDataWriter.DetachBuffer();
                }
                WiFiDirectTestLogger.Log("Included Service Info: \"{0}\"", WiFiDirectTestUtilities.GetTruncatedString(serviceInfo));
            }
            else
            {
                advertiser.ServiceInfo = null;
            }

            if (deferredServiceInfo != null && deferredServiceInfo.Length > 0)
            {
                using (var deferredSessionInfoDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream()))
                {
                    deferredSessionInfoDataWriter.WriteString(deferredServiceInfo);
                    advertiser.DeferredSessionInfo = deferredSessionInfoDataWriter.DetachBuffer();
                }
                WiFiDirectTestLogger.Log("Included Session Info: \"{0}\"", WiFiDirectTestUtilities.GetTruncatedString(deferredServiceInfo));
            }
            else
            {
                advertiser.DeferredSessionInfo = null;
            }

            if (configMethods != null)
            {
                advertiser.PreferredConfigurationMethods.Clear();
                foreach (var configMethod in configMethods)
                {
                    advertiser.PreferredConfigurationMethods.Add(configMethod);
                    WiFiDirectTestLogger.Log("Added config method {0}", configMethod.ToString());
                }
            }

            if (prefixList != null && prefixList.Count > 0)
            {
                advertiser.ServiceNamePrefixes.Clear();
                foreach (var prefix in prefixList)
                {
                    advertiser.ServiceNamePrefixes.Add(prefix);
                    WiFiDirectTestLogger.Log("Added prefix {0}", prefix);
                }
            }

            ServiceAdvertiser advertiserWrapper = new ServiceAdvertiser(advertiser, this, this, this);

            advertiserCollection.Add(advertiserWrapper.Handle, advertiserWrapper);

            WiFiDirectTestLogger.Log("Starting Service: \"{1}\" (Advertiser={0})", advertiserWrapper.Handle, serviceName);
            advertiser.Start();

            return(advertiserWrapper.Handle);
        }
        /// <summary>
        /// This is the click handler for the 'scenario3BtnBuffer' button.  You would replace this with your own handler
        /// if you have a button or buttons on this page.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Scenario3BtnBuffer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get load settings
                var loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings();
                if (true == scenario3RB1.IsChecked)
                {
                    loadSettings.ProhibitDtd = true;        // DTD is prohibited
                    loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
                }
                else if (true == scenario3RB2.IsChecked)
                {
                    loadSettings.ProhibitDtd = false;       // DTD is not prohibited
                    loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
                }
                else if (true == scenario3RB3.IsChecked)
                {
                    loadSettings.ProhibitDtd = false;       // DTD is not prohibited
                    loadSettings.ResolveExternals = true;   // Enable the resolve to external definitions such as external DTD
                }

                String xml;

                scenario3OriginalData.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml);

                // Set external dtd file path
                if (loadSettings.ResolveExternals == true && loadSettings.ProhibitDtd == false)
                {
                    Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("loadExternaldtd");
                    String dtdPath = storageFolder.Path + "\\dtd.txt";
                    xml = xml.Replace("dtd.txt", dtdPath);
                }

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

                dataWriter.WriteString(xml);

                Windows.Storage.Streams.IBuffer ibuffer = dataWriter.DetachBuffer();

                var doc = new Windows.Data.Xml.Dom.XmlDocument();

                doc.LoadXmlFromBuffer(ibuffer, loadSettings);

                Scenario.RichEditBoxSetMsg(scenario3Result, doc.GetXml(), true);
            }
            catch (Exception)
            {
                // After loadSettings.ProhibitDtd is set to true, the exception is expected as the sample XML contains DTD
                Scenario.RichEditBoxSetError(scenario3Result, "Error: DTD is prohibited");
            }
        }
        // Click event for "Advertise" button.
        void AdvertiseForPeers(object sender, RoutedEventArgs e)
        {
            if (!started)
            {
                Windows.Networking.Proximity.PeerFinder.DisplayName = DisplayNameTextBox.Text;

                if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                     Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered) ==
                    Windows.Networking.Proximity.PeerDiscoveryTypes.Triggered)
                {
                    Windows.Networking.Proximity.PeerFinder.TriggeredConnectionStateChanged +=
                        TriggeredConnectionStateChanged;

                    WriteMessageText("You can tap to connect a peer device that is " +
                                     "also advertising for a connection.\n");
                }
                else
                {
                    WriteMessageText("Tap to connect is not supported.\n");
                }

                if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes &
                     Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) !=
                    Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
                {
                    WriteMessageText("Peer discovery using Wi-Fi Direct is not supported.\n");
                }

                // Set the peer role selected by the user.
                if (launchedByTap)
                {
                    Windows.Networking.Proximity.PeerFinder.Role = appRole;
                }
                else
                {
                    switch (GetRoleFromUser())
                    {
                    case "Peer":
                        Windows.Networking.Proximity.PeerFinder.Role =
                            Windows.Networking.Proximity.PeerRole.Peer;
                        break;

                    case "Host":
                        Windows.Networking.Proximity.PeerFinder.Role =
                            Windows.Networking.Proximity.PeerRole.Host;
                        break;

                    case "Client":
                        Windows.Networking.Proximity.PeerFinder.Role =
                            Windows.Networking.Proximity.PeerRole.Client;
                        break;
                    }
                }

                // Set discoveryData property with user supplied text.
                var discData = GetDiscoveryDataFromUser();
                var writer   = new Windows.Storage.Streams.DataWriter(
                    new Windows.Storage.Streams.InMemoryRandomAccessStream());
                writer.WriteString(discData);
                Windows.Networking.Proximity.PeerFinder.DiscoveryData =
                    writer.DetachBuffer();

                Windows.Networking.Proximity.PeerFinder.Start();
                started = true;
            }
        }
예제 #26
0
            /// <summary>
            /// SET_LINE_CODING CDC request.
            /// </summary>
            /// <param name="index">Interface index.</param>
            /// <param name="dteRate">Data terminal rate, in bits per second.</param>
            /// <param name="charFormat">Stop bits.</param>
            /// <param name="parityType">Parity.</param>
            /// <param name="dataBits">Data bits.</param>
            /// <returns>
            /// The result of Task contains a length of bytes actually sent to the serial port.
            /// </returns>
           private Task<uint> SetLineCoding(
                uint index,
                uint dteRate,
                byte charFormat,
                byte parityType,
                byte dataBits
            )
            {
                // SetLineCoding
                var writer = new Windows.Storage.Streams.DataWriter();
                writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;
                writer.WriteUInt32(dteRate);
                writer.WriteByte(charFormat);
                writer.WriteByte(parityType);
                writer.WriteByte(dataBits);
                var buffer = writer.DetachBuffer();

                var requestType = new UsbControlRequestType();
                requestType.AsByte = RequestType.Set;

                return UsbControlRequestForSet(
                        index,
                        requestType,
                        RequestCode.SetLineCoding,
                        0,
                        buffer);
            }
예제 #27
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();
        }
예제 #28
0
    public void toggleAllDigitalPinsV2(bool setPinsHigh)
    {
      //a DataWriter object uses an IBuffer as its backing storage
      //we'll write our data to this object and detach the buffer to invoke sendSysex()
      Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter();

      //we're defining our own command, so we're free to encode it how we want.
      //let's send a '1' if we want the pins HIGH, and a 0 for LOW
      writer.WriteByte((byte)(setPinsHigh ? 1 : 0));

      //invoke the sendSysex command with ALL_PINS_COMMAND and our data payload as an IBuffer
      //firmata.@lock();
      firmata.sendSysex(ALL_PINS_COMMAND, writer.DetachBuffer());
      //firmata.@unlock();
    }
예제 #29
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);
            }
        }
예제 #30
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);
        }
예제 #31
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();
         }
     }
 }
        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();
            }
        }
        private async Task <bool> InitialKickEvents()
        {
            var   writer = new Windows.Storage.Streams.DataWriter();
            short val    = 0x0100;

            writer.WriteInt16(val);
            GattCommunicationStatus writeResult = await writeCharacteristic.WriteValueAsync(writer.DetachBuffer());

            bool success = writeResult == GattCommunicationStatus.Success;

            return(success);
        }
예제 #34
0
        // Handles PeerFinder_AdvertiseButton click
        void PeerFinder_StartAdvertising(object sender, RoutedEventArgs e)
        {
            // If PeerFinder is started, stop it, so that new properties
            // selected by the user (Role/DiscoveryData) can be updated.
            PeerFinder_StopAdvertising(sender, e);

            rootPage.NotifyUser("", NotifyType.ErrorMessage);
            if (!_peerFinderStarted)
            {
                // attach the callback handler (there can only be one PeerConnectProgress handler).
                PeerFinder.TriggeredConnectionStateChanged += new TypedEventHandler <object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler);
                // attach the incoming connection request event handler
                PeerFinder.ConnectionRequested += new TypedEventHandler <object, ConnectionRequestedEventArgs>(PeerConnectionRequested);

                // Set the PeerFinder.Role property
                switch (PeerFinder_SelectRole.SelectionBoxItem.ToString())
                {
                case "Peer":
                    PeerFinder.Role = PeerRole.Peer;
                    break;

                case "Host":
                    PeerFinder.Role = PeerRole.Host;
                    break;

                case "Client":
                    PeerFinder.Role = PeerRole.Client;
                    break;
                }

                // Set DiscoveryData property if the user entered some text
                if ((PeerFinder_DiscoveryData.Text.Length > 0) && (PeerFinder_DiscoveryData.Text != "What's happening today?"))
                {
                    using (var discoveryDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream()))
                    {
                        discoveryDataWriter.WriteString(PeerFinder_DiscoveryData.Text);
                        PeerFinder.DiscoveryData = discoveryDataWriter.DetachBuffer();
                    }
                }

                // start listening for proximate peers
                PeerFinder.Start();
                _peerFinderStarted = true;
                PeerFinder_StopAdvertiseButton.Visibility = Visibility.Visible;
                PeerFinder_ConnectButton.Visibility       = Visibility.Visible;

                if (_browseConnectSupported && _triggeredConnectSupported)
                {
                    rootPage.NotifyUser("Click Browse for Peers button or tap another device to connect to a peer.", NotifyType.StatusMessage);
                    PeerFinder_BrowseGrid.Visibility = Visibility.Visible;
                }
                else if (_triggeredConnectSupported)
                {
                    rootPage.NotifyUser("Tap another device to connect to a peer.", NotifyType.StatusMessage);
                }
                else if (_browseConnectSupported)
                {
                    rootPage.NotifyUser("Click Browse for Peers button.", NotifyType.StatusMessage);
                    PeerFinder_BrowseGrid.Visibility = Visibility.Visible;
                }
            }
        }