Ejemplo n.º 1
0
        private void LaunchCallback(ResponseFrame frame, Exception e)
        {
            if (CheckForErrorsOrTimeout(frame, e))
            {
                return;
            }

            byte[] data = frame.Data;
            byte[] temp = new byte[data.Length - data[1] - 2];

            Array.Copy(data, 2 + data[1], temp, 0, temp.Length);

            NdefMessage message = NdefMessage.FromByteArray(temp);

            if (message.Count > 0)
            {
                if (Encoding.UTF8.GetString(message[0].Type).Equals("U"))
                {
                    NdefUriRecord uriRecord = new NdefUriRecord(message[0]);
                    NdefUri       uri       = new NdefUri(uriRecord.Uri);
                    if (uri.Scheme == 0)
                    {
                        return;
                    }
                    Process.Start(uriRecord.Uri);
                }
            }

            Task.Run(() =>
            {
                Thread.Sleep(500);
                DetectandLaunch();
            });
        }
Ejemplo n.º 2
0
 /* <summary>
  * void parse_record
  * Constructs NDEF record from given byte array. Parsing fails if the NDEF tag is not valid.
  * </summary>
  *
  * <remarks>
  * If you know that NDEF tag is legit all you have to worry about is passing the right chunk of
  * bytes to the function. NDEF tag starts with "D1" byte and ends IN "FE" byte.
  * </remarks>
  *
  * //TODO: expand for all types of NDEF records
  */
 static void parse_record(NdefMessage ndefMessage)
 {
     foreach (NdefRecord record in ndefMessage)
     {
         Debug.WriteLine("Record type: " + Encoding.UTF8.GetString(record.Type, 0, record.Type.Length));
         // Check the type of each record - handling a Smart Poster, URI and Text record in this example
         var specializedType = record.CheckSpecializedType(false);
         if (specializedType == typeof(NdefSpRecord))
         {
             // Convert and extract Smart Poster info
             var spRecord = new NdefSpRecord(record);
             Debug.WriteLine("URI: " + spRecord.Uri);
             Debug.WriteLine("Titles: " + spRecord.TitleCount());
             Debug.WriteLine("1. Title: " + spRecord.Titles[0].Text);
             Debug.WriteLine("Action set: " + spRecord.ActionInUse());
             // You can also check the action (if in use by the record),
             //mime type and size of the linked content.
         }
         else if (specializedType == typeof(NdefUriRecord))
         {
             // Convert and extract URI info
             var uriRecord = new NdefUriRecord(record);
             Debug.WriteLine("URI: " + uriRecord.Uri);
         }
         else if (specializedType == typeof(NdefTextRecord))
         {
             // Convert and extract Text record info
             var textRecord = new NdefTextRecord(record);
             Debug.WriteLine("Text: " + textRecord.Text);
             Debug.WriteLine("Language code: " + textRecord.LanguageCode);
             var textEncoding = (textRecord.TextEncoding == NdefTextRecord.TextEncodingType.Utf8 ? "UTF-8" : "UTF-16");
             Debug.WriteLine("Encoding: " + textEncoding);
         }
     }
 }
Ejemplo n.º 3
0
        private bool IsShopCard(byte[] buffer)
        {
            // NDEF - byte 0 should be 0x03, byte 1 should be length of remaining bytes.
            if (buffer.Length < 2 || buffer[0] != 0x03 || buffer[1] != buffer.Length - 2)
            {
                return(false);
            }

            try
            {
                var msg = NdefMessage.FromByteArray(buffer.Skip(2).ToArray());

                if (msg.Count > 0 && msg.First().CheckSpecializedType(false) == typeof(NdefUriRecord))
                {
                    var record = new NdefUriRecord(msg.First());

                    return(record.Uri.StartsWith(CardUri));
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

            return(false);
        }
Ejemplo n.º 4
0
        private ObservableCollection <string> readNDEFMEssage(NdefMessage message)
        {
            ObservableCollection <string> collection = new ObservableCollection <string>();

            if (message == null)
            {
                return(collection);
            }

            foreach (NdefRecord record in message)
            {
                // Go through each record, check if it's a Smart Poster
                if (record.CheckSpecializedType(false) == typeof(NdefSpRecord))
                {
                    // Convert and extract Smart Poster info
                    var spRecord = new NdefSpRecord(record);
                    collection.Add("URI: " + spRecord.Uri);
                    collection.Add("Titles: " + spRecord.TitleCount());
                    collection.Add("1. Title: " + spRecord.Titles[0].Text);
                    collection.Add("Action set: " + spRecord.ActionInUse());
                }

                if (record.CheckSpecializedType(false) == typeof(NdefUriRecord))
                {
                    // Convert and extract Smart Poster info
                    var spRecord = new NdefUriRecord(record);
                    collection.Add("Text: " + spRecord.Uri);
                }
            }
            return(collection);
        }
Ejemplo n.º 5
0
        private void messagedReceived(ProximityDevice device, ProximityMessage m)
        {
            uint x = m.Data.Length;

            byte[] b = new byte[x];
            b = m.Data.ToArray();

            PlaySound();

            // string s = Encoding.UTF8.GetString(b, 0, b.Length);
            // Debug.WriteLine(s);


            NdefMessage ndefMessage = NdefMessage.FromByteArray(b);

            foreach (NdefRecord record in ndefMessage)
            {
                WriteMessageText("\n----------------------------");
                WriteMessageText("\nType: " + Encoding.UTF8.GetString(record.Type, 0, record.Type.Length));
                if (record.CheckSpecializedType(false) == typeof(NdefUriRecord))
                {
                    var uriRecord = new NdefUriRecord(record);
                    WriteMessageText("\nURI: " + uriRecord.Uri);
                }
                ;
            }
            WriteMessageText("\n----------------------------\n");
        }
Ejemplo n.º 6
0
        // ------------------------------------------
        //  PUBLIC
        // http://software.intel.com/en-us/articles/using-winrt-apis-from-desktop-applications
        // ------------------------------------------

        public void WriteURIRecord(String uri)
        {
            var uriRecord = new NdefUriRecord {
                Uri = uri
            };

            PublishRecord(uriRecord, true);
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            // Dynamically construct some more NDEF records
            var spRecord = new NdefSpRecord
            {
                Uri       = "http://andijakl.github.io/ndef-nfc/",
                NfcAction = NdefSpActRecord.NfcActionType.DoAction
            };

            spRecord.AddTitle(new NdefTextRecord {
                LanguageCode = "en", Text = "NFC Library"
            });
            spRecord.AddTitle(new NdefTextRecord {
                LanguageCode = "de", Text = "NFC Bibliothek"
            });
            NfcRecords.Add("SmartPoster", spRecord);

            // Ensure the path exists
            var tagsDirectory = Path.Combine(Environment.CurrentDirectory, FileDirectory);

            Directory.CreateDirectory(tagsDirectory);

            // Write tag contents to files
            foreach (var curNdefRecord in NfcRecords)
            {
                WriteTagFile(tagsDirectory, curNdefRecord.Key, curNdefRecord.Value);
            }

            // Multi-record file
            var record1 = new NdefUriRecord {
                Uri = "http://www.twitter.com"
            };
            var record2 = new NdefAndroidAppRecord {
                PackageName = "com.twitter.android"
            };
            var twoRecordsMsg = new NdefMessage {
                record1, record2
            };

            WriteTagFile(tagsDirectory, "TwoRecords", twoRecordsMsg);

            var record3 = new NdefRecord
            {
                TypeNameFormat = NdefRecord.TypeNameFormatType.ExternalRtd,
                Type           = Encoding.UTF8.GetBytes("custom.com:myapp")
            };
            var threeRecordsMsg = new NdefMessage {
                record1, record3, record2
            };

            WriteTagFile(tagsDirectory, "ThreeRecords", threeRecordsMsg);

            // Success message on output
            Console.WriteLine("Generated {0} tag files in {1}.", NfcRecords.Count, tagsDirectory);
            Debug.WriteLine("Generated {0} tag files in {1}.", NfcRecords.Count, tagsDirectory);
        }
Ejemplo n.º 8
0
        private void BtnPublishUri_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // Create a URI record
            var record = new NdefUriRecord {
                Uri = "http://www.nfcinteractor.com/"
            };

            // Publish the record using the proximity device
            PublishRecord(record, false);
        }
Ejemplo n.º 9
0
        private string getURIFromNdef(byte[] data)
        {
            var message = NdefMessage.FromByteArray(data);

            foreach (NdefRecord record in message)
            {
                if (record.CheckSpecializedType(false) == typeof(NdefUriRecord))
                {
                    var uri = new NdefUriRecord(record);
                    return(uri.Uri);
                }
            }
            return(null);
        }
Ejemplo n.º 10
0
        // ------------------------------------------
        //  PRIVATE READER
        // ------------------------------------------

        private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
        {
            // Parse raw byte array to NDEF message
            var rawMsg      = message.Data.ToArray();
            var ndefMessage = NdefMessage.FromByteArray(rawMsg);

            // Loop over all records contained in the NDEF message
            foreach (NdefRecord record in ndefMessage)
            {
                Console.WriteLine("Record type: " + Encoding.UTF8.GetString(record.Type, 0, record.Type.Length));

                // Check the type of each record - handling a Smart Poster in this example
                var specializedType = record.CheckSpecializedType(true);

                // Convert and extract Smart Poster info
                if (specializedType == typeof(NdefSpRecord))
                {
                    var    spRecord = new NdefSpRecord(record);
                    String msg      = "URI: " + spRecord.Uri + "\n"
                                      + "Titles: " + spRecord.TitleCount() + "\n"
                                      + "1. Title: " + spRecord.Titles[0].Text + "\n"
                                      + "Action set: " + spRecord.ActionInUse();
                    NFCManager.getInstance().Alert(msg);
                }

                // Convert and extract URI record info
                else if (specializedType == typeof(NdefUriRecord))
                {
                    var    uriRecord = new NdefUriRecord(record);
                    String msg       = "URI: " + uriRecord.Uri + "\n";
                    NFCManager.getInstance().Alert(msg);
                    NFCManager.getInstance().SendRequest(uriRecord.Uri);
                }

                // Convert and extract Mailto record info
                else if (specializedType == typeof(NdefMailtoRecord))
                {
                    var    mailtoRecord = new NdefMailtoRecord(record);
                    String msg          = "Address: " + mailtoRecord.Address + "\n"
                                          + "Subject: " + mailtoRecord.Subject + "\n"
                                          + "Body: " + mailtoRecord.Body;
                    NFCManager.getInstance().Alert(msg);
                }
            }
        }
Ejemplo n.º 11
0
        public MessageViewModel(NdefLibrary.Ndef.NdefRecord message)
        {
            Type type = message.CheckSpecializedType(true);

            Type = type.Name;
            Info = "Feel free to add this mapping to the message view model";
            if (type == typeof(NdefLibrary.Ndef.NdefTextRecord))
            {
                var text = new NdefTextRecord(message);
                Info = string.Format("The message on the tag is \"{0}\". The language is \"{1}\"", text.Text,
                                     text.LanguageCode);
            }
            if (type == typeof(NdefLibrary.Ndef.NdefUriRecord))
            {
                var text = new NdefUriRecord(message);
                Info = string.Format("The URI on the tag is \"{0}\"", text.Uri);
            }
        }
Ejemplo n.º 12
0
        public static String ProcessNFCRecord(NdefRecord record)
        {
            //Define the tag content we want to return.
            String tagContent = null;

            //Make sure we have a record.
            if (record != null)
            {
                //Check if the record is a URL.
                if (record.CheckSpecializedType(true) == typeof(NdefUriRecord))
                {
                    //The content is a URL.
                    tagContent = new NdefUriRecord(record).Uri;
                }
                else if (record.CheckSpecializedType(true) == typeof(NdefMailtoRecord))
                {
                    //The content is a mailto record.
                    tagContent = new NdefMailtoRecord(record).Uri;
                }
                else if (record.CheckSpecializedType(true) == typeof(NdefTelRecord))
                {
                    //The content is a tel record.
                    tagContent = new NdefTelRecord(record).Uri;
                }
                else if (record.CheckSpecializedType(true) == typeof(NdefSmsRecord))
                {
                    //The content is a sms record.
                    tagContent = new NdefSmsRecord(record).Uri;
                }
                else if (record.CheckSpecializedType(true) == typeof(NdefTextRecord))
                {
                    //The content is a text record.
                    tagContent = new NdefTextRecord(record).Text;
                }
                else
                {
                    //Try and force a pure text conversion.
                    tagContent = Encoding.UTF8.GetString(record.Payload);
                }
            }

            //Return the tag content.
            return(tagContent);
        }
Ejemplo n.º 13
0
        private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
        {
            SetStatusOutput("Found proximity card");
            // Convert to NdefMessage from NDEF / NFC Library
            var         msgArray    = message.Data.ToArray();
            NdefMessage ndefMessage = NdefMessage.FromByteArray(msgArray);

            // Loop over all records contained in the message
            foreach (NdefRecord record in ndefMessage)
            {
                // Check the type of each record
                if (record.CheckSpecializedType(false) == typeof(NdefUriRecord))
                {
                    // Convert and extract URI info
                    var uriRecord = new NdefUriRecord(record);
                    SetStatusOutput("NDEF URI: " + uriRecord.Uri);
                }
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            LuaForm.navService = this;
            LuaForm.activeForm = this;
            if (FirstInit)
            {
                FirstInit = false;
            }
            else if (!mainPage)
            {
                LuaInternalParameter lip = (LuaInternalParameter)e.Parameter;
                luaId = lip["luaId"];
                String initUI = lip["ui"];
                if (initUI != "")
                {
                    LuaViewInflator inflater = new LuaViewInflator(luaContext);
                    this.view = inflater.ParseFile(initUI, null);
                    Content   = view.GetView();
                }
                else
                {
                    LuaEngine.Instance.OnGuiEvent(this, LuaEngine.GuiEvents.GUI_EVENT_CREATE, luaContext);
                }
            }
#if WP8
            proximityDevice = ProximityDevice.GetDefault();
            if (proximityDevice != null)
            {
                nfcSubsId = proximityDevice.SubscribeForMessage("NDEF", (device, message) =>
                {
                    Logger.Log(LogType.CONSOLE, LogLevel.ERROR, "**** Subs Ndef ****");
                    // Parse raw byte array to NDEF message
                    byte[] rawMsg           = message.Data.ToArray();
                    NdefMessage ndefMessage = NdefMessage.FromByteArray(rawMsg);

                    Dictionary <Int32, Dictionary <String, String> > nfcData = new Dictionary <Int32, Dictionary <String, String> >();
                    int count = 0;
                    foreach (NdefRecord record in ndefMessage)
                    {
                        Dictionary <String, String> recordDict = new Dictionary <String, String>();
                        Type recordType = record.CheckSpecializedType(false);
                        if (recordType == typeof(NdefUriRecord))
                        {
                            NdefUriRecord uriRecord = new NdefUriRecord(record);
                            recordDict.Add("type", "uri");
                            recordDict.Add("uri", uriRecord.Uri);
                            nfcData.Add(count++, recordDict);
                        }
                        else if (recordType == typeof(NdefSmartUriRecord))
                        {
                            NdefSmartUriRecord sUriRecord = new NdefSmartUriRecord(record);
                            recordDict.Add("type", "spr");
                            recordDict.Add("title", sUriRecord.Titles[0].Text);
                            recordDict.Add("uri", sUriRecord.Uri);
                        }
                    }
                    LuaEngine.Instance.OnGuiEvent(this, LuaEngine.GuiEvents.GUI_EVENT_NFC, luaContext, nfcData);
                });
            }
#endif
            LuaEngine.Instance.OnGuiEvent(this, LuaEngine.GuiEvents.GUI_EVENT_RESUME, luaContext);
        }
Ejemplo n.º 15
0
        private async void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
        {
            // Get the raw NDEF message data as byte array
            var rawMsg = message.Data.ToArray();
            // Let the NDEF library parse the NDEF message out of the raw byte array
            var ndefMessage = NdefMessage.FromByteArray(rawMsg);

            // Analysis result
            var tagContents = new StringBuilder();

            // Loop over all records contained in the NDEF message
            foreach (NdefRecord record in ndefMessage)
            {
                // --------------------------------------------------------------------------
                // Print generic information about the record
                if (record.Id != null && record.Id.Length > 0)
                {
                    // Record ID (if present)
                    tagContents.AppendFormat("Id: {0}\n", Encoding.UTF8.GetString(record.Id, 0, record.Id.Length));
                }
                // Record type name, as human readable string
                tagContents.AppendFormat("Type name: {0}\n", ConvertTypeNameFormatToString(record.TypeNameFormat));
                // Record type
                if (record.Type != null && record.Type.Length > 0)
                {
                    tagContents.AppendFormat("Record type: {0}\n",
                                             Encoding.UTF8.GetString(record.Type, 0, record.Type.Length));
                }

                // --------------------------------------------------------------------------
                // Check the type of each record
                // Using 'true' as parameter for CheckSpecializedType() also checks for sub-types of records,
                // e.g., it will return the SMS record type if a URI record starts with "sms:"
                // If using 'false', a URI record will always be returned as Uri record and its contents won't be further analyzed
                // Currently recognized sub-types are: SMS, Mailto, Tel, Nokia Accessories, NearSpeak, WpSettings
                var specializedType = record.CheckSpecializedType(true);

                if (specializedType == typeof(NdefMailtoRecord))
                {
                    // --------------------------------------------------------------------------
                    // Convert and extract Mailto record info
                    var mailtoRecord = new NdefMailtoRecord(record);
                    tagContents.Append("-> Mailto record\n");
                    tagContents.AppendFormat("Address: {0}\n", mailtoRecord.Address);
                    tagContents.AppendFormat("Subject: {0}\n", mailtoRecord.Subject);
                    tagContents.AppendFormat("Body: {0}\n", mailtoRecord.Body);
                }
                else if (specializedType == typeof(NdefUriRecord))
                {
                    // --------------------------------------------------------------------------
                    // Convert and extract URI record info
                    var uriRecord = new NdefUriRecord(record);
                    tagContents.Append("-> URI record\n");
                    tagContents.AppendFormat("URI: {0}\n", uriRecord.Uri);
                }
                else if (specializedType == typeof(NdefLaunchAppRecord))
                {
                    // --------------------------------------------------------------------------
                    // Convert and extract LaunchApp record info
                    var launchAppRecord = new NdefLaunchAppRecord(record);
                    tagContents.Append("-> LaunchApp record" + Environment.NewLine);
                    if (!string.IsNullOrEmpty(launchAppRecord.Arguments))
                    {
                        tagContents.AppendFormat("Arguments: {0}\n", launchAppRecord.Arguments);
                    }
                    if (launchAppRecord.PlatformIds != null)
                    {
                        foreach (var platformIdTuple in launchAppRecord.PlatformIds)
                        {
                            if (platformIdTuple.Key != null)
                            {
                                tagContents.AppendFormat("Platform: {0}\n", platformIdTuple.Key);
                            }
                            if (platformIdTuple.Value != null)
                            {
                                tagContents.AppendFormat("App ID: {0}\n", platformIdTuple.Value);
                            }
                        }
                    }
                }
                else if (specializedType == typeof(NdefVcardRecordBase))
                {
                    // --------------------------------------------------------------------------
                    // Convert and extract business card info
                    var vcardRecord = await NdefVcardRecord.CreateFromGenericBaseRecord(record);

                    tagContents.Append("-> Business Card record" + Environment.NewLine);
                    tagContents.AppendFormat("vCard Version: {0}" + Environment.NewLine,
                                             vcardRecord.VCardFormatToWrite == VCardFormat.Version2_1 ? "2.1" : "3.0");
                    var contact     = vcardRecord.ContactData;
                    var contactInfo = await contact.GetPropertiesAsync();

                    foreach (var curProperty in contactInfo.OrderBy(i => i.Key))
                    {
                        tagContents.Append(String.Format("{0}: {1}" + Environment.NewLine, curProperty.Key, curProperty.Value));
                    }
                }
                else
                {
                    // Other type, not handled by this demo
                    tagContents.Append("NDEF record not parsed by this demo app" + Environment.NewLine);
                }
            }
            // Update status text for UI
            SetStatusOutput(string.Format(AppResources.StatusTagParsed, tagContents));
        }
Ejemplo n.º 16
0
        private bool NfcTag_ReadWrite()
        {
            try
            {
                var spRecord = new NdefSpRecord
                {
                    Uri       = "",
                    NfcAction = NdefSpActRecord.NfcActionType.DoAction
                };
                spRecord.AddTitle(new NdefTextRecord {
                    LanguageCode = "en", Text = "NFC Library"
                });
                spRecord.AddTitle(new NdefTextRecord {
                    LanguageCode = "de", Text = "NFC Bibliothek"
                });

                NfcTagGenerator.NfcRecords.Add("SmartPoster", spRecord);

                // Ensure the path exists
                var tagsDirectory = Path.Combine(Environment.CurrentDirectory, NfcTagGenerator.FileDirectory);
                Directory.CreateDirectory(tagsDirectory);

                // Write tag contents to files
                foreach (var curNdefRecord in NfcTagGenerator.NfcRecords)
                {
                    NfcTagGenerator.WriteTagFile(tagsDirectory, curNdefRecord.Key, curNdefRecord.Value);
                }

                // Multi-record file
                var record1 = new NdefUriRecord {
                    Uri = "https://www.twitter.com"
                };
                var record2 = new NdefAndroidAppRecord {
                    PackageName = "com.twitter.android"
                };
                var twoRecordsMsg = new NdefMessage {
                    record1, record2
                };
                NfcTagGenerator.WriteTagFile(tagsDirectory, "TwoRecords", twoRecordsMsg);

                var record3 = new NdefRecord
                {
                    TypeNameFormat = NdefRecord.TypeNameFormatType.ExternalRtd,
                    Type           = Encoding.UTF8.GetBytes("custom.com:myapp")
                };
                var threeRecordsMsg = new NdefMessage {
                    record1, record3, record2
                };
                NfcTagGenerator.WriteTagFile(tagsDirectory, "ThreeRecords", threeRecordsMsg);

                // Success message on output
                Console.WriteLine("Generated {0} tag files in {1}.", NfcTagGenerator.NfcRecords.Count, tagsDirectory);
                Debug.WriteLine("Generated {0} tag files in {1}.", NfcTagGenerator.NfcRecords.Count, tagsDirectory);
                return(true);
            }
            catch (NdefException ex)
            {
                return(false);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Ejemplo n.º 17
0
        private async Task ParseTagContents(NdefMessage ndefMessage, StringBuilder tagContents)
        {
            // Loop over all records contained in the NDEF message
            foreach (NdefRecord record in ndefMessage)
            {
                // --------------------------------------------------------------------------
                // Print generic information about the record
                if (record.Id != null && record.Id.Length > 0)
                {
                    // Record ID (if present)
                    tagContents.AppendFormat("Id: {0}\n", Encoding.UTF8.GetString(record.Id, 0, record.Id.Length));
                }
                // Record type name, as human readable string
                tagContents.AppendFormat("Type name: {0}\n", ConvertTypeNameFormatToString(record.TypeNameFormat));
                // Record type
                if (record.Type != null && record.Type.Length > 0)
                {
                    tagContents.AppendFormat("Record type: {0}\n",
                                             Encoding.UTF8.GetString(record.Type, 0, record.Type.Length));
                }

                // --------------------------------------------------------------------------
                // Check the type of each record
                // Using 'true' as parameter for CheckSpecializedType() also checks for sub-types of records,
                // e.g., it will return the SMS record type if a URI record starts with "sms:"
                // If using 'false', a URI record will always be returned as Uri record and its contents won't be further analyzed
                // Currently recognized sub-types are: SMS, Mailto, Tel, Nokia Accessories, NearSpeak, WpSettings
                var specializedType = record.CheckSpecializedType(true);

                if (specializedType == typeof(NdefMailtoRecord))
                {
                    // --------------------------------------------------------------------------
                    // Convert and extract Mailto record info
                    var mailtoRecord = new NdefMailtoRecord(record);
                    tagContents.Append("-> Mailto record\n");
                    tagContents.AppendFormat("Address: {0}\n", mailtoRecord.Address);
                    tagContents.AppendFormat("Subject: {0}\n", mailtoRecord.Subject);
                    tagContents.AppendFormat("Body: {0}\n", mailtoRecord.Body);
                }
                else if (specializedType == typeof(NdefUriRecord))
                {
                    // --------------------------------------------------------------------------
                    // Convert and extract URI record info
                    var uriRecord = new NdefUriRecord(record);
                    tagContents.Append("-> URI record\n");
                    tagContents.AppendFormat("URI: {0}\n", uriRecord.Uri);
                }
                else if (specializedType == typeof(NdefSpRecord))
                {
                    // --------------------------------------------------------------------------
                    // Convert and extract Smart Poster info
                    var spRecord = new NdefSpRecord(record);
                    tagContents.Append("-> Smart Poster record\n");
                    tagContents.AppendFormat("URI: {0}", spRecord.Uri);
                    tagContents.AppendFormat("Titles: {0}", spRecord.TitleCount());
                    if (spRecord.TitleCount() > 1)
                    {
                        tagContents.AppendFormat("1. Title: {0}", spRecord.Titles[0].Text);
                    }
                    tagContents.AppendFormat("Action set: {0}", spRecord.ActionInUse());
                    // You can also check the action (if in use by the record),
                    // mime type and size of the linked content.
                }
                else if (specializedType == typeof(NdefVcardRecordBase))
                {
                    // --------------------------------------------------------------------------
                    // Convert and extract business card info
                    var vcardRecord = new NdefVcardRecord(record);
                    tagContents.Append("-> Business Card record" + Environment.NewLine);
                    var contact = vcardRecord.ContactData;

                    // Contact has phone or email info set? Use contact manager to show the contact card
                    await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        if (contact.Emails.Any() || contact.Phones.Any())
                        {
                            var rect = GetElementRect(StatusOutput);
                            ContactManager.ShowContactCard(contact, rect, Placement.Below);
                        }
                        else
                        {
                            // No phone or email set - contact manager would not show the contact card.
                            // -> parse manually
                            tagContents.AppendFormat("Name: {0}\n", contact.DisplayName);
                            tagContents.Append("[not parsing other values in the demo app]");
                        }
                    });
                }
                else if (specializedType == typeof(NdefLaunchAppRecord))
                {
                    // --------------------------------------------------------------------------
                    // Convert and extract LaunchApp record info
                    var launchAppRecord = new NdefLaunchAppRecord(record);
                    tagContents.Append("-> LaunchApp record" + Environment.NewLine);
                    if (!string.IsNullOrEmpty(launchAppRecord.Arguments))
                    {
                        tagContents.AppendFormat("Arguments: {0}\n", launchAppRecord.Arguments);
                    }
                    if (launchAppRecord.PlatformIds != null)
                    {
                        foreach (var platformIdTuple in launchAppRecord.PlatformIds)
                        {
                            if (platformIdTuple.Key != null)
                            {
                                tagContents.AppendFormat("Platform: {0}\n", platformIdTuple.Key);
                            }
                            if (platformIdTuple.Value != null)
                            {
                                tagContents.AppendFormat("App ID: {0}\n", platformIdTuple.Value);
                            }
                        }
                    }
                }
                else if (specializedType == typeof(NdefMimeImageRecordBase))
                {
                    // --------------------------------------------------------------------------
                    // Convert and extract Image record info
                    var imgRecord = new NdefMimeImageRecord(record);
                    tagContents.Append("-> MIME / Image record" + Environment.NewLine);
                    _dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => SetStatusImage(await imgRecord.GetImageAsBitmap()));
                }
                else
                {
                    // Other type, not handled by this demo
                    tagContents.Append("NDEF record not parsed by this demo app" + Environment.NewLine);
                }
            }
        }
Ejemplo n.º 18
0
        private void AddNdefContent(ResponseFrame frame, Exception e)
        {
            if (CheckForErrorsOrTimeout(frame, e))
            {
                return;
            }

            byte[] data = frame.Data;

            byte[] temp = new byte[data.Length - data[1] - 2];

            if (temp.Length > 0)
            {
                Array.Copy(data, 2 + data[1], temp, 0, temp.Length);

                NdefMessage message = NdefMessage.FromByteArray(temp);

                Action update = () =>
                {
                    foreach (NdefRecord record in message)
                    {
                        ndefData.AppendText("Ndef Record:\n\n");

                        if (record.TypeNameFormat == NdefRecord.TypeNameFormatType.Empty)
                        {
                            ndefData.AppendText("Empty NDEF Record");
                        }
                        else
                        {
                            string type = Encoding.UTF8.GetString(record.Type);
                            ndefData.AppendText($"TNF: {record.TypeNameFormat.ToString()} ({(byte)record.TypeNameFormat})\n");
                            ndefData.AppendText($"Type: {type}\n");

                            if (record.Id != null)
                            {
                                ndefData.AppendText($"Type: {BitConverter.ToString(record.Id)}\n");
                            }

                            if (type.Equals("U"))
                            {
                                NdefUriRecord uriRecord = new NdefUriRecord(record);
                                ndefData.AppendText($"Payload: {uriRecord.Uri}\n");
                            }
                            else if (type.Equals("T"))
                            {
                                NdefTextRecord textRecord = new NdefTextRecord(record);
                                ndefData.AppendText($"Encoding: {textRecord.TextEncoding.ToString()}\n");
                                ndefData.AppendText($"Language: {textRecord.LanguageCode}\n");
                                ndefData.AppendText($"Payload: {textRecord.Text}\n");
                            }
                            else if (type.Contains("text"))
                            {
                                ndefData.AppendText($"Payload: {Encoding.UTF8.GetString(record.Payload)}\n");
                            }
                            else
                            {
                                ndefData.AppendText($"Payload: {BitConverter.ToString(record.Payload)}");
                            }

                            ndefData.AppendText($"----------\n");
                        }
                    }
                };

                Dispatcher.BeginInvoke(update);
            }

            ShowSuccessStatus();
        }
        public void KeyboardWedge(ResponseFrame frame, Exception e)
        {
            DetectSingleNdef repeatRead  = new DetectSingleNdef(0, DetectTagSetting.Type2Type4AandMifare);
            bool             textEntered = false;

            if (CheckForErrorsOrTimeout(frame, e))
            {
                tappy.SendCommand(repeatRead, InvokeKeyboardFeature);
                return;
            }
            else if (frame.CompareCommandFamilies(new byte[] { 0x00, 0x01 }) && frame.ResponseCode == 0x02)
            {
                try
                {
                    byte[] data = frame.Data;
                    byte[] buf  = new byte[data.Length - data[1] - 2];

                    if (buf.Length > 0)
                    {
                        Array.Copy(data, 2 + data[1], buf, 0, buf.Length);

                        NdefMessage message = NdefMessage.FromByteArray(buf);

                        int numRecords = message.Count;
                        int recordNum  = 1;

                        foreach (NdefRecord record in message)
                        {
                            string type = Encoding.UTF8.GetString(record.Type);
                            textEntered = false;
                            if (record.TypeNameFormat == NdefRecord.TypeNameFormatType.NfcRtd && type.Equals("T") && recordTypes.Contains(RecordType.TEXT))
                            {
                                NdefTextRecord textRecord = new NdefTextRecord(record);
                                System.Windows.Forms.SendKeys.SendWait(textRecord.Text);
                                textEntered = true;
                            }
                            else if ((record.TypeNameFormat == NdefRecord.TypeNameFormatType.NfcRtd && type.Equals("U") && recordTypes.Contains(RecordType.URI)) ||
                                     (record.TypeNameFormat == NdefRecord.TypeNameFormatType.Uri && recordTypes.Contains(RecordType.URI)))
                            {
                                NdefUriRecord uriRecord = new NdefUriRecord(record);
                                System.Windows.Forms.SendKeys.SendWait(uriRecord.Uri);
                                textEntered = true;
                            }
                            else if ((record.TypeNameFormat == NdefRecord.TypeNameFormatType.ExternalRtd && recordTypes.Contains(RecordType.EXTERNAL)) ||
                                     (record.TypeNameFormat == NdefRecord.TypeNameFormatType.Mime && recordTypes.Contains(RecordType.MIME)))
                            {
                                System.Windows.Forms.SendKeys.SendWait(Encoding.UTF8.GetString(record.Payload));
                                textEntered = true;
                            }

                            if (textEntered == true && formModeActive == true)
                            {
                                if (recordNum == numRecords)
                                {
                                    System.Windows.Forms.SendKeys.SendWait("{ENTER}");
                                }
                                else
                                {
                                    System.Windows.Forms.SendKeys.SendWait("{TAB}");
                                }
                            }
                            else if (textEntered == true)
                            {
                                if (controlCharacters.Contains(ControlCharacter.CRLF))
                                {
                                    System.Windows.Forms.SendKeys.SendWait("{ENTER}");
                                }
                                if (controlCharacters.Contains(ControlCharacter.TAB))
                                {
                                    System.Windows.Forms.SendKeys.SendWait("{TAB}");
                                }
                            }

                            recordNum++;
                        }

                        if (textEntered)
                        {
                            Thread.Sleep(scanStaggerMs);
                        }
                    }
                    tappy.SendCommand(repeatRead, InvokeKeyboardFeature);
                    return;
                }
                catch
                {
                    Console.WriteLine("Error Parsing NDEF Response From Tappy");
                }
            }
            else
            {
                Console.WriteLine("Invalid TCMP Response From Tappy (i.e not the command family and response code expected)");
            }
        }
Ejemplo n.º 20
0
        private void nfcService_MessageReceivedCompleted(ProximityMessage message)
        {
            if (message.MessageType == "WriteableTag")
            {
                Int32 size = System.BitConverter.ToInt32(message.Data.ToArray(), 0);
                tagSize = size;
                LogMessage(AppResources.NfcWriteableTagSize + " " + size + " bytes", NfcLogItem.INFO_ICON);
            }
            else if (message.MessageType == "WindowsMime")
            {
                var buffer   = message.Data.ToArray();
                int mimesize = 0;
                for (mimesize = 0; mimesize < 256 && buffer[mimesize] != 0; ++mimesize)
                {
                }
                ;
                var    mimeType = Encoding.UTF8.GetString(buffer, 0, mimesize);
                string extra    = AppResources.NdefRecordMimeType + ": " + mimeType;
                LogMessage(AppResources.NdefMessageRecordType + ": WindowsMime", NfcLogItem.INFO_ICON, extra);
                return;
            }
            else if (message.MessageType == "NDEF:Unknown")
            {
                LogMessage(AppResources.NdefMessageRecordType + ": " + AppResources.NdefUnknown, NfcLogItem.INFO_ICON);
                return;
            }
            else if (message.MessageType == "NDEF")
            {
                var rawMsg      = message.Data.ToArray();
                var ndefMessage = NdefMessage.FromByteArray(rawMsg);

                // Loop over all records contained in the NDEF message
                string messageInformation = "";
                foreach (NdefRecord record in ndefMessage)
                {
                    string extra = "";
                    messageInformation = AppResources.NdefMessageRecordType + ": " + Encoding.UTF8.GetString(record.Type, 0, record.Type.Length);
                    //if the record is a Smart Poster
                    if (record.CheckSpecializedType(false) == typeof(NdefSpRecord))
                    {
                        // Convert and extract Smart Poster info
                        var spRecord = new NdefSpRecord(record);
                        extra  = AppResources.NdefSpUri + ": " + spRecord.Uri;
                        extra += "\n" + AppResources.NdefSpTitles + ": " + spRecord.TitleCount();
                        extra += "\n" + AppResources.NdefSpTitle + ": " + spRecord.Titles[0].Text;
                        if (spRecord.ActionInUse())
                        {
                            extra += "\n" + AppResources.NdefSpAction + ": " + spRecord.NfcAction;
                        }
                        LogMessage(messageInformation, NfcLogItem.INFO_ICON, extra);
                    }
                    if (record.CheckSpecializedType(false) == typeof(NdefUriRecord))
                    {
                        var uriRecord = new NdefUriRecord(record);
                        extra = AppResources.NdefSpUri + ": " + uriRecord.Uri;
                        LogMessage(messageInformation, NfcLogItem.INFO_ICON, extra);
                    }
                    if (record.CheckSpecializedType(false) == typeof(NdefTextRecord))
                    {
                        var textRecord = new NdefTextRecord(record);
                        extra  = AppResources.NdefTextRecordText + ": " + textRecord.Text;
                        extra += "\n" + AppResources.NdefTextRecordLanguage + ": " + textRecord.LanguageCode;
                        LogMessage(messageInformation, NfcLogItem.INFO_ICON, extra);
                    }
                    if (record.CheckSpecializedType(false) == typeof(NdefLaunchAppRecord))
                    {
                        var launchAppRecord = new NdefLaunchAppRecord(record);
                        foreach (KeyValuePair <string, string> entry in launchAppRecord.PlatformIds)
                        {
                            extra += AppResources.NdefLaunchAppRecordPlatform + ": " + entry.Key + "\n";
                            extra += AppResources.NdefLaunchAppRecordId + ": " + entry.Value + "\n";
                        }
                        extra = extra.TrimEnd('\n');
                        LogMessage(messageInformation, NfcLogItem.INFO_ICON, extra);
                    }
                    if (record.CheckSpecializedType(false) == typeof(NdefAndroidAppRecord))
                    {
                        var androidRecord = new NdefAndroidAppRecord(record);
                        extra = AppResources.NdefAAR + ": " + androidRecord.PackageName;
                        LogMessage(messageInformation, NfcLogItem.INFO_ICON, extra);
                    }
                }
                return;
            }
        }