Пример #1
0
        /// <inheritdoc/>
        public bool Write(params NfcDefRecord[] records)
        {
            var message = new NdefMessage(records.Select(x =>
                                                         new NdefRecord(AndroidNfc.GetTypeNameFormat(x.TypeNameFormat), null, null, x.Payload)).ToArray());

            if (_ndef != null)
            {
                if (!Writable)
                {
                    return(false);
                }
                _ndef.Connect();
                // NFC tags can only store a small amount of data, this depends on the type of tag its.
                var size = message.ToByteArray().Length;
                if (_ndef.MaxSize < size)
                {
                    throw new InvalidOperationException("Not enough space on NFC tag");
                }

                _ndef.WriteNdefMessage(message);
                return(true);
            }

            var format = NdefFormatable.Get(_base);

            format.Connect();
            format.Format(message);
            return(true);
        }
Пример #2
0
        private bool TryAndFormatTagWithMessage(Tag tag, NdefMessage ndefMessage)
        {
            var format = NdefFormatable.Get(tag);

            if (format == null)
            {
                Toast.MakeText(this, "Tag does not appear to support NDEF format.", ToastLength.Short).Show();
            }
            else
            {
                try
                {
                    format.Connect();
                    format.Format(ndefMessage);
                    Toast.MakeText(this, "Tag successfully written.", ToastLength.Short).Show();
                    return(true);
                }
                catch (Exception ioex)
                {
                    var msg = "There was an error trying to format the tag: ";
                    Toast.MakeText(this, msg + ioex, ToastLength.Short).Show();
                }
            }
            return(false);
        }
        /// <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);
        }
Пример #4
0
        /*
         * Method Name: FormatCard
         * Purpose: To format the card to be able to be written to
         */
        private async Task FormatCard(Tag cardTag, NdefMessage cardContent)
        {
            try
            {
                var formatter = NdefFormatable.Get(cardTag);
                if (formatter == null)
                {
                    AlertBoxComponent cardFullAlertBox = new AlertBoxComponent(_context);
                    cardFullAlertBox.Setup("Incorrect Card Type", "This card does not support Ndef format. Please use a different card.");
                    cardFullAlertBox.Show();
                }
                await formatter.ConnectAsync();

                await formatter.FormatAsync(cardContent);

                formatter.Close();

                AlertBoxComponent writeSuccessfulAlertBox = new AlertBoxComponent(_context);
                writeSuccessfulAlertBox.MenuOptionSetup("Card Write Was Successful", "The card was successfully written to. You will now be taken back to the main menu.", _context, _activity);
                writeSuccessfulAlertBox.Show();
            }
            catch (Exception e)
            {
                AlertBoxComponent cardFullAlertBox = new AlertBoxComponent(_context);
                string            alertMessage     = "An error has occured. Please try again.Error: " + e;
                cardFullAlertBox.Setup("Error Writing To Card", alertMessage);
                cardFullAlertBox.Show();
            }
        }
Пример #5
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);
        }
Пример #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 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);
        }
Пример #8
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);
        }
Пример #9
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);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #10
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));
            }
        }
Пример #11
0
        public override WriteResult WriteTag(NdefMessage message, Tag tag)
        {
            if (tag == null)
            {
                return(WriteResult.NULL);
            }

            try
            {
                var ndefTag = Ndef.Get(tag);
                if (ndefTag == null)
                {
                    NdefFormatable nForm = NdefFormatable.Get(tag);
                    if (nForm != null)
                    {
                        try
                        {
                            nForm.Connect();
                            nForm.Format(message);
                            nForm.Close();
                            return(WriteResult.OK);
                        } catch { return(WriteResult.FORMATFAILED); }
                    }
                    return(WriteResult.NOTSUPPORTED);
                }
                else
                {
                    ndefTag.Connect();
                    if (ndefTag.MaxSize < message.ToByteArray().Length)
                    {
                        return(WriteResult.TOOLARGE);
                    }
                    if (ndefTag.IsWritable)
                    {
                        ndefTag.WriteNdefMessage(message);
                        ndefTag.Close();
                        return(WriteResult.OK);
                    }
                    return(WriteResult.READONLY);
                }
            }
            catch { return(WriteResult.FAILED); }
        }
Пример #12
0
        public NFCMessage NdefFormatable_FormatTag(Tag tag)
        {
            if (!tag.GetTechList().Contains(Tech_NdefFormatable))
            {
                return(NFCMessage.NFC_UN_FORMATABLE_TAG);
            }
            NdefFormatable ndefFormatable = NdefFormatable.Get(tag);

            if (ndefFormatable == null)
            {
                return(NFCMessage.NFC_CANT_FORMAT);
            }
            ndefFormatable.Connect();
            NdefRecord  record  = NdefRecord.CreateMime("text/plain", Encoding.ASCII.GetBytes("New"));
            NdefMessage message = new NdefMessage(new NdefRecord[] { record });

            ndefFormatable.Format(message);
            ndefFormatable.Close();
            OnFormatting_NdefTag?.Invoke();
            return(NFCMessage.NFC_TAG_FORMATED);
        }
        /**
         *
         * Método faz a formatação do cartão.
         *
         * A formatação do cartão só é necessario na sua primeira gravação.
         *
         * Após já existir algum valor gravado no cartão, não será possível formata-lo
         * novamente.
         *
         * @param ndef = Contém as informações do cartão que esta sendo lido.
         *
         * @throws IOException
         * @throws FormatException
         *
         * @return boolean =>  True = Cartão Formatado / False = Cartão não formatado
         *
         * */
        public bool FormataCartao(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 (IOException e)
            {
                throw new IOException(e.Message);
            }
            catch (System.FormatException e)
            {
                throw new System.FormatException(e.Message);
            }
            finally
            {
                this.GravaTempoFinal();
            }


            return(retorno);
        }
Пример #14
0
 public (TagInfo?, NFCMessage) ReadInfo(Tag tag)
 {
     if (tag == null)
     {
         return(null, NFCMessage.NFC_NULL_TAG);
     }
     return(new TagInfo
     {
         Uid = tag.GetId(),
         Tag = tag,
         IsoDep = IsoDep.Get(tag),
         MifareClassic = MifareClassic.Get(tag),
         MifareUltralight = MifareUltralight.Get(tag),
         NfcV = NfcV.Get(tag),
         Ndef = Ndef.Get(tag),
         NdefFormatable = NdefFormatable.Get(tag),
         NfcA = NfcA.Get(tag),
         NfcB = NfcB.Get(tag),
         NfcF = NfcF.Get(tag),
         NfcBarcode = NfcBarcode.Get(tag),
         TechList = tag.GetTechList()
     }, NFCMessage.NFC_NO_ERROR);
 }
Пример #15
0
        private bool TryAndFormatTagWithMessage(Tag tag, NdefMessage ndefMessage)
        {
            var format = NdefFormatable.Get(tag);

            if (format == null)
            {
                _alertMessage.Text = "Tag does not appear to support NDEF format.";
            }
            else
            {
                try
                {
                    format.Connect();
                    format.Format(ndefMessage);
                    _alertMessage.Text = "Tag successfully written.";
                    return(true);
                }
                catch (IOException ioex)
                {
                    _alertMessage.Text = "There was an error trying to format the tag: " + ioex.Message;
                }
            }
            return(false);
        }
Пример #16
0
        protected override void OnNewIntent(Intent intent)
        {
            base.OnNewIntent(intent);
            Toast.MakeText(this, "Leyendo NFC", ToastLength.Short).Show();
            var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

            /*if (_inWriteMode)
             * {
             *  _inWriteMode = false;
             *
             *  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("YeeSaurio");
             *  var mimeBytes = Encoding.ASCII.GetBytes("application/NFCFighters");
             *  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);
             *  }
             * }
             *
             * /*string[] techList = tag.GetTechList();
             * info.Text = "";
             * foreach (string tech in techList)
             * {
             *  info.Text += "\n\t" + tech;
             * }*/

            NfcA             nfca  = NfcA.Get(tag);
            NdefFormatable   ndeff = NdefFormatable.Get(tag);
            IsoDep           iso   = IsoDep.Get(tag);
            MifareUltralight mifU  = MifareUltralight.Get(tag);


            /*try
             * {
             *  nfca.Connect();
             *  short s = nfca.Sak;
             *  byte[] a = nfca.GetAtqa();
             *  string atqa = Encoding.ASCII.GetString(a);
             *  info.Text += "\nSAK = " + s + "\nATQA = " + atqa;
             *  nfca.Close();
             * } catch (Exception e)
             * {
             *  Toast.MakeText(this, "NfcA" + e.Message, ToastLength.Short).Show();
             * }*/

            /*try
             * {
             *  iso.Connect();
             *
             *  iso.Close();
             * }
             * catch (Exception e)
             * {
             *  Toast.MakeText(this, "IsoDep" + e.Message, ToastLength.Short).Show();
             * }*/

            /*try
             * {
             *  ndeff.Connect();
             *  //info.Text += "\nType: " + ndeff.GetType();
             *  //info.Text += "\nConnected: " + ndeff.IsConnected;
             *  var rawMsgs = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);
             *  var msg = (NdefMessage)rawMsgs[0];
             *  var record = msg.GetRecords()[0];
             *
             *  info.Text += "\n\tNdefFormatted: " + Encoding.ASCII.GetString(record.GetPayload());
             *  ndeff.Close();
             * }
             * catch (Exception e)
             * {
             *  Toast.MakeText(this, "NdefFormatted " + e.Message, ToastLength.Short).Show();
             * }*/

            try
            {
                mifU.Connect();
                byte[]        mPag      = mifU.ReadPages(12);
                StringBuilder aux       = new StringBuilder();
                String        cont_mpag = "";
                for (int i = 0; i < mPag.Length; i++)
                {
                    aux.Append(mPag[i]);
                }
                cont_mpag = aux.ToString();
                //info.Text = Charset.AvailableCharsets().ToString();
                //var mifM = new String(cont_mpag, Charset.ForName("US-ASCII"));
                string mifM = Encoding.ASCII.GetString(mPag);
                info.Text += "\nTu personaje es " + mifM;
                mifU.Close();
            }
            catch (Exception e)
            {
                //Toast.MakeText(this, "MifareUltralight" + e.Message, ToastLength.Short).Show();
            }
        }