public override void SetContent(Ndef ndef)
 {
     if (ndef is RtdHandoverSelector)
     {
         SetContent((RtdHandoverSelector)ndef);
     }
 }
Exemplo n.º 2
0
        // Zusätzliche Methode zum Schreiben auf ein NFC-Tag
        public bool WriteToTag(Intent intent, string content)
        {
            // Neue Instanz des NfcAdapters dieses Smartphones
            _nfcAdapter = NfcAdapter.GetDefaultAdapter(this);

            // Eine Instanz des NFC-Tag Objekts anhand der Intent-Daten
            var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

            // Prüfung des Tags == ist es vorhanden?
            if (tag != null)
            {
                Ndef ndef = Ndef.Get(tag);
                if (ndef != null && ndef.IsWritable)
                {
                    var payload     = System.Text.Encoding.ASCII.GetBytes(content);
                    var mimeBytes   = System.Text.Encoding.ASCII.GetBytes("text/plain");
                    var record      = new NdefRecord(NdefRecord.TnfWellKnown, mimeBytes, new byte[0], payload);
                    var ndefMessage = new NdefMessage(new[] { record });

                    ndef.Connect();
                    ndef.WriteNdefMessage(ndefMessage);
                    ndef.Close();
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Make a tag read-only
        /// WARNING: This operation is permanent
        /// </summary>
        /// <param name="ndef"><see cref="Ndef"/></param>
        /// <returns>boolean</returns>
        bool MakeReadOnly(Ndef ndef)
        {
            if (ndef == null)
            {
                return(false);
            }

            var result        = false;
            var newConnection = false;

            if (!ndef.IsConnected)
            {
                newConnection = true;
                ndef.Connect();
            }

            if (ndef.CanMakeReadOnly())
            {
                result = ndef.MakeReadOnly();
            }

            if (newConnection && ndef.IsConnected)
            {
                ndef.Close();
            }

            return(result);
        }
Exemplo n.º 4
0
        /*
         * Este método irá tentar fazer a formatação do atual cartão que esta
         * sendo lido pela leitora.
         *
         * @param ndef = contém as informações do cartão que acabou de ser lido.
         *
         * @exception IOException
         * @exception FormatException
         **/
        private void FormatFromNFC(Ndef ndef)
        {
            bool retorno;

            try
            {
                retorno = nfcLeituraGravacao.FormataCartao(ndef);

                if (retorno)
                {
                    texMensagem.Text = "Cartão formatado";
                }
                else
                {
                    texMensagem.Text = "Nao é necessário formatar este cartão.";
                }
            }
            catch (IOException e)
            {
                Console.WriteLine(e.StackTrace);
            }
            catch (FormatException e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }
Exemplo n.º 5
0
        /**
         * Este método irá apresentar na tela as atuais mensagens cadastadas no cartão
         *
         * @param ndef = contém as informações do cartão que acabou de ser lido.
         *
         * @exception IOException
         * @exception FormatException
         * @exception Exception
         *
         * */
        private void ReadFromNFC(Ndef ndef)
        {
            string mensagem;
            string idCartao;
            long   tempoExecucao;

            try
            {
                // Recebe a leitura das atuais mensagens cadastradas no cartão
                mensagem = nfcLeituraGravacao.RetornaMensagemGravadaCartao(ndef);
                idCartao = nfcLeituraGravacao.IdCartaoHexadecimal();

                // Recebe o tempo total de execução da operação de leitura
                tempoExecucao = nfcLeituraGravacao.RetornaTempoDeExeculcaoSegundos();

                if (mensagem.Equals(""))
                {
                    mTvMessage.Text = "Não existe mensagem gravada no cartão";
                }
                else
                {
                    mTvMessage.Text = "ID Cartão: " + idCartao + "\n" + mensagem +
                                      "\n\nTempo de execução: " + tempoExecucao + " segundos";
                }
            }
            catch (IOException e) {
                Toast.MakeText(Activity, e.Message, ToastLength.Long).Show();
                //Toast.MakeText(this.ApplicationContext, "Tipo de cartão não suportado.", ToastLength.Short).Show();
            }catch (FormatException e) {
                Toast.MakeText(Activity, e.Message, ToastLength.Long).Show();
            }
            catch (Exception e) {
                Toast.MakeText(Activity, e.Message, ToastLength.Long).Show();
            }
        }
Exemplo n.º 6
0
        public void OnTagDiscovered(Tag tag)
        {
            try
            {
                var techs = tag.GetTechList();

                if (!techs.Contains(Java.Lang.Class.FromType(typeof(Ndef)).Name))
                {
                    return;
                }

                var ndef = Ndef.Get(tag);

                ndef.Connect();

                var ndefMessage = ndef.NdefMessage;
                var records     = ndefMessage.GetRecords();

                ndef.Close();

                var nfcTag = new NfcDefTag(ndef, records);

                TagDetected?.Invoke(nfcTag);
            }
            catch (Exception ex)
            {
                // handle errors
            }
        }
        private void ProcessIntent(Intent intent)
        {
            var label = FindViewById <TextView>(Resource.Id.ResultLabel);

            try
            {
                lock (this)
                {
                    nfcTag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
                }

                /*
                 * label.Text =$"Id: 0x{Utils.ByteToHex(nfcTag.GetId())}";
                 * label.Text += $"{newLine}Techs: {newLine}";
                 * label.Text += string.Join(newLine, nfcTag.GetTechList());
                 */

                this.Scan();
            }
            catch (Exception ex)
            {
                label.Text += $"{newLine} Exception: {newLine} {ex.Message} {newLine} {ex.StackTrace}";
            }
            finally
            {
                if (Ndef.Get(nfcTag).IsConnected)
                {
                    Ndef.Get(nfcTag).Close();
                }
            }
        }
Exemplo n.º 8
0
 public NfcDefTag(Ndef tag, IEnumerable <NdefRecord> records)
 {
     IsWriteable = tag.IsWritable;
     Records     = records
                   .Select(r => new AndroidNdefRecord(r))
                   .ToArray();
 }
Exemplo n.º 9
0
 public override void SetContent(Ndef ndef)
 {
     if (ndef is RtdSmartPoster)
     {
         SetContent((RtdSmartPoster)ndef);
     }
 }
Exemplo n.º 10
0
        private bool WriteNFC(Ndef ndef, string mensagem)
        {
            bool retorno = false;

            try
            {
                if (ndef != null)
                {
                    ndef.Connect();
                    NdefRecord mimeRecord = null;

                    Java.Lang.String str = new Java.Lang.String(mensagem);

                    mimeRecord = NdefRecord.CreateMime
                                     ("UTF-8", str.GetBytes(Charset.ForName("UTF-8")));

                    ndef.WriteNdefMessage(new NdefMessage(mimeRecord));
                    ndef.Close();
                    retorno = true;
                }
                else
                {
                    retorno = FormatNFC(ndef);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new System.Exception("Não foi possível ler o cartão.");
            }

            return(retorno);
        }
Exemplo n.º 11
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.");
            }
        }
Exemplo n.º 12
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);
        }
Exemplo n.º 13
0
        private Boolean FormatNFC(Ndef ndef)
        {
            bool retorno = false;

            NdefFormatable ndefFormatable = NdefFormatable.Get(ndef.Tag);

            Java.Lang.String msg = new Java.Lang.String(MENSAGEM_PADRAO);
            try
            {
                if (ndefFormatable == null)
                {
                    return(retorno);
                }

                if (!ndefFormatable.IsConnected)
                {
                    ndefFormatable.Connect();
                }
                ndefFormatable.Format(new NdefMessage(NdefRecord.CreateMime
                                                          ("UTF-8", msg.GetBytes(Charset.ForName("UTF-8")))));
                ndefFormatable.Close();
                retorno = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new System.Exception("Não foi possível ler o cartão.");
            }

            return(retorno);
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
0
 public override void SetContent(Ndef ndef)
 {
     if (ndef is RtdText)
     {
         SetContent((RtdText)ndef);
     }
 }
Exemplo n.º 16
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);
        }
Exemplo n.º 17
0
 public void OnTagDiscovered(Tag tag)
 {
     try
     {
         var ndef = Ndef.Get(tag);
         if (ndef != null)
         {
             //ndef.Type
             //ndef.IsConnected
             //ndef.IsWritable
             var records = new List <NDefRecord>();
             foreach (var record in ndef.NdefMessage.GetRecords())
             {
                 records.Add(new NDefRecord
                 {
                     Identifier = record.GetId(),
                     Uri        = record.ToUri()?.ToString(),
                     //MimeType => this.native.ToMimeType(); // Android only>?
                     Payload     = record.GetPayload(),
                     PayloadType = record.Tnf switch
                     {
                         0x00 => NfcPayloadType.Empty,
                         0x01 => NfcPayloadType.WellKnown,
                         0x02 => NfcPayloadType.Mime,
                         0x03 => NfcPayloadType.Uri,
                         0x04 => NfcPayloadType.External,
                         0x06 => NfcPayloadType.Unchanged,
                         0x05 => NfcPayloadType.Unknown,
                         0x07 => NfcPayloadType.Unknown,
                         _ => NfcPayloadType.Unknown
                     }
                 });
             }
Exemplo n.º 18
0
        private bool TryAndWriteToTag(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)
                {
                    Toast.MakeText(this, "Tag is read-only.", ToastLength.Short).Show();
                }

                // 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)
                {
                    Toast.MakeText(this, "Tag doesn't have enough space.", ToastLength.Short).Show();
                }

                ndef.WriteNdefMessage(ndefMessage);
                //info.Text = ndefMessage.ToString();
                Toast.MakeText(this, "Succesfully wrote tag.", ToastLength.Short).Show();
                return(true);
            }

            return(false);
        }
Exemplo n.º 19
0
 public override void SetContent(Ndef ndef)
 {
     if (ndef is RtdMedia)
     {
         SetContent((RtdMedia)ndef);
     }
 }
        public void ReadFromTag(Tag tag, Intent intent)
        {
            var messages = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);

            Ndef ndef = Ndef.Get(tag);

            try
            {
                ndef.Connect();

                NdefMessage[] ndefMessages = new NdefMessage[messages.Length];
                for (int i = 0; i < messages.Length; i++)
                {
                    ndefMessages[i] = (NdefMessage)messages[i];
                }
                NdefRecord record = ndefMessages[0].GetRecords()[0];

                byte[] payload = record.GetPayload();

                var msg = System.Text.Encoding.UTF8.GetString(payload);
                msg = msg.Remove(0, 3);

                EditText AccNoetxt = FindViewById <EditText>(Resource.Id.AccNoetxt);
                AccNoetxt.Text            = msg;
                PublicVariables.AccountNo = msg;


                ndef.Close();
            }

            catch (Exception e)
            {
                Toast.MakeText(this, "Message: " + e.Message, ToastLength.Long).Show();
            }
        }
Exemplo n.º 21
0
        public NdefMessage Ndef_ReadMessage(Ndef ndf)
        {
            var res = ndf.NdefMessage;

            OnReading_NdefMessage?.Invoke(res);
            return(res);
        }
Exemplo n.º 22
0
        bool TryUpdateTag(Tag tag)
        {
            var ndef = Ndef.Get(tag);

            if (ndef == null || !ndef.IsWritable)
            {
                return(false);
            }

            var mimeBytes = Encoding.Default.GetBytes(ViewApeMimeType);
            var id        = tag.GetId();

            Action(BitConverter.ToString(id).Replace("-", ""), Message);
            return(true);


            //var apeRecord = new NdefRecord(NdefRecord.TnfMimeMedia, mimeBytes, id, Encoding.ASCII.GetBytes(Message));
            //var ndefMessage = new NdefMessage(new[] { apeRecord });

            //if (ndef.MaxSize < ndefMessage.ToByteArray().Length)
            //    return false;

            //if (ndef.IsConnected)
            //    ndef.Close();

            //try
            //{
            //    ndef.Connect();
            //    ndef.WriteNdefMessage(ndefMessage);

            //    Action(new Guid(id), Message);
            //    ndef.Close();
            //    return true;
            //}
            //catch (Java.IO.IOException)
            //{
            //    var format = NdefFormatable.Get(tag);
            //    if (format == null)
            //    {
            //        return false;
            //        //DisplayMessage("Tag does not appear to support NDEF format.");
            //    }
            //    else
            //    {
            //        try
            //        {
            //            format.Connect();
            //            format.Format(ndefMessage);
            //            Action(new Guid(id), Message);
            //            format.Close();
            //            return true;
            //        }
            //        catch (IOException)
            //        {
            //            return false;
            //        }
            //    }
            //}
        }
 public void onNfcDetected(Ndef ndef, string message)
 {
     nfcLeituraGravacao = new NfcLeituraGravacao(ndef.Tag);
     if (WriteToNfc(ndef, message))
     {
         ReadFromNFC(ndef);
     }
 }
Exemplo n.º 24
0
        private void publish(string type, string args)
        {
            string ndefMessage = JsonHelper.Deserialize <string[]>(args)[0];

            NdefRecord[] records = JsonHelper.Deserialize <NdefRecord[]>(ndefMessage);
            byte[]       data    = Ndef.toBytes(records);
            stopPublishing();
            publishedMessageId = proximityDevice.PublishBinaryMessage(type, data.AsBuffer());
        }
Exemplo n.º 25
0
        private void OnWriteTag(Intent intent, string content)
        {
            if (null != content)
            {
                var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

                if (tag != null)
                {
                    Ndef ndef = Ndef.Get(tag);

                    if (ndef != null && ndef.IsWritable)
                    {
                        var payload     = Encoding.ASCII.GetBytes(content);
                        var mimeBytes   = Encoding.ASCII.GetBytes("text/plain");
                        var record      = new NdefRecord(NdefRecord.TnfWellKnown, mimeBytes, new byte[0], payload);
                        var ndefMessage = new NdefMessage(new[] { record });

                        ndef.Connect();
                        ndef.WriteNdefMessage(ndefMessage);
                        ndef.Close();
                    }
                    else
                    {
                        NdefFormatable ndefFormatable = NdefFormatable.Get(tag);

                        if (ndefFormatable != null)
                        {
                            try
                            {
                                var payload     = Encoding.ASCII.GetBytes(content);
                                var mimeBytes   = Encoding.ASCII.GetBytes("text/plain");
                                var record      = new NdefRecord(NdefRecord.TnfWellKnown, mimeBytes, new byte[0], payload);
                                var ndefMessage = new NdefMessage(new[] { record });

                                ndefFormatable.Connect();
                                ndefFormatable.Format(ndefMessage);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                            finally
                            {
                                try
                                {
                                    ndefFormatable.Close();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 26
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;
 }
Exemplo n.º 27
0
        public WriteResponse WriteTag(NdefMessage message, Tag tag)
        {
            int    size = message.ToByteArray().Length;
            string mess = "";

            try {
                Ndef ndef = Ndef.Get(tag);
                if (ndef != null)
                {
                    ndef.Connect();

                    if (!ndef.IsWritable)
                    {
                        return(new WriteResponse(0, "Tag is read-only"));
                    }
                    if (ndef.MaxSize < size)
                    {
                        mess = "Tag capacity is " + ndef.MaxSize + " bytes, message is " + size
                               + " bytes.";
                        return(new WriteResponse(0, mess));
                    }

                    ndef.WriteNdefMessage(message);
                    if (writeProtect)
                    {
                        ndef.MakeReadOnly();
                    }
                    mess = "Wrote message to pre-formatted tag.";
                    return(new WriteResponse(1, mess));
                }
                else
                {
                    NdefFormatable format = NdefFormatable.Get(tag);
                    if (format != null)
                    {
                        try {
                            format.Connect();
                            format.Format(message);
                            mess = "Formatted tag and wrote message";
                            return(new WriteResponse(1, mess));
                        } catch (IOException) {
                            mess = "Failed to format tag.";
                            return(new WriteResponse(0, mess));
                        }
                    }
                    else
                    {
                        mess = "Tag doesn't support NDEF.";
                        return(new WriteResponse(0, mess));
                    }
                }
            } catch (Exception) {
                mess = "Failed to write tag";
                return(new WriteResponse(0, mess));
            }
        }
Exemplo n.º 28
0
        private void ManageCleanOperation()
        {
            //TODO 3. WRITING CARD 5
            Ndef          ndef   = null;
            NfcNdefRecord record = null;

            try
            {
                ndef = Ndef.Get(currentTag);
                if (!CheckWriteOperation(ndef, record))
                {
                    OnNfcTagCleaned?.Invoke(this, false);
                    return;
                }

                ndef.Connect();

                byte[]      empty   = Array.Empty <byte>();
                NdefMessage message = new NdefMessage(new NdefRecord[1] {
                    new NdefRecord(NdefRecord.TnfEmpty, empty, empty, empty)
                });

                ndef.WriteNdefMessage(message);
                OnNfcTagCleaned?.Invoke(this, true);
                return;
            }
            catch (Android.Nfc.TagLostException tlex)
            {
                Debug.WriteLine($"Tag Lost Error: {tlex.Message}");
            }
            catch (Java.IO.IOException ioex)
            {
                Debug.WriteLine($"Tag IO Error: {ioex.Message}");
            }
            catch (Android.Nfc.FormatException fe)
            {
                Debug.WriteLine($"Tag Format Error: {fe.Message}");
            }
            catch
            {
                Debug.WriteLine($"Tag Error");
            }
            finally
            {
                if (ndef?.IsConnected == true)
                {
                    ndef.Close();
                }

                currentTag    = null;
                currentIntent = null;
            }

            OnNfcTagCleaned?.Invoke(this, false);
        }
Exemplo n.º 29
0
        public void SetNdef(Ndef ndef)
        {
            /* Display the NDEF as raw data in the hexBox */
            /* ------------------------------------------ */

            Trace.WriteLine("SetNdef");

            byte[] b = ndef.GetBytes();
            DynamicByteProvider p = new DynamicByteProvider(b);

            hexBox.ByteProvider = p;

            /* Try to recognize the NDEF, to display it in a user-friendly control */
            /* ------------------------------------------------------------------- */

            RtdControl control = null;

            if (ndef is RtdSmartPoster)
            {
                lbDecodedType.Text = "SmartPoster";
                control            = new RtdSmartPosterControl();
                control.SetContent(ndef);
            }
            else if (ndef is RtdUri)
            {
                lbDecodedType.Text = "URI";
                control            = new RtdUriControl();
                control.SetContent(ndef);
            }
            else if (ndef is RtdText)
            {
                lbDecodedType.Text = "Text";
                control            = new RtdControl();
                control.SetContent(ndef);
            }
            else if (ndef is RtdVCard)
            {
                lbDecodedType.Text = "VCard";
                control            = new RtdVCardControl();
                control.SetContent(ndef);
            }
            else if (ndef is RtdMedia)
            {
                lbDecodedType.Text = "Media (MIME)";
                control            = new RtdMediaControl();
                control.SetContent(ndef);
            }

            if (control != null)
            {
                pDecoded.Controls.Clear();
                control.Dock = DockStyle.Fill;
                pDecoded.Controls.Add(control);
            }
        }
        private bool isNDEFTag(Tag tag)
        {
            bool returnVar = false;
            Ndef lNdefTag  = Ndef.Get(tag);

            if (lNdefTag != null)
            {
                returnVar = true;
            }
            return(returnVar);
        }