Пример #1
0
        public void NdefMultipleMessage()
        {
            // Arrange
            // Extract the data from the Mifare card dump
            var extract = ExtractAllBlocksFromCardDump(CardDumpExamples.Memory1KDumpMultipleEntries);
            // Get the NDEF section from the card dump
            var ndef = ExtractAllMessage(extract);
            // Act
            // Get the NDEF Message
            NdefMessage message       = new NdefMessage(ndef);
            var         firstRecord   = message.Records.First();
            var         recordTestUri = message.Records[2];
            var         uriRecord     = new UriRecord(recordTestUri);
            var         mediaTest     = message.Records[5];
            var         media         = new MediaRecord(mediaTest);
            var         ret           = media.TryGetPayloadAsText(out string payloadAsText);
            var         lastRecord    = message.Records.Last();

            // Assert
            // Check if all is ok
            Assert.Equal(10, message.Records.Count);
            Assert.True(firstRecord.Header.IsFirstMessage);
            Assert.True(UriRecord.IsUriRecord(recordTestUri));
            Assert.False(MediaRecord.IsMediaRecord(recordTestUri));
            Assert.Equal("bing.com/search?q=.net%20core%20iot", uriRecord.Uri);
            Assert.Equal(UriType.HttpsWww, uriRecord.UriType);
            Assert.Equal(new Uri("https://www.bing.com/search?q=.net%20core%20iot"), uriRecord.FullUri);
            Assert.True(MediaRecord.IsMediaRecord(mediaTest));
            Assert.Equal("text/vcard", media.PayloadType);
            Assert.True(media.IsTextType);
            Assert.True(ret);
            Assert.Contains("VCARD", payloadAsText);
            Assert.True(lastRecord.Header.IsLastMessage);
        }
Пример #2
0
        /// <summary>
        /// This method will be called when an NFC tag is discovered by the application,
        /// as long as we've enabled 'foreground dispatch' - send it to us, don't go looking
        /// for another program to respond to the tag.  Not actually necessary for launching
        /// the interaction modes themselves; that'll happen even if they're in the background.
        /// Used here to enable the "write to tag" functionality.
        /// </summary>
        /// <param name="intent">The Intent representing the occurrence of "hey, we spotted an NFC!"</param>
        protected override void OnNewIntent(Intent intent)
        {
            if (_inWriteMode)
            {
                _inWriteMode = false;
                nfcTag       = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

                if (nfcTag == null)
                {
                    return;
                }

                var nfcID = nfcTag.tagID();
                Log.Info("Main", "NFC tag ID is " + nfcID ?? "(none)");

                // These next few lines will create a payload (consisting of a string)
                // and a mimetype. NFC records are arrays of bytes.
                var payload     = System.Text.Encoding.ASCII.GetBytes(selectedMode.Name);
                var mimeBytes   = System.Text.Encoding.ASCII.GetBytes(Res.AtroposMimeType);
                var newRecord   = new NdefRecord(NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
                var ndefMessage = new NdefMessage(new[] { newRecord });

                if (!TryAndWriteToTag(nfcTag, ndefMessage))
                {
                    // Maybe the write couldn't happen because the tag wasn't formatted?
                    TryAndFormatTagWithMessage(nfcTag, ndefMessage);
                }
                //_nfcAdapter.DisableForegroundDispatch(this);
            }
        }
Пример #3
0
        public static 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);
        }
Пример #4
0
        private void ButtonWriteNFC_Clicked(object sender, EventArgs e)
        {
            var spRecord = new NdefSpRecord
            {
                Uri       = "www.google.at",
                NfcAction = NdefSpActRecord.NfcActionType.DoAction,
            };

            spRecord.AddTitle(new NdefTextRecord
            {
                Text         = "NFCForms - XamarinForms - Write-Demo",
                LanguageCode = "en"
            });
            // Add record to NDEF message
            var msg = new NdefMessage {
                spRecord
            };

            try
            {
                nfcService.WriteTag(msg);
            }
            catch (Exception excp)
            {
                DisplayAlert("Error", excp.Message, "OK");
            }
        }
Пример #5
0
        private IEnumerable <string> readNDEFMEssage(NdefMessage message)
        {
            List <string> allTagInfos = new List <string>();

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

            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);
                    allTagInfos.Add("URI: " + spRecord.Uri);
                    allTagInfos.Add("Titles: " + spRecord.TitleCount());
                    allTagInfos.Add("1. Title: " + spRecord.Titles[0].Text);
                    allTagInfos.Add("Action set: " + spRecord.ActionInUse());
                }

                if (record.CheckSpecializedType(false) == typeof(NdefUriRecord))
                {
                    // Convert and extract Smart Poster info
                    var spRecord = new NdefUriRecord(record);
                    allTagInfos.Add("Text: " + spRecord.Uri);
                }
            }
            return(allTagInfos);
        }
Пример #6
0
        /// <summary>
        /// Attempts to format a new tag with the message.
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="ndefMessage"></param>
        /// <returns></returns>
        private bool TryAndFormatTagWithMessage(Tag tag, NdefMessage ndefMessage)
        {
            var format = NdefFormatable.Get(tag);

            if (format == null)
            {
                if (tag.GetTechList().Any((s) => s.ToLower().Contains("ndef")))
                {
                    DisplayMessage("Tag supports NDEF but is not formattable - not all of them are.\nYou might also retry the write.");
                }
                else
                {
                    DisplayMessage("Tag does not appear to support NDEF format.");
                }
            }
            else
            {
                try
                {
                    format.Connect();
                    format.Format(ndefMessage);
                    DisplayMessage("Tag successfully written.");
                    return(true);
                }
                catch (IOException ioex)
                {
                    var msg = "There was an error trying to format the tag.";
                    DisplayMessage(msg);
                    Log.Error(Res.AtroposMimeType, ioex, msg);
                }
            }
            return(false);
        }
Пример #7
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();
            });
        }
Пример #8
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
                UpdateUiForNfcStatusAsync();
            }
            catch (Exception e)
            {
                SetStatusOutput(string.Format(_loader.GetString("StatusPublicationError"), e.Message));
            }
        }
Пример #9
0
        private bool?FormatNdef(Tag tag, NdefMessage ndefMsg)
        {
            NdefFormatable ndef = NdefFormatable.Get(tag);

            if (ndef == null)
            {
                ShowToast("Tag is not NDEF formatable.");
                return(false);
            }

            try
            {
                ndef.Connect();
                ndef.Format(ndefMsg);
            }
            catch (Exception e)
            {
                ShowToast("Failed formating tag: " + e.Message);
                return(null);
            }
            finally
            {
                try
                {
                    ndef.Close();
                }
                catch (Exception)
                {
                    ShowToast("Tag connection failed to close.");
                }
            }

            return(true);
        }
Пример #10
0
        /// <summary>
        /// This method will try and write the specified message to the provided tag.
        /// </summary>
        /// <param name="tag">The NFC tag that was detected.</param>
        /// <param name="ndefMessage">An NDEF message to write.</param>
        /// <returns>true if the tag was written to.</returns>
        private bool TryAndSendNfc(Tag tag, NdefMessage ndefMessage)
        {
            // This object is used to get information about the NFC tag as
            // well as perform operations on it.
            var ndef = Ndef.Get(tag);

            if (ndef != null)
            {
                ndef.Connect();

                // Once written to, a tag can be marked as read-only - check for this.
                if (!ndef.IsWritable)
                {
                    DisplayMessage("Tag is read-only.");
                }

                // NFC tags can only store a small amount of data, this depends on the type of tag its.
                var size = ndefMessage.ToByteArray().Length;
                if (ndef.MaxSize < size)
                {
                    DisplayMessage("Tag doesn't have enough space.");
                }

                ndef.WriteNdefMessage(ndefMessage);
                DisplayMessage("Succesfully wrote tag.");
                return(true);
            }

            return(false);
        }
Пример #11
0
        void HandleClicked(object sender, EventArgs e)
        {
            var spRecord = new NdefSpRecord
            {
                Uri       = "www.poz1.com",
                NfcAction = NdefSpActRecord.NfcActionType.DoAction,
            };

            spRecord.AddTitle(new NdefTextRecord
            {
                Text         = "NFCForms - XamarinForms - Poz1.com",
                LanguageCode = "en"
            });
            // Add record to NDEF message
            var msg = new NdefMessage {
                spRecord
            };

            try
            {
                device.WriteTag(msg);
            }
            catch (Exception excp)
            {
                DisplayAlert("Error", excp.Message, "OK");
            }
        }
Пример #12
0
        private void WriteDataToTag(Tag tag)
        {
            try
            {
                ndefHandler.SetKeys(AppSettings.Global.PubKey, AppSettings.Global.PrivKey);
                ndefHandler.SetExtraSignDataFromTag(tag);

                byte[]      rawNdefMsg = ndefHandler.GenerateRawNdefMessage(writeData);
                NdefMessage ndefMsg    = new NdefMessage(rawNdefMsg);

                bool?written = WriteNdef(tag, ndefMsg);

                if (written == false)
                {
                    written = FormatNdef(tag, ndefMsg);
                }

                if (written == true)
                {
                    ShowToast("Written " + ndefMsg.ByteArrayLength + " bytes of NDEF data.");
                    Finish();
                }
            }
            finally
            {
                ndefHandler.ClearKeys();
                ndefHandler.ClearExtraSignData();
            }
        }
Пример #13
0
        private void NfcHandler_ReceiveNdefMessage(NdefMessage msg)
        {
            NdefHandler.SetKeys(AppSettings.PubKey);

            Dictionary <string, string> vals = NdefHandler.ParseNdefMessage(msg);

            bool?sigValid = GetSigValid(vals);

            if (TryHandleSettings(vals, sigValid))
            {
                return;
            }

            if (sigValid == false)
            {
                SignalFailure();
            }
            else
            {
                SignalSuccess();
            }

            if (NdefHandler.HasPubKey() && sigValid != true && !AppSettings.ReportAllScans)
            {
                return;
            }

            HandleScannedTag(vals, sigValid);
        }
Пример #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="ndefMessage"></param>
        /// <returns></returns>
        private bool TryAndFormatTagWithMessage(Tag tag, NdefMessage ndefMessage)
        {
            var format = NdefFormatable.Get(tag);

            if (format == null)
            {
                DisplayMessage("Tag does not appear to support NDEF format.");
            }
            else
            {
                try
                {
                    format.Connect();
                    format.Format(ndefMessage);
                    DisplayMessage("Tag successfully written.");
                    return(true);
                }
                catch (Java.IO.IOException ioex)
                {
                    var msg = "There was an error trying to format the tag.";
                    DisplayMessage(msg);
                    Log.Error(this.Application.PackageName, ioex.Message, msg);
                }
            }
            // clear the input text
            _writeTextView.Text = String.Empty;
            return(false);
        }
Пример #15
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);
        }
Пример #16
0
        private string ReadNFC(Ndef ndef)
        {
            string message;

            try
            {
                if (ndef == null)
                {
                    throw new System.Exception("Não foi possível ler o cartão.");
                }

                if (!ndef.IsConnected)
                {
                    ndef.Connect();
                }

                NdefMessage ndefMessage = ndef.NdefMessage;
                if (ndefMessage == null)
                {
                    throw new System.Exception("Não foi possível ler o cartão.");
                }
                else
                {
                    message = Encoding.UTF8.GetString(ndefMessage.GetRecords()[0].GetPayload());
                    return(message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new System.Exception("Não foi possível ler o cartão.");
            }
        }
Пример #17
0
        private void WriteToTagExecute()
        {
            var spRecord = new NdefSpRecord
            {
                Uri       = shortenedNote,
                NfcAction = NdefSpActRecord.NfcActionType.DoAction
            };

            if (SecureNoteTitle != String.Empty && SecureNoteTitle != null)
            {
                spRecord.AddTitle(new NdefTextRecord
                {
                    Text         = SecureNoteTitle,
                    LanguageCode = CultureInfo.CurrentCulture.TwoLetterISOLanguageName
                });
            }
            var msg = new NdefMessage {
                spRecord
            };

            if (tagSize >= msg.ToByteArray().Length)
            {
                nfcService.WriteNdefMessageToTag(msg);
                uxService.ShowToastNotification("NFC", AppResources.NfcMessageWritten);
            }
            else
            {
                uxService.ShowToastNotification("NFC", AppResources.NfcMessageTooLong);
                LogMessage(AppResources.NfcMessageTooLong, NfcLogItem.WARNING_ICON);
            }
        }
Пример #18
0
 internal NdefMessage[] GetNdefMessages(Intent intent)
 {
     try
     {
         IParcelable[] rawMessages = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
         if (rawMessages != null)
         {
             NdefMessage[] messages = new NdefMessage[rawMessages.Length];
             for (int i = 0; i < messages.Length; i++)
             {
                 messages[i] = (NdefMessage)rawMessages[i];
             }
             return(messages);
         }
         else
         {
             return(null);
         }
     }
     catch (Exception e)
     {
         Log.Error(TAG, e.Message + "\n" + e.StackTrace);
         return(null);
     }
 }
Пример #19
0
        private void PublishMessageExecute()
        {
            var spRecord = new NdefSpRecord
            {
                Uri       = "http://msdn.microsoft.com/windows",
                NfcAction = NdefSpActRecord.NfcActionType.DoAction
            };

            spRecord.AddTitle(new NdefTextRecord
            {
                Text         = "Windows Dev Center",
                LanguageCode = "es"
            });
            // Add record to NDEF message
            var msg = new NdefMessage {
                spRecord
            };

            nfcService.PublishNdefMessage(msg);
            //var uri = new Uri(" http://www.nokia.com/");
            ////encode uri to UTF16LE.
            //var buffer = Encoding.Unicode.GetBytes(uri.ToString());
            //nfcService.PublishBinaryMessage("WindowsUri", buffer);
            //NdefUriRecord rec = new NdefUriRecord { Uri = "http://www.nokia.com/" };
            //NdefMessage msg = new NdefMessage { rec };
            //nfcService.PublishNdefMessage(msg);
        }
Пример #20
0
        void HandleNewTag(object sender, NfcTag e)
        {
            var                       contentRead        = Encoding.ASCII.GetString(e.NdefMessage[0].Payload);
            string                    serialNumber       = BitConverter.ToString(e.Id);
            var                       r                  = new CrudApi(App.btoken);
            Uri                       restUri            = new Uri(Constants.RestURLAddAttendance);
            string                    NFCContentUploaded = Guid.NewGuid().ToString();
            AddAttendanceBody         body               = new AddAttendanceBody(serialNumber, contentRead, NFCContentUploaded);
            AddAttendanceResponseBody responseBody       = null;

            try
            {
                var spRecord = new NdefTextRecord
                {
                    Payload = Encoding.ASCII.GetBytes(NFCContentUploaded)
                };
                var msg = new NdefMessage {
                    spRecord
                };
                device.WriteTag(msg);
                responseBody = Task.Run(async() =>
                                        { return(await r.PostAsync <AddAttendanceBody, AddAttendanceResponseBody>(restUri, body)); }).Result;
                string text = responseBody.EmployeeInfo + " succesfully added attendance no." + responseBody.ID + " on point " + System.Environment.NewLine + responseBody.TagInfo;
                ShowSuccess(text);
            }
            catch (Exception excp)
            {
                ShowFail("An error occurred.");
                DependencyService.Get <IAudio>().PlayMp3File("door.mp3");
                return;
            }
            Device.StartTimer(System.TimeSpan.FromSeconds(5), () => { ShowBasic(); return(true); });
            return;
        }
Пример #21
0
        public bool WriteExternalType(string pathPrefix, string payload, object tag)
        {
            if (!(tag is Tag))
            {
                return(false);
            }
            if (string.IsNullOrEmpty(pathPrefix) || string.IsNullOrEmpty(payload))
            {
                return(false);
            }

            WriteResult writeResult = WriteResult.FAILED;

            try
            {
                NdefRecord extRecord = new NdefRecord(
                    (short)TypeNameFormat.TNF_EXTERNAL_TYPE,
                    Encoding.UTF8.GetBytes(pathPrefix),
                    new byte[0],
                    Encoding.UTF8.GetBytes(payload));
                NdefMessage ndefMessage = new NdefMessage(new NdefRecord[] { extRecord });
                writeResult = WriteTag(ndefMessage, (Tag)tag);
            }
            catch { }
            return(writeResult == WriteResult.OK);
        }
Пример #22
0
        /// <summary>
        /// Returns informations contains in NFC Tag
        /// </summary>
        /// <param name="tag">Android <see cref="Tag"/></param>
        /// <param name="ndefMessage">Android <see cref="NdefMessage"/></param>
        /// <returns><see cref="ITagInfo"/></returns>
        ITagInfo GetTagInfo(Tag tag, NdefMessage ndefMessage = null)
        {
            if (tag == null)
            {
                return(null);
            }

            var ndef = Ndef.Get(tag);

            if (ndef == null)
            {
                return(null);
            }

            if (ndefMessage == null)
            {
                ndefMessage = ndef.CachedNdefMessage;
            }

            var nTag = new TagInfo()
            {
                IsWritable = ndef.IsWritable
            };

            if (ndefMessage != null)
            {
                var records = ndefMessage.GetRecords();
                nTag.Records = GetRecords(records);
            }

            return(nTag);
        }
Пример #23
0
        public bool WriteAbsoluteUri(string uri, object tag)
        {
            if (!(tag is Tag))
            {
                return(false);
            }
            if (string.IsNullOrEmpty(uri))
            {
                return(false);
            }

            WriteResult writeResult = WriteResult.FAILED;

            try
            {
                NdefRecord uriRecord = new NdefRecord(
                    (short)TypeNameFormat.TNF_ABSOLUTE_URI,
                    Encoding.ASCII.GetBytes(uri),
                    new byte[0],
                    new byte[0]);
                NdefMessage ndefMessage = new NdefMessage(new NdefRecord[] { uriRecord });
                writeResult = WriteTag(ndefMessage, (Tag)tag);
            }
            catch { }
            return(writeResult == WriteResult.OK);
        }
Пример #24
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();

            // Parse tag contents
            try
            {
                // Clear bitmap if the last tag contained an image
                SetStatusImage(null);

                // Parse the contents of the tag
                await ParseTagContents(ndefMessage, tagContents);

                // Update status text for UI
                SetStatusOutput(string.Format(_loader.GetString("StatusTagParsed"), tagContents));
            }
            catch (Exception ex)
            {
                SetStatusOutput(string.Format(_loader.GetString("StatusNfcParsingError"), ex.Message));
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="ndefMessage"></param>
        /// <returns></returns>
        private bool TryAndFormatTagWithMessage(Tag tag, NdefMessage ndefMessage)
        {
            var format = NdefFormatable.Get(tag);

            if (format == null)
            {
                DisplayMessage("Tag does not appear to support NDEF format.");
            }
            else
            {
                try
                {
                    format.Connect();
                    format.Format(ndefMessage);
                    DisplayMessage("Tag successfully written.");
                    return(true);
                }
                catch (IOException ioex)
                {
                    var msg = "There was an error trying to format the tag.";
                    DisplayMessage(msg);
                    Log.Error(Tag, ioex, msg);
                }
            }
            return(false);
        }
Пример #26
0
        private string ReadTagAsync(Tag tag)
        {
            Ndef ndef = Ndef.Get(tag);

            if (ndef == null)
            {
                // NDEF is not supported by this Tag.
                return(null);
            }

            NdefMessage ndefMessage = ndef.CachedNdefMessage;

            NdefRecord[] records = ndefMessage.GetRecords();
            foreach (NdefRecord ndefRecord in records)
            {
                if (ndefRecord.Tnf == NdefRecord.TnfWellKnown)
                {
                    try {
                        return(ReadText(ndefRecord));
                    } catch (UnsupportedEncodingException ex) {
                        Log.Error("VirtualWall", "Unsupported Encoding", ex);
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// This method is called when an NFC tag is discovered by the application.
        /// </summary>
        /// <param name="intent"></param>
        protected override void OnNewIntent(Intent intent)
        {
            if (_inWriteMode)
            {
                _inWriteMode = false;
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

                if (tag == null)
                {
                    return;
                }

                // These next few lines will create a payload (consisting of a string)
                // and a mimetype. NFC record are arrays of bytes.
                var payload     = Encoding.ASCII.GetBytes(GetRandomHominid());
                var mimeBytes   = Encoding.ASCII.GetBytes(ViewApeMimeType);
                var apeRecord   = new NdefRecord(NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
                var ndefMessage = new NdefMessage(new[] { apeRecord });

                if (!TryAndWriteToTag(tag, ndefMessage))
                {
                    // Maybe the write couldn't happen because the tag wasn't formatted?
                    TryAndFormatTagWithMessage(tag, ndefMessage);
                }
            }
        }
Пример #28
0
        protected override void OnNewIntent(Intent intent)
        {
            if (_inWriteMode)
            {
                _inWriteMode = false;
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

                if (tag == null)
                {
                    return;
                }

                // These next few lines will create a payload (consisting of a string)
                // and a mimetype. NFC record are arrays of bytes.
                var message = _inputText.Text += " " + DateTime.Now.ToString("HH:mm:ss dd/M/yyyy");
                _outputText.Text = message;
                var payload         = Encoding.ASCII.GetBytes(message);
                var mimeBytes       = Encoding.ASCII.GetBytes(ViewIsolationType);
                var isolationRecord = new NdefRecord(NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
                var ndefMessage     = new NdefMessage(new[] { isolationRecord });

                TryAndFormatTagWithMessage(tag, ndefMessage);
                if (!TryAndWriteToTag(tag, ndefMessage))
                {
                    // Maybe the write couldn't happen because the tag wasn't formatted?
                    TryAndFormatTagWithMessage(tag, ndefMessage);
                }
            }
        }
Пример #29
0
        /// <summary>
        /// Returns informations contains in NFC Tag
        /// </summary>
        /// <param name="tag">Android <see cref="Tag"/></param>
        /// <param name="ndefMessage">Android <see cref="NdefMessage"/></param>
        /// <returns><see cref="ITagInfo"/></returns>
        ITagInfo GetTagInfo(Tag tag, NdefMessage ndefMessage = null)
        {
            if (tag == null)
            {
                return(null);
            }

            var ndef = Ndef.Get(tag);
            var nTag = new TagInfo(tag.GetId(), ndef != null);

            if (ndef != null)
            {
                nTag.Capacity   = ndef.MaxSize;
                nTag.IsWritable = ndef.IsWritable;

                if (ndefMessage == null)
                {
                    ndefMessage = ndef.CachedNdefMessage;
                }

                if (ndefMessage != null)
                {
                    var records = ndefMessage.GetRecords();
                    nTag.Records = GetRecords(records);
                }
            }

            return(nTag);
        }
Пример #30
0
        private static void WriteTagFile(string pathName, string tagName, NdefMessage ndefMessage)
        {
            // NDEF message
            var ndefMessageBytes = ndefMessage.ToByteArray();

            // Write NDEF message to binary file
            var binFileName = string.Format(FileNameBin, tagName);

            using (var fs = File.Create(Path.Combine(pathName, binFileName)))
            {
                foreach (var curByte in ndefMessageBytes)
                {
                    fs.WriteByte(curByte);
                }
            }

            // Write NDEF message to hex file
            var hexFileName = string.Format(FileNameHex, tagName);

            using (var fs = File.Create(Path.Combine(pathName, hexFileName)))
            {
                using (var logFileWriter = new StreamWriter(fs))
                {
                    logFileWriter.Write(ConvertToHexByteString(ndefMessageBytes));
                }
            }
        }
Пример #31
0
 protected override void NewMessage(string tagid, NdefMessage message)
 {
     if (_result != null)
     {
         MessageReceived result = new MessageReceived(tagid,message,this);
         _result.TrySetResult(result);
     }
 }
Пример #32
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);

                }
            }
        }
Пример #33
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     var device = ProximityDevice.GetDefault();
     if (device == null) return;
     var record = new NdefSpRecord {
         Uri = "cloudsdale://clouds/" + cloud.id,
         NfcAction = NdefSpActRecord.NfcActionType.DoAction
     };
     record.AddTitle(new NdefTextRecord { Text = cloud.name, LanguageCode = "en" });
     var message = new NdefMessage { record };
     messageIds.Add(device.PublishBinaryMessage("NDEF", message.ToByteArray().AsBuffer()));
 }
Пример #34
0
        private async void DoWriteTag()
        {

            WritingTag = true;
            Result = "";
            
            NdefLibrary.Ndef.NdefMessage message = new NdefMessage();
            NdefTextRecord record = new NdefTextRecord();
            record.LanguageCode = "en";
            record.TextEncoding = NdefTextRecord.TextEncodingType.Utf8;
            record.Text = Message;
            message.Add(record);

            var result = await _writeTask.WriteTag(message);
            if (result.DidSucceed)
            {
                Result = "Wrote Message to tag with ID " + result.NFCTag.Id;
            }
            else
            {
                switch(result.ReasonForFailure)

                {                    
                    case FailureReasons.TagReadOnly:
                        Result = "The tag was read only";
                        break;
                    case FailureReasons.TagTooSmall:
                        Result = "The tag was too small for this message";

                        break;
                    case FailureReasons.ErrorDuringWrite:
                        Result = "An error occured whislt trying to write the tag";

                        break;
                    case FailureReasons.UnableToFormatTag:
                        Result = "The tag was not formatted. Please format it first";

                        break;
                    case FailureReasons.Unkown:
                        Result = "An unkown error occured";

                        break;
                    case FailureReasons.TagLostDuringWrite:
                        Result = "The tag was removed whilst it was been written to";

                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }
            WritingTag = false;
        }
Пример #35
0
        static void r_NewNdefMessageDetected(NdefMessage message, int readerId)
        {
            Answer a = answers.Find(an => an.ReaderID == readerId);
            if (a == null)
            {
                a = new Answer(readerId);
                answers.Add(a);
                Console.WriteLine("Buzzer '{0}' initialisiert", a.Label);
            }
            var textRecord = new NdefTextRecord(message.First());

            Console.WriteLine("Tag '{0}' an Buzzer '{1}'", textRecord.Text, a.Label);
        }
Пример #36
0
        private void Device_DeviceArrived(ProximityDevice sender)
        {
            var data = new { Employee = new { Id = 2572923226000L, Name = "TestUser" } };
            var payload = JsonConvert.SerializeObject(data);

            var spRecord = new NdefSpRecord
            {
                NfcAction = NdefSpActRecord.NfcActionType.OpenForEditing,
                Payload = Encoding.UTF8.GetBytes(payload),
                NfcSize = (uint)payload.Length,
                Type = Encoding.UTF8.GetBytes("application/json; charset=\"utf-8\"")
            };

            var msg = new NdefMessage { spRecord };

            long publishingId = device.PublishBinaryMessage("NDEF:WriteTag", msg.ToByteArray().AsBuffer(), (d0, id) => {
                device.DeviceArrived -= Device_DeviceArrived;
                Debug.WriteLine(" published. id = " + id);
                var notify = new MessageDialog("The message has been published.");
            });
        }
Пример #37
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);
        }
Пример #38
0
        private ObservableCollection<string> readNDEFMEssage(NdefMessage message)
        {

            ObservableCollection<string> collection = new ObservableCollection<string>();
            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;
        }
Пример #39
0
 void HandleClicked(object sender, EventArgs e)
 {
     var spRecord = new NdefSpRecord
     {
         Uri = "www.poz1.com",
         NfcAction = NdefSpActRecord.NfcActionType.DoAction,
     };
     spRecord.AddTitle(new NdefTextRecord
     {
         Text = "NFCForms - XamarinForms - Poz1.com",
         LanguageCode = "en"
     });
     // Add record to NDEF message
     var msg = new NdefMessage { spRecord };
     try
     {
         device.WriteTag(msg);
     }
     catch (Exception excp)
     {
         DisplayAlert("Error", excp.Message, "OK");
     }
 }
Пример #40
0
 public Task<WriteResult> WriteTag(NdefMessage message)
 {
     return WriteTag(message, CancellationToken.None);
 }
Пример #41
0
        public void SetPublishCrew(string personnel)
        {
            if (_proximity != null)
            {
                if (_subscribedMessageId != -1)
                {
                    _proximity.StopSubscribingForMessage(_subscribedMessageId);

                    _subscribedMessageId = -1;
                }

                try
                {
                    
                    //In case for Crew
                    var record = GetPublishingMessage(typeof(NdefTextRecord), personnel.ToString());
                    //In case for foreman to auto login
                    //var record = GetPublishingMessage(typeof(NdefLaunchAppRecord), "user="******"NDEF:WriteTag", msg.ToByteArray().AsBuffer(), messageTransmitted);
                    //NotifyUser("Publishing Message: \n" + record.ToString(), NotifyType.StatusMessage);

                    /*
                     * This section is based on MSDN and same function with using NDEF Library.
                     * But it was not verified
                     */
                    //string launchArgs = "user="******"!" + praid;
                    //string launchAppMessage = launchArgs + "\tWindows\t" + appName;
                    //var dataWriter = new Windows.Storage.Streams.DataWriter();
                    //dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                    //dataWriter.WriteString(launchAppMessage);
                    //_proximity.PublishBinaryMessage("LaunchApp:WriteTag", dataWriter.DetachBuffer(), messageTransmitted);
                    //NotifyUser("Publishing Message: \n" + launchArgs, NotifyType.StatusMessage);
                    
                }
                catch (Exception e)
                {
                    _subscribedMessageId = _proximity.SubscribeForMessage("NDEF", messageReceived);
                    this.NotifyUser(e.Message, NotifyType.ErrorMessage);
                }
            }
            else
                this.NotifyUser("NFC Device could not be found...", NotifyType.ErrorMessage);
        }
Пример #42
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);
        }
Пример #43
0
        /// <summary>
        /// Reverse function to parseRecords() - this one takes
        /// the information stored in the individual record instances and assembles
        /// it into the payload of the base class.
        /// </summary>
        /// <remarks>
        /// As the URI is mandatory, the payload will not be assembled
        /// if no URI is defined.
        /// </remarks>
        /// <returns>Whether assembling the payload was successful.</returns>
        private bool AssemblePayload()
        {
            // Uri is mandatory - don't assemble the payload if it's not set
            if (RecordUri == null) return false;

            // URI (mandatory)
            var message = new NdefMessage { RecordUri };

            // Title(s) (optional)
            if (Titles != null && Titles.Count > 0)
                message.AddRange(Titles);

            // Action (optional)
            if (ActionInUse())
                message.Add(_recordAction);

            // Size (optional)
            if (SizeInUse())
                message.Add(_recordSize);

            // Mime Type (optional)
            if (MimeTypeInUse())
                message.Add(_recordMimeType);

            // Image (optional)
            if (ImageInUse())
                message.Add(_recordImage);

            SetPayloadAndParse(message.ToByteArray(), false);

            return true;
        }
Пример #44
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);
            // Update status text for UI
            SetStatusOutput(string.Format((writeToTag ? AppResources.StatusWriteToTag : AppResources.StatusWriteToDevice), msgArray.Length, _publishingMessageId));
            // Update enabled / disabled state of buttons in the User Interface
            SetStatusOutput(string.Format("You said \"{0}\"\nPlease touch a tag to write the message.", recordresult));
           



            recordresult = "";
            UpdateUiForNfcStatus();
        }
Пример #45
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(NdefIcalendarRecordBase))
                //{
                //    // --------------------------------------------------------------------------
                //    // Convert and extract iCalendar info
                //    var icalendarRecord = new NdefIcalendarRecord(record);
                //    tagContents.Append("-> iCalendar record" + Environment.NewLine);
                //    var ap = icalendarRecord.AppointmentData;
                //    if (!String.IsNullOrEmpty(ap.Subject))
                //        tagContents.AppendFormat("Subject: {0}\n", ap.Subject);
                //    if (!String.IsNullOrEmpty(ap.Details))
                //        tagContents.AppendFormat("Details: {0}\n", ap.Details);
                //    if (!String.IsNullOrEmpty(ap.Organizer.Address))
                //        tagContents.AppendFormat("Organizer Address: {0}\n", ap.Organizer.Address);
                //    if (!String.IsNullOrEmpty(ap.Location))
                //        tagContents.AppendFormat("Location: {0}\n", ap.Location);
                //    tagContents.AppendFormat("Start time: {0}\n", ap.StartTime);
                //    tagContents.AppendFormat("Duration: {0}\n", ap.Duration);
                //    tagContents.AppendFormat("AllDay? {0}\n", ap.AllDay ? "yes" : "no");
                //    if (ap.Reminder != null)
                //        tagContents.AppendFormat("Reminder: {0}\n", ap.Reminder);
                //}
                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);
                }
            }
        }
Пример #46
0
 void HandleClicked(object sender, EventArgs e)
 {
     var spRecord = new NdefSpRecord
     {
         NfcAction = NdefSpActRecord.NfcActionType.DoAction,
     };
     spRecord.AddTitle(new NdefTextRecord
         {
             Text = "00001:5.49"
         });
     // Add record to NDEF message
     var msg = new NdefMessage { spRecord };
     try
     {
         device.WriteTag(msg);
     }
     catch (Exception excp)
     {
         DisplayAlert("Error", excp.Message, "OK");
     }
 }
Пример #47
0
        private static void WriteTagFile(string pathName, string tagName, NdefMessage ndefMessage)
        {
            // NDEF message
            var ndefMessageBytes = ndefMessage.ToByteArray();

            // Write NDEF message to binary file
            var binFileName = String.Format(FileNameBin, tagName);
            using (var fs = File.Create(Path.Combine(pathName, binFileName)))
            {
                foreach (var curByte in ndefMessageBytes)
                {
                    fs.WriteByte(curByte);
                }
            }

            // Write NDEF message to hex file
            var hexFileName = String.Format(FileNameHex, tagName);
            using (var fs = File.Create(Path.Combine(pathName, hexFileName)))
            {
                using (var logFileWriter = new StreamWriter(fs))
                {
                    logFileWriter.Write(ConvertToHexByteString(ndefMessageBytes));
                }
            }
        }
Пример #48
0
     //   private Windows.UI.Core.CoreDispatcher _dispatcher =
     //Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;

     //   private async void ProximityDeviceArrived(object sender)
     //   {
     //       await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
     //       () =>
     //       {
     //           StatusOutput.Text += "Proximate device arrived.\n";
     //       });
     //   }

     //   private async void ProximityDeviceDeparted(object sender)
     //   {
     //       await _dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
     //       () =>
     //       {
     //           StatusOutput.Text += "Proximate device departed.\n";
     //       });
     //   }

        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);
            // Update status text for UI
           //_publishingMessageId = -1;
            SetStatusOutput(string.Format((writeToTag ? AppResources.StatusWriteToTag : AppResources.StatusWriteToDevice), msgArray.Length, _publishingMessageId));
           
        }
Пример #49
0
        public string Write()
        {
            Log.Debug("Card write");

            try
            {
                using (var reader = new IsoReader(CardContext, GetReader(), SCardShareMode.Shared, SCardProtocol.Any, false))
                {
                    var status = GetReaderStatus(reader);

                    Log.Debug(String.Format("Card State: {0}", status.CardState));

                    if (!status.CardState.HasFlag(SCardState.Present))
                        return null;

                    var id = GetCardId(reader);
                    var cardName = GetCardName(status.Atr);
                    var cardType = GetInt16(cardName);

                    var isMifare = cardType == CardReader.Mifare1KCard || cardType == CardReader.Mifare4KCard;
                    var isMifareUltralight = cardType == CardReader.MifareUltralightCard;

                    Log.Debug(String.Format("Card Id: {0}", BitConverter.ToString(id)));

                    var cardString = BitConverter.ToString(cardName.Concat(id).ToArray()).Replace("-", "");

                    if (isMifareUltralight)
                    {
                        var msg = new NdefMessage { new NdefUriRecord { Uri = CardReader.CardUri + "/#/" + cardString } };
                        var data = msg.ToByteArray();
                        var buffer = new List<byte>(new byte[] { 0x03, (byte)data.Length }.Concat(data));

                        WriteAllCardBytes(reader, buffer.ToArray(), isMifareUltralight ? 4 : 16);
                    }

                    return BitConverter.ToString(cardName.Concat(id).ToArray()).Replace("-", "");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

            return null;
        }
Пример #50
0
        /// <summary>
        /// Create the payload based on the data stored in the properties. Usually called
        /// automatically when changing properties, but you might need to call this manually
        /// if you modify the list of alternative carrier records directly without using
        /// accessor method provided by this class.
        /// </summary>
        /// <exception cref="NdefException">Thrown if unable to assemble the payload.
        /// The exception message contains further details about the issue.</exception>
        public void AssemblePayload()
        {
            if (_handoverVersion == null)
            {
                throw new NdefException(NdefExceptionMessages.ExHandoverInvalidVersion);
            }

            // Convert child records to message
            var childMsg = new NdefMessage();
            if (_handoverAlternativeCarrierRecords != null) childMsg.AddRange(_handoverAlternativeCarrierRecords);
            if (_handoverErrorRecord != null) childMsg.Add(_handoverErrorRecord);

            var childBytes = childMsg.ToByteArray();

            var newPayload = new byte[childBytes.Length + 1];

            // Frist byte: handover version
            newPayload[0] = _handoverVersion.Version;

            // Rest of the payload: child message containing Alternative Carrier records + Error record
            Array.Copy(childBytes, 0, newPayload, 1, childBytes.Length);

            _payload = newPayload;
        }
Пример #51
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
         UpdateUiForNfcStatusAsync();
     }
     catch (Exception e)
     {
         SetStatusOutput(string.Format(_loader.GetString("StatusPublicationError"), e.Message));
     }
 }
Пример #52
0
        protected DokanError WritePayload(byte[] payload, string extension)
        {
            // Make sure the chip is still here
            if (!rfidListener.ReconnectOnCard())
            {
                log.Error("Card reconnection failed");
                return DokanError.ErrorNotReady;
            }

            IChip chip = rfidListener.GetChip();
            ICardService svc = chip.GetService(CardServiceType.CST_NFC_TAG);
            IDESFireEV1NFCTag4CardService nfcsvc = svc as IDESFireEV1NFCTag4CardService;
            if (nfcsvc == null)
            {
                log.Error("No NFC service.");
                // If no NFC service for this chip, we must fail
                return DokanError.ErrorNotReady;
            }

            try
            {
                IStorageCardService storage = chip.GetService(CardServiceType.CST_STORAGE) as IStorageCardService;
                if (storage != null)
                {
                    storage.Erase();
                }
                nfcsvc.CreateNFCApplication(1, null);

                NdefMessage ndef = new NdefMessage();
                switch (extension)
                {
                    case "txt":
                        log.Info("Adding Text Record");
                        ndef.AddRawTextRecord(payload);
                        break;
                    case "url":
                        string lnk = Encoding.UTF8.GetString(payload);
                        int urlpos = lnk.IndexOf("URL=");
                        if (urlpos > -1)
                        {
                            urlpos += 4;
                            int end = lnk.IndexOf(Environment.NewLine, urlpos);
                            if (end < 0)
                            {
                                end = lnk.Length - urlpos;
                            }
                            else
                            {
                                end -= urlpos;
                            }
                            string url = lnk.Substring(urlpos, end).Trim();
                            log.Info(String.Format("Adding Uri Record `{0}`", url));
                            ndef.AddUriRecord(url, UriType.NO_PREFIX);
                        }
                        else
                        {
                            log.Warn("Cannot found URL on link file content.");
                        }
                        break;
                    default:
                        string mime = System.Web.MimeMapping.GetMimeMapping("dummy." + extension);
                        log.Info(String.Format("Adding Mime Record `{0}`", mime));
                        ndef.AddMimeMediaRecord(mime, Encoding.ASCII.GetString(payload));   // This shouldn't be a string here
                        break;
                }
                nfcsvc.WriteNDEFFile(ndef);

                ResetCache();
            }
            catch (COMException ex)
            {
                log.Info("NDEF write error", ex);
            }

            return DokanError.ErrorSuccess;
        }