Beispiel #1
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);
            }
        }
Beispiel #2
0
        private void WriteToNFCButton_Click(object sender, RoutedEventArgs e)
        {
            // make sure the device exists and was initialized
            if (_proximityDevice == null)
            {
                return;
            }

            // cancel if it's currently publishing a message
            if (_publishedUriId != -1)
            {
                _proximityDevice.StopPublishingMessage(_publishedUriId);
            }

            //Encoding the URL we write (must be Utf16)
            var dataWriter = new DataWriter {
                UnicodeEncoding = UnicodeEncoding.Utf16LE
            };

            //Capacity of tags differs
            dataWriter.WriteString(UriTextBox.Text);

            var dataBuffer = dataWriter.DetachBuffer();

            // write our data to the tag, handler will get called upon successful transmission
            _publishedUriId = _proximityDevice.PublishBinaryMessage("WindowsUri:WriteTag", dataBuffer, messageTransmittedHandler);
        }
Beispiel #3
0
        public void WriteTag(NdefLibrary.Ndef.NdefMessage message)
        {
            int messageSize = 0;

            foreach (NdefRecord record in message)
            {
                messageSize += record.Payload.Length;
                if (!record.CheckIfValid())
                {
                    throw new Exception("A record on NDEFMessage is not valid");
                }
            }

            if (!isTagPresent)
            {
                throw new Exception("No Tag present or Tag is incompatible ");
            }

            if (!nfcTag.IsWriteable)
            {
                throw new Exception("Tag is write locked ");
            }

            if (nfcTag.MaxSize < messageSize)
            {
                throw new Exception("Tag is too small for this message");
            }

            RaiseTagConnected(nfcTag);

            nfcDevice.PublishBinaryMessage("NDEF:WriteTag", message.ToByteArray().AsBuffer(), writerHandler);
        }
Beispiel #4
0
        private void PublishRecord(NdefRecord record, bool writeToTag)
        {
            if (_device == null)
            {
                return;
            }
            // Make sure we're not already publishing another message
            StopPublishingMessage(false);
            // Wrap the NDEF record into an NDEF message
            var message = new NdefMessage {
                record
            };
            // Convert the NDEF message to a byte array
            var msgArray = message.ToByteArray();

            try
            {
                // Publish the NDEF message to a tag or to another device, depending on the writeToTag parameter
                // Save the publication ID so that we can cancel publication later
                _publishingMessageId = _device.PublishBinaryMessage((writeToTag ? "NDEF:WriteTag" : "NDEF"), msgArray.AsBuffer(), MessageWrittenHandler);
                // Update status text for UI
                SetStatusOutput(string.Format(_loader.GetString(writeToTag ? "StatusWriteToTag" : "StatusWriteToDevice"), msgArray.Length, _publishingMessageId));
                // Update enabled / disabled state of buttons in the User Interface
                UpdateUiForNfcStatus();
            }
            catch (Exception e)
            {
                SetStatusOutput(string.Format(_loader.GetString("StatusPublicationError"), e.Message));
            }
        }
        /// <summary>
        /// Function to handle the chunk message and push the NFC message to proximity device.
        /// </summary>
        /// <param name="proximityDevice">ProximityDevice instance to be used.</param>
        /// <param name="chuckData">IBuffer to chunk message.</param>
        private static async Task NfcMessageHandlerAsync(ProximityDevice proximityDevice, IBuffer chuckData, CancellationToken ct)
        {
            using (var publishedEvent = new AutoResetEvent(false))
            {
                long publishedMessageId = INVALID_PUBLISHED_MESSAGE_ID;

                publishedMessageId = proximityDevice.PublishBinaryMessage(
                    NFC_PROV_MESSAGE_PROTOCOL_NAME,
                    chuckData, (
                        Windows.Networking.Proximity.ProximityDevice device,
                        long messageId
                        ) =>
                {
                    publishedEvent.Set();
                });

                if (INVALID_PUBLISHED_MESSAGE_ID == publishedMessageId)
                {
                    throw new System.ArgumentException("Published message ID returned was invalid.");
                }

                // Wait for the event to be signaled on a threadpool thread so we don't block the UI thread.
                await Task.Run(() =>
                {
                    // Wait for the message transmitted handler to ensure the NFC message has been processed internally.
                    WaitHandle.WaitAny(new WaitHandle[] { publishedEvent, ct.WaitHandle });
                    ct.ThrowIfCancellationRequested();
                });
            }
        }
 private void WriteToTag(object sender, RoutedEventArgs e)
 {
     pressed           = sender as Button;
     pressed.IsEnabled = false;
     msgId             = device.PublishBinaryMessage("LaunchApp:WriteTag", GetBufferFromString(prefix + "{" + inputText.Text + "}"), messageTransmittedHandler);
     isPublishing      = true;
 }
        private void btnWriteLauch_Click(object sender, RoutedEventArgs e)
        {
            ProximityDevice device = ProximityDevice.GetDefault();

            if (device != null)
            {
                //var appId = Windows.ApplicationModel.Store.CurrentApp.AppId;
                var          appId      = "4bad5210-10de-4ae1-a10d-3bb5ce218d66";
                const string launchArgs = "user=default";

                string appName = "NFCMessage" + "!" + appId;

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

                var dataWriter = new DataWriter {
                    UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE
                };

                dataWriter.WriteString(launchAppMessage);
                _launchAppPubId = device.PublishBinaryMessage(
                    "LaunchApp:WriteTag", dataWriter.DetachBuffer(), (proximityDevice, id) =>
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    device.StopPublishingMessage(_launchAppPubId);
                    MessageBox.Show("Nachricht erfolgreich geschrieben !");
                }));
            }
        }
        public void PingAdversary(ProximityDevice device, NotifyNfcReady notify)
        {
            if (subscribeId != -1)
            {
                proximityDevice.StopSubscribingForMessage(subscribeId);
                subscribeId = -1;
            }

            if (publishId != -1)
            {
                proximityDevice.StopPublishingMessage(publishId);
                publishId = -1;
            }

            if (state == NfcManager.ProtoState.Busy)
            {
                return;
            }

            state       = NfcManager.ProtoState.NotReady;
            notifyReady = notify;
            initialMessage.devicetime = random.NextDouble();
            MemoryStream           stream     = new MemoryStream();
            DataContractSerializer serializer = new DataContractSerializer(initialMessage.GetType());

            serializer.WriteObject(stream, initialMessage);
            stream.Position = 0;
            var dataWriter = new DataWriter();

            dataWriter.WriteBytes(stream.GetBuffer());
            proximityDevice = device;
            publishId       = proximityDevice.PublishBinaryMessage("Windows.CarTrumps", dataWriter.DetachBuffer());
            subscribeId     = proximityDevice.SubscribeForMessage("Windows.CarTrumps", OnMessageReceived);
        }
Beispiel #9
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());
            }
        }
Beispiel #10
0
        private void OnWriteableTagArrived(ProximityDevice sender, ProximityMessage message)
        {
            var dataWriter = new DataWriter();

            dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
            string appLauncher = string.Format(@"mywaiter:MainPage?source=3");

            dataWriter.WriteString(appLauncher);
            pubId = sender.PublishBinaryMessage("WindowsUri:WriteTag", dataWriter.DetachBuffer());
        }
Beispiel #11
0
        public async Task <WriteResult> WriteTag(NdefMessage message, CancellationToken cancellationToken, TimeSpan timeout)
        {
            if (!IsSupported)
            {
                if (_dontThrowExpceptionWhenNotSupported)
                {
                    return(null);
                }
                throw new NotSupportedException("This device does not support NFC (or perhaps it's disabled)");
            }
            Task timeoutTask = null;

            if (timeout != default(TimeSpan))
            {
                timeoutTask = Task.Delay(timeout);
            }
            long subscription;

            TaskCompletionSource <WriteResult> resultSource = new TaskCompletionSource <WriteResult>(); //needs a message type

            using (cancellationToken.Register((s => ((TaskCompletionSource <WriteResult>)s).TrySetCanceled()), resultSource))
            {
                byte[] theMessage = message.ToByteArray();
                subscription = _proximityDevice.PublishBinaryMessage("NDEF:WriteTag", theMessage.AsBuffer(), (sender, id) =>
                {
                    WriteResult result      = new WriteResult();
                    result.NFCTag           = new NFCTag();
                    result.ReasonForFailure = FailureReasons.DidNotFail;
                    resultSource.TrySetResult(result);
                });
                try
                {
                    if (timeoutTask != null)
                    {
                        await Task.WhenAny(timeoutTask, resultSource.Task);



                        if (timeoutTask.IsCompleted)
                        {
                            throw new TimeoutException("NFC message not recieved in time");
                        }
                    }
                    if (resultSource.Task.IsCanceled)
                    {
                        return(null);
                    }
                    return(await resultSource.Task);
                }
                finally
                {
                    _proximityDevice.StopPublishingMessage(subscription);
                }
            }
        }
Beispiel #12
0
 private void PeerFinder_TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs args)
 {
     if (args.State == TriggeredConnectState.PeerFound)
     {
         proximityDevice = ProximityDevice.GetDefault();
         var message = new NdefMessage {
             new NdefUriRecord {
                 Uri = "tracktimer:addFriend?" + App.MobileService.CurrentUser.UserId
             }
         };
         proximityDevice.PublishBinaryMessage("NDEF", message.ToByteArray().AsBuffer(), MessageWrittenHandler);
     }
 }
Beispiel #13
0
 private void BtnLockTag_Click(object sender, RoutedEventArgs e)
 {
     if (_device == null)
     {
         return;
     }
     // Make sure we're not already publishing another message
     StopPublishingMessage(false);
     // Start locking tags
     try
     {
         var empty = new byte[0];
         _publishingMessageId = _device.PublishBinaryMessage("SetTagReadOnly", empty.AsBuffer(), TagLockedHandler);
         // Update status text for UI
         SetStatusOutput(string.Format(_loader.GetString("StatusLockingTag")));
         // Update enabled / disabled state of buttons in the User Interface
         UpdateUiForNfcStatusAsync();
     }
     catch (Exception ex)
     {
         SetStatusOutput(string.Format(_loader.GetString("StatusLockingNotSupported"), ex.Message));
     }
 }
        public writeTag()
        {
            InitializeComponent();
            var dataWriter = new DataWriter()
            {
                UnicodeEncoding = UnicodeEncoding.Utf8
            };

            dataWriter.WriteString(textToWrite.Text);
            ProximityDevice device = ProximityDevice.GetDefault();

            // Make sure NFC is supported
            if (device != null)
            {
                device.PublishBinaryMessage("Windows:WriteTag.mySubType", dataWriter.DetachBuffer(), messageWrittenHandler);
            }
        }
Beispiel #15
0
 private void DoWriteTag()
 {
     try
     {
         using (var writer = new DataWriter {
             UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE
         })
         {
             Debug.WriteLine("Writing message to NFC: " + Url);
             writer.WriteString(Url);
             long id = _proximityDevice.PublishBinaryMessage("WindowsUri:WriteTag", writer.DetachBuffer());
             _proximityDevice.StopPublishingMessage(id);
         }
     }
     catch (Exception e)
     {
         Debug.WriteLine(e.StackTrace);
     }
 }
Beispiel #16
0
        private void PublishRecordToTag(NDEFRecordShort record, MessageTransmittedHandler handler)
        {
            if (record == null ||
                record.Data == null)
            {
                return;
            }

            IBuffer buffer = record.Data.AsBuffer();

            device.PublishBinaryMessage("NDEF:WriteTag", buffer, (sender, msgID) => {
                if (handler != null)
                {
                    handler(sender, msgID);
                }

                device.StopPublishingMessage(msgID);
            });
        }
Beispiel #17
0
 public void WriteToTag()
 {
     StopWritingMessage();
     UpdateState(NfcHelperState.WaitingForWriting);
     try
     {
         var str = new StringBuilder();
         str.Append("action=my_custom_action");
         str.Append("\tWindowsPhone\t{");
         str.Append(CurrentApp.AppId);
         str.Append("}");
         _writingMessageId = _nfcDevice.PublishBinaryMessage("LaunchApp:WriteTag", GetBufferFromString(str.ToString()),
                                                             WriteToTagComplete);
     }
     catch
     {
         UpdateState(NfcHelperState.ErrorWriting);
         StopWritingMessage();
     }
 }
        private void btnWriteMimePublish_Click(object sender, RoutedEventArgs e)
        {
            ProximityDevice device = ProximityDevice.GetDefault();

            if (device != null)
            {
                btnWriteMimePublish.IsEnabled = false;
                _idTxtPlain = device.PublishBinaryMessage(
                    "WindowsMime:WriteTag.text/plain",
                    Encoding.UTF8.GetBytes(tbMime.Text).AsBuffer(),
                    (proximityDevice, messageId) => {
                    Deployment.Current.Dispatcher.BeginInvoke(() => {
                        device.StopPublishingMessage(_idTxtPlain);
                        MessageBox.Show("Nachricht erfolgreich geschrieben !");
                        btnWriteMimePublish.IsEnabled = true;
                    });
                }
                    );
            }
        }
Beispiel #19
0
        private void PublishRecord(NdefRecord record, bool writeToTag)
        {
            if (_device == null)
            {
                return;
            }

            // Make sure we're not already publishing another message
            StopPublishingMessage(false);
            // Wrap the NDEF record into an NDEF message
            var message = new NdefMessage {
                record
            };
            // Convert the NDEF message to a byte array
            var msgArray = message.ToByteArray();

            // Publish the NDEF message to a tag or to another device, depending on the writeToTag parameter
            // Save the publication ID so that we can cancel publication later
            _publishingMessageId = _device.PublishBinaryMessage((writeToTag ? "NDEF:WriteTag" : "NDEF"), msgArray.AsBuffer(), MessageWrittenHandler);
        }
        private void btnWriteURI_Click(object sender, RoutedEventArgs e)
        {
            ProximityDevice device = ProximityDevice.GetDefault();

            if (device != null)
            {
                _idUriWrite = device.PublishBinaryMessage(
                    "WindowsUri:WriteTag",
                    Encoding.Unicode.GetBytes(tbUrl.Text).AsBuffer(),
                    (proximityDevice, messageId) =>
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        device.StopPublishingMessage(_idUriWrite);
                        MessageBox.Show("Nachricht erfolgreich geschrieben !");
                    });
                }
                    );
            }
        }
Beispiel #21
0
 /// <summary>
 /// Deliver any kind of binary message
 /// </summary>
 /// <param name="type"></param>
 /// <param name="message"></param>
 private void DeliverBinaryMessage(string type, byte[] message)
 {
     pDevice.PublishBinaryMessage(type, message.AsBuffer(), MessageWrittenHandler);
 }
Beispiel #22
0
        //Write to NFC Tag
        async void SettingsWriteNFCTag_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ProximityDevice vProximityDevice = ProximityDevice.GetDefault();
                if (vProximityDevice != null)
                {
                    Nullable <bool> MessageDialogResult = null;
                    MessageDialog   MessageDialog       = new MessageDialog("After this message hold your NFC tag to this device's NFC area so the tag can be written.", "TimeMe");
                    MessageDialog.Commands.Add(new UICommand("Continue", new UICommandInvokedHandler((cmd) => MessageDialogResult = true)));
                    MessageDialog.Commands.Add(new UICommand("Cancel", new UICommandInvokedHandler((cmd) => MessageDialogResult   = false)));
                    await MessageDialog.ShowAsync();

                    if (MessageDialogResult == true)
                    {
                        Button Button     = (Button)sender;
                        string LaunchArgs = Button.Tag.ToString();
                        Set_NFCTags.Opacity = 0.60; Set_NFCTags.IsHitTestVisible = false;

                        //Create 10 seconds timeout timer
                        int             TimeoutTime  = 0;
                        DispatcherTimer TimeoutTimer = new DispatcherTimer();
                        TimeoutTimer.Interval = TimeSpan.FromSeconds(1);
                        TimeoutTimer.Tick    += delegate
                        {
                            TimeoutTime++;
                            if (TimeoutTime >= 11)
                            {
                                vProximityDevice = null; TimeoutTimer.Stop(); Set_NFCTags.Opacity = 1; Set_NFCTags.IsHitTestVisible = true; sp_StatusBar.Visibility = Visibility.Collapsed;
                            }
                            else
                            {
                                txt_StatusBar.Text = "Waiting on NFC tag for " + (11 - TimeoutTime).ToString() + "sec..."; sp_StatusBar.Visibility = Visibility.Visible;
                            }
                        };
                        TimeoutTimer.Start();

                        //Start checking for NFC tag if NFC device is active
                        vProximityDevice.DeviceArrived += async delegate
                        {
                            if (vProximityDevice != null)
                            {
                                string WinAppId = Package.Current.Id.FamilyName + "!" + "App";
                                string AppMsg   = LaunchArgs + "\tWindows\t" + WinAppId;

                                using (DataWriter DataWriter = new DataWriter {
                                    UnicodeEncoding = UnicodeEncoding.Utf16LE
                                })
                                {
                                    DataWriter.WriteString(AppMsg);
                                    long PublishBinaryMessage = vProximityDevice.PublishBinaryMessage("LaunchApp:WriteTag", DataWriter.DetachBuffer());
                                    vProximityDevice.StopPublishingMessage(PublishBinaryMessage);
                                    vProximityDevice = null;

                                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async delegate
                                    {
                                        TimeoutTimer.Stop();
                                        Set_NFCTags.Opacity     = 1; Set_NFCTags.IsHitTestVisible = true;
                                        sp_StatusBar.Visibility = Visibility.Collapsed;
                                        await new MessageDialog("The NFC tag has successfully been written to your tag, please note that this might not work with all NFC tags due to incompatibility issues or with some tags that are locked.", "TimeMe").ShowAsync();
                                    });
                                }
                            }
                        };
                    }
                }
                else
                {
                    vProximityDevice = null;
                    Nullable <bool> MessageDialogResult = null;
                    MessageDialog   MessageDialog       = new MessageDialog("It seems like your device's NFC is disabled or does not support NFC, please make sure NFC is turned on before writing a new NFC tag, do you want to enable your device's NFC functionality?", "TimeMe");
                    MessageDialog.Commands.Add(new UICommand("Enable", new UICommandInvokedHandler((cmd) => MessageDialogResult = true)));
                    MessageDialog.Commands.Add(new UICommand("Cancel", new UICommandInvokedHandler((cmd) => MessageDialogResult = false)));
                    await MessageDialog.ShowAsync();

                    if (MessageDialogResult == true)
                    {
                        await Launcher.LaunchUriAsync(new Uri("ms-settings:proximity"));
                    }
                }
            }
            catch (Exception Ex) { await new MessageDialog("NFCError: " + Ex.Message, "TimeMe").ShowAsync(); }
        }