Esempio n. 1
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.");
            }
        }
Esempio n. 2
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);
        }
Esempio n. 3
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);
        }
Esempio n. 4
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);
        }
Esempio n. 5
0
 /// <inheritdoc/>
 public AndroidTag(Tag @base, NdefMessage message)
 {
     Records = message.GetRecords().Select(x => new NfcDefRecord()
     {
         Payload = x.GetPayload(), TypeNameFormat = AndroidNfc.GetTypeNameFormat(x.Tnf)
     }).ToArray();
     _ndef = Ndef.Get(@base);
     _base = @base;
 }
Esempio n. 6
0
        /// <summary>
        /// Accepts data from an NFC touch and performs a search for any printers with matching information.
        /// </summary>
        /// <param name="intent"> intent that contains NFC payload data </param>
        private void ProcessNfcScan(Intent intent)
        {
            IParcelable[] scannedTags = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
            if (scannedTags != null && scannedTags.Length > 0)
            {
                try
                {
                    NdefMessage msg          = (NdefMessage)scannedTags[0];
                    byte[]      payloadBytes = msg.GetRecords()[0].GetPayload();
                    String      payload      = String.Empty;
                    foreach (byte b in payloadBytes)
                    {
                        payload += Convert.ToChar(b);
                    }
                    string friendlyName = GetDeviceFriendlyName(payload);
                    string macAddress   = GetDeviceMacAddress(payloadBytes);
                    if (IsDevicePaired(friendlyName))
                    {
                        ShowAlreadyPaired(friendlyName);
                    }
                    else
                    {
                        StartSearching(friendlyName);
                        Activity.RunOnUiThread(() =>
                        {
                            try
                            {
                                if (_activity.Bluetooth.Adapter == null)
                                {
                                    throw new Exception("No Bluetooth adapter found.");
                                }

                                if (!_activity.Bluetooth.Adapter.IsEnabled)
                                {
                                    throw new Exception("Bluetooth adapter is not enabled.");
                                }

                                PairDevice(friendlyName, macAddress);
                            }
                            catch (DiscoveryException e)
                            {
                                Console.WriteLine(e.ToString());
                                Console.Write(e.StackTrace);
                            }
                            finally
                            {
                            }
                        });
                    }
                }
                catch (Exception ex)
                {
                }

                intent.RemoveExtra(NfcAdapter.ExtraNdefMessages);
            }
        }
Esempio n. 7
0
        private string GetDataStoredOnTag(NdefMessage message)
        {
            var result  = "";
            var payload = message.GetRecords()[0].GetPayload();

            payload.ForEach(b => { result += (char)b; });

            return(result);
        }
Esempio n. 8
0
        void ProcessIntent(Intent intent)
        {
            IParcelable [] rawMsgs = intent.GetParcelableArrayExtra(
                NfcAdapter.ExtraNdefMessages);
            // only one message sent during the beam
            NdefMessage msg = (NdefMessage)rawMsgs [0];

            // record 0 contains the MIME type, record 1 is the AAR, if present
            mInfoText.Text = Encoding.UTF8.GetString(msg.GetRecords() [0].GetPayload());
        }
Esempio n. 9
0
        public void OnNewIntent(object sender, Intent e)
        {
            IParcelable[] tags = e.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
            if (tags?.Length > 0)
            {
                NdefMessage message = (NdefMessage)tags[0];
                string      nfcData = Encoding.UTF8.GetString(message.GetRecords()[0].GetPayload());

                TagScanned?.Invoke(this, nfcData);
            }
        }
        void ProcessIntent(Intent intent)
        {
            IParcelable[] rawMsgs = intent.GetParcelableArrayExtra(                     //WHERE SENT TEXT IS RECEIVED
                NfcAdapter.ExtraNdefMessages);
            // only one message sent during the beam
            NdefMessage msg = (NdefMessage)rawMsgs[0];
            // record 0 contains the MIME type, record 1 is the AAR, if present
            string message = Encoding.UTF8.GetString(msg.GetRecords()[0].GetPayload());     //WHAT TO DO WITH SENT DATA

            MakePayment(message);
        }
Esempio n. 11
0
        void ProcessIntent(Intent intent)
        {
            IParcelable[] rawMsg   = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
            NdefMessage   msg      = (NdefMessage)rawMsg[0];
            string        datagram = Encoding.UTF8.GetString(msg.GetRecords()[0].GetPayload());

            contactName = datagram.Split(',')[0];

            Padbook friendBook = pm.GetPadbookForUsername(contactName);

            friendBook.AppendPads(datagram.Split(',')[1].Split('#')); // keys are seperated with a hash
        }
Esempio n. 12
0
 void ProcessIntent(Intent intent)
 {
     try
     {
         IParcelable[] rawMsgs = intent.GetParcelableArrayExtra(
             NfcAdapter.ExtraNdefMessages);
         // only one message sent during the beam
         NdefMessage msg = (NdefMessage)rawMsgs[0];
         // record 0 contains the MIME type, record 1 is the AAR, if present
         Global.ReadMessage = Encoding.UTF8.GetString(msg.GetRecords()[0].GetPayload());
     }
     catch (Exception exc)
     {
         Helpers.LoggerHelper.LogException(exc);
     }
 }
Esempio n. 13
0
        private static Intent ProcessNfcScan(Intent intent)
        {
            IParcelable[] scannedTags = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
            if (scannedTags != null && scannedTags.Length > 0)
            {
                try
                {
                    NdefMessage msg          = (NdefMessage)scannedTags[0];
                    byte[]      payloadBytes = msg.GetRecords()[0].GetPayload();
                    String      payload      = String.Empty;
                    foreach (byte b in payloadBytes)
                    {
                        payload += Convert.ToChar(b);
                    }
                    NFCDevice nfcDevice = new NFCDevice
                    {
                        FriendlyName = GetDeviceFriendlyName(payload),
                        MacAddress   = GetDeviceMacAddress(payloadBytes),
                    };
                    bool alreadyPaired = false;
                    for (int i = 0; i < _deviceList.Count; i++)
                    {
                        if ((_deviceList[i].Name == nfcDevice.FriendlyName) && (_deviceList[i].Address == nfcDevice.MacAddress))
                        {
                            alreadyPaired = true;
                            break;
                        }
                    }
                    if (!alreadyPaired)
                    {
                        intent = PairDevice(nfcDevice, intent);
                    }
                    else
                    {
                        intent.PutExtra("ErrorMessage", "Device Already Paired");
                    }
                }
                catch (Exception ex)
                {
                }

                intent.RemoveExtra(NfcAdapter.ExtraNdefMessages);
            }

            return(intent);
        }
        /**
         *
         * Método faz a gravação de uma nova mensagem no cartão.
         *
         * Essa nova mensagem será códificada usando o padrão UTF-8.
         *
         * @param ndef = Contém as informações do cartão que esta sendo lido.
         *
         * @throws IOException
         * @throws FormatException
         *
         * @return String = contém a mensagem que esta gravada no cartão
         *
         * */
        public string RetornaMensagemGravadaCartao(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());
                    Console.WriteLine(message);
                }
            }
            catch (IOException e)
            {
                throw new System.Exception(e.Message);
            }
            catch (System.FormatException e)
            {
                throw new System.Exception(e.Message);
            }
            catch (System.Exception e)
            {
                throw new System.Exception(e.Message);
            }
            finally
            {
                GravaTempoFinal();
            }
            return(message);
        }
Esempio n. 15
0
 protected void HandleNFC(Intent intent, Boolean inForeground)
 {
     IParcelable[] scannedTags = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
     if (scannedTags != null && scannedTags.Length > 0)
     {
         NdefMessage msg          = (NdefMessage)scannedTags[0];
         byte[]      payloadBytes = msg.GetRecords()[0].GetPayload();
         String      payload      = String.Empty;
         foreach (byte b in payloadBytes)
         {
             payload += Convert.ToChar(b);
         }
     }
     else
     {
         DisplayMessage("No message");
     }
 }
        public static string GetNdefData(Intent intent)
        {
            string result = default(string);

            if (intent.Action == NfcAdapter.ActionNdefDiscovered)
            {
                NdefMessage msg     = (NdefMessage)intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages)[0];
                byte[]      payload = msg.GetRecords()[0].GetPayload();

                result = System.Text.Encoding.UTF8.GetString(payload);

                var endIndex = result.IndexOf("en");
                if (endIndex >= 0)
                {
                    result = result.Remove(0, endIndex + 2);
                }
            }
            return(result);
        }
Esempio n. 17
0
        private void ProcessIntent(Intent intent)
        {
            IParcelable[] rawMsgs = Intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
            // only one message sent during the beam
            NdefMessage msg = (NdefMessage)rawMsgs[0];

            // record 0 contains the MIME type, record 1 is the AAR, if present
            AlarmPage.record = Encoding.UTF8.GetString(msg.GetRecords()[0].GetPayload());
            //string msg_typ = msg.GetType().ToString();
            //string rec_typ = msg.GetRecords()[0].GetType().ToString();
            //byte[] rec_typinfo = msg.GetRecords()[0].GetTypeInfo();
            //byte[] rec_id = msg.GetRecords()[0].GetId();
            //byte[] rec_daten = (byte[])msg.GetRecords()[0];
            //byte[] rec_nutzdaten = msg.GetRecords()[0].GetPayload();
            //cList.Clear();
            //cList.Add(ByteArrayToText(rec_daten));
            //ListAdapter = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleListItem1, cList);
            //cListView.Adapter = ListAdapter;
        }
Esempio n. 18
0
        protected override void OnNewIntent(Intent intent) //When a new NFC tag is discovered
        {
            try
            {
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

                IParcelable[] rawMsgs = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
                if (rawMsgs != null)
                {
                    NdefMessage  message = (NdefMessage)rawMsgs[0];
                    NdefRecord[] records = message.GetRecords();
                    if (records != null)
                    {
                        if (MainPage.currentPage == "Read From Node")       //If current page is read page
                        {
                            ReadNFC.DisplayValues(records[0].GetPayload()); //Encrypt nonce and create reply
                        }
                        else //If current page is write page
                        {
                            Ndef ndef = Ndef.Get(tag);
                            ndef.Connect();

                            byte[] bytes = WriteNFC.CreateRequest();

                            NdefRecord  newRecord  = new NdefRecord(NdefRecord.TnfUnknown, new byte[0], new byte[0], bytes);
                            NdefMessage newMessage = new NdefMessage(new NdefRecord[] { newRecord });
                            ndef.WriteNdefMessage(newMessage);
                            ndef.Close();
                            Toast.MakeText(ApplicationContext, "Write Succesful", ToastLength.Long).Show();
                        }
                    }
                }
                else
                {
                    Toast.MakeText(ApplicationContext, "The Tag did not contain a message.", ToastLength.Long).Show();
                }
            }
            catch
            {
                Toast.MakeText(ApplicationContext, "Something went wrong, please try again.", ToastLength.Long).Show();
            }
        }
        public static CardboardDeviceParams createFromNfcContents(NdefMessage tagContents)
        {
            if (tagContents == null)
            {
                Log.Warn("CardboardDeviceParams", "Could not get contents from NFC tag.");
                return(null);
            }

            CardboardDeviceParams deviceParams = new CardboardDeviceParams();

            foreach (NdefRecord record in tagContents.GetRecords())
            {
                if (deviceParams.parseNfcUri(record))
                {
                    break;
                }
            }

            return(deviceParams);
        }
Esempio n. 20
0
        private void ReadNfcTag(Intent intent)
        {
            // Find first NDEF message
            var parcellableNdefMessages = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);

            NdefMessage ndefMessage = null;

            if (parcellableNdefMessages != null && parcellableNdefMessages.Length > 0)
            {
                ndefMessage = parcellableNdefMessages[0] as NdefMessage;
                LogMessage("NDEF formatted NFC Tag discovered.");
            }
            else
            {
                LogMessage("Error: Tag is not NDEF formatted. This is unexpected.");
                return;
            }

            // Find first record in NDEF message
            NdefRecord ndefRecord  = null;
            var        ndefRecords = ndefMessage.GetRecords();

            if (ndefRecords != null && ndefRecords.Length > 0)
            {
                LogMessage("Using first NDEF record.");
                ndefRecord = ndefRecords[0];
            }
            else
            {
                LogMessage("Error: No records found in NDEF Message.");
                return;
            }

            // Log Uri to output
            LogMessage(String.Format("TAG Uri: {0}\n", ndefRecord.ToUri()));


            //var openUriIntent = new Intent(Android.Content.Intent.ActionView, ndefRecord.ToUri());
            //StartActivity(openUriIntent);
        }
Esempio n. 21
0
        private NfcTagInfo GetNfcTagInfo(Tag tag)
        {
            if (tag == null)
            {
                return(null);
            }

            Ndef       ndef = Ndef.Get(tag);
            NfcTagInfo nTag = new NfcTagInfo();

            if (ndef != null)
            {
                if (ndef.CachedNdefMessage != null)
                {
                    NdefMessage ndefMessage = ndef.CachedNdefMessage; //TODO 2. READING CARD 6 ndef.NdefMessage -> TagLost
                    var         records     = ndefMessage.GetRecords();
                    nTag.Records = GetRecords(records);
                }
            }

            return(nTag);
        }
Esempio n. 22
0
        internal SmartPoster Parse(NdefRecord record)
        {
            /*
             *
             *        Preconditions.checkArgument(record.getTnf() == NdefRecord.TNF_WELL_KNOWN);
             * Preconditions.checkArgument(Arrays.equals(record.getType(), NdefRecord.RTD_SMART_POSTER));
             * try {
             * NdefMessage subRecords = new NdefMessage(record.getPayload());
             * return parse(subRecords.getRecords());
             * } catch (FormatException e) {
             * throw new IllegalArgumentException(e);
             * }
             */
            Preconditions.CheckArgument(record.Tnf == NdefRecord.TnfWellKnown);
            //Preconditions.CheckArgument(Arrays.Equals(record.GetTypeInfo(), NdefRecord.RtdSmartPoster));
            if (record.GetTypeInfo()[0] != NdefRecord.RtdSmartPoster[0])
            {
                throw new Exception();
            }
            NdefMessage subRecords = new NdefMessage(record.GetPayload());

            return(Parse(subRecords.GetRecords()));
        }
Esempio n. 23
0
        protected override void OnNewIntent(Intent intent)
        {
            //base.OnNewIntent(intent);
            // CrossNFC.OnNewIntent(intent);

            string manuf        = "";
            string data         = "";
            string serialNumber = "";

            TagRead tagRead = new TagRead();


            if (intent.Action == NfcAdapter.ActionTagDiscovered)
            {
                List <string> tags        = new List <string>();
                NdefMessage   ndefMessage = null;

                var id = intent.GetByteArrayExtra(NfcAdapter.ExtraId);

                if (id != null)
                {
                    serialNumber = NFCUtils.ByteArrayToHexString(id, ":");

                    /*for (int ii = 0; ii < id.Length; ii++)
                     * {
                     *  if (!string.IsNullOrEmpty(data))
                     *      serialNumber += "-";
                     *  serialNumber += id[ii].ToString("X2");
                     * }*/
                    tagRead.SerialNumber = serialNumber;
                    tags.Add(serialNumber);
                }
                else
                {
                    tags.Add(null);
                }

                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
                if (tag != null)
                {
                    manuf = NFCHelpers.GetManufacturer(tag);
                    tags.Add(manuf);
                    tagRead.Model = manuf;

                    if (NFCHelpers.IsNDEFTag(tag))
                    {
                        var ndef = Ndef.Get(tag);

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

                            if (ndefMessage != null)
                            {
                                NdefRecord[] records     = ndefMessage.GetRecords();
                                var          ndefrecords = NFCHelpers.GetRecords(records);
                                for (var i = 0; i < ndefrecords.Count; i++)
                                {
                                    if (data != "")
                                    {
                                        data += "\n";
                                    }
                                    data += ndefrecords[i];
                                }
                                tags.Add(data);
                                tagRead.Data = data;
                            }
                        }
                    }

/*
 *                  var rawTagMessages = intent.GetParcelableArrayExtra(NfcAdapter.ExtraTag);
 *
 *                  // First get all the NdefMessage
 *                  var rawMessages = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
 *                  if (rawMessages != null)
 *                  {
 *
 *                      // https://medium.com/@ssaurel/create-a-nfc-reader-application-for-android-74cf24f38a6f
 *
 *                      foreach (var message in rawMessages)
 *                      {
 *
 *                          foreach (var r in NdefMessageParser.GetInstance().Parse((NdefMessage)message))
 *                          {
 *                              System.Diagnostics.Debug.WriteLine("TAG: " + r.Str());
 *                              tags.Add(r.Str());
 *                          }
 *
 *                      }
 *                  }*/
                }

                MessagingCenter.Send <App, TagRead>((App)Xamarin.Forms.Application.Current, "Tag", tagRead);
            }
            else if (intent.Action == NfcAdapter.ActionNdefDiscovered)
            {
                System.Diagnostics.Debug.WriteLine("ActionNdefDiscovered");
            }
        }
Esempio n. 24
0
 public List <IParsedNdefRecord> Parse(NdefMessage message)
 {
     return(GetRecords(message.GetRecords()));
 }