public override void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
        {
            var results = new List <string>();

            foreach (var message in messages)
            {
                foreach (var record in message.Records)
                {
                    try
                    {
                        results.Add(new NSString(record.Payload, NSStringEncoding.UTF8));
                    }
                    catch { }
                }
            }

            foreach (var result in results)
            {
                var matches = _otpPattern.Matches(result);
                if (matches.Count > 0 && matches[0].Groups.Count > 1)
                {
                    var otp = matches[0].Groups[1].ToString();
                    _callback.Invoke(true, otp);
                    return;
                }
            }

            _callback.Invoke(false, "No tags were read.");
        }
Example #2
0
        public static void SubscribeBroadcastReceiver(UIViewController controller, NFCNdefReaderSession nfcSession,
                                                      NFCReaderDelegate nfcDelegate)
        {
            var broadcasterService  = ServiceContainer.Resolve <IBroadcasterService>("broadcasterService");
            var messagingService    = ServiceContainer.Resolve <IMessagingService>("messagingService");
            var deviceActionService = ServiceContainer.Resolve <IDeviceActionService>("deviceActionService");

            broadcasterService.Subscribe(nameof(controller), (message) =>
            {
                if (message.Command == "showDialog")
                {
                    var details     = message.Data as DialogDetails;
                    var confirmText = string.IsNullOrWhiteSpace(details.ConfirmText) ?
                                      AppResources.Ok : details.ConfirmText;

                    NSRunLoop.Main.BeginInvokeOnMainThread(async() =>
                    {
                        var result = await deviceActionService.DisplayAlertAsync(details.Title, details.Text,
                                                                                 details.CancelText, confirmText);
                        var confirmed = result == details.ConfirmText;
                        messagingService.Send("showDialogResolve", new Tuple <int, bool>(details.DialogId, confirmed));
                    });
                }
                else if (message.Command == "listenYubiKeyOTP")
                {
                    ListenYubiKey((bool)message.Data, deviceActionService, nfcSession, nfcDelegate);
                }
            });
        }
Example #3
0
        public override void DidDetectTags(NFCNdefReaderSession session, INFCNdefTag[] tags)
        {
            try
            {
                var nFCNdefTag = tags[0];
                session.ConnectToTag(nFCNdefTag, CompletionHandler);
                string         dominio        = "http://boxweb.azurewebsites.net/";
                string         user           = MainViewModel.GetInstance().User.UserId.ToString();
                string         tag_id         = "";
                string         url            = dominio + "index3.aspx?user_id=" + user + "&tag_id=" + tag_id;
                NFCNdefPayload payload        = NFCNdefPayload.CreateWellKnownTypePayload(url);
                NFCNdefMessage nFCNdefMessage = new NFCNdefMessage(new NFCNdefPayload[] { payload });
                nFCNdefTag.WriteNdef(nFCNdefMessage, delegate
                {
                    session.InvalidateSession();
                });
                //Task task = App.DisplayAlertAsync(user_id_tag);

                //AppDelegate.user_id_tag = "?";
                //PopupNavigation.Instance.PopAsync();


                //session.InvalidateSession();
                //session.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                session.Dispose();
                session.InvalidateSession();
            }

            MainViewModel.GetInstance().Home = new HomeViewModel();
            Xamarin.Forms.Application.Current.MainPage = new MasterPage();
        }
Example #4
0
 public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
 {
     int user_id = 0;            
     try
     {                                
         if (messages != null && messages.Length > 0)
         {
             var first = messages[0];
             string messa = GetRecords(first.Records);
             string[] variables = messa.Split('=');
             string[] depura_userid = variables[1].Split('&');
             string tag_id = variables[2];
             user_id = Convert.ToInt32(depura_userid[0]);
             //if (write_tag.modo_escritura == false) { Imprime_box.Consulta_user(user_id.ToString(), tag_id); }                    
             Imprime_box.Consulta_user(user_id.ToString(), tag_id);
         }                
     }
     catch (Exception e) 
     {
         Console.WriteLine(e);
     }            
      
     //user_id_tag = user_id.ToString();
     //if (write_tag.modo_escritura == true)
     //{
     //    session.InvalidateSession();
     //    session.Dispose();
     //    Thread.Sleep(7000);
     //    write_tag.modo_escritura = false;
     //    write_tag myobject = new write_tag();
     //    myobject.ScanWriteAsync();
     //}
     session.InvalidateSession();           
     Session.InvalidateSession();
 }        
Example #5
0
 public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
 {
     foreach (var msg in messages)
     {
         Console.WriteLine(msg);
     }
 }
Example #6
0
        public override void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
        {
            var message = messages.FirstOrDefault();
            var tag     = new NfcTag(message, message.Records);

            _tcs.SetResult(tag);
        }
Example #7
0
        //private void ManageReadOperation(NFCNdefReaderSession session, NFCNdefMessage[] messages)
        //{
        //    if (messages?.Any() != true)
        //    {
        //        OnNfcTagRead?.Invoke(this, null);
        //        return;
        //    }

        //    NfcTagInfo tagInfo = new NfcTagInfo();
        //    OnNdefRed(messages.FirstOrDefault(), null);
        //}

        private void ManageReadOperation(NFCNdefReaderSession session, INFCNdefTag[] tags)
        {
            var nFCNdefTag = tags[0];

            session.ConnectToTag(nFCNdefTag, (error) => OnNfcTagTextWriten(this, false));
            nFCNdefTag.ReadNdef(OnNdefRed);
        }
Example #8
0
        public override void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
        {
            int user_id = 0;

            try
            {
                if (messages != null && messages.Length > 0)
                {
                    var      first         = messages[0];
                    string   messa         = GetRecords(first.Records);
                    string[] variables     = messa.Split('=');
                    string[] depura_userid = variables[1].Split('&');
                    string   tag_id        = variables[2];
                    user_id = Convert.ToInt32(depura_userid[0]);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            AppDelegate.user_id_tag = user_id.ToString();
            session.InvalidateSession();
            session.Dispose();
            Thread.Sleep(4000);
            write_tag myobject = new write_tag();

            myobject.ScanWriteAsync();
        }
Example #9
0
        public async Task EnableSessionAsync()
        {
            try
            {
                await _lockSemaphore.WaitAsync();

                if (_isSessionEnabled)
                {
                    return;
                }

                _session = new NFCNdefReaderSession(this, DispatchQueue.CurrentQueue, false)
                {
                    AlertMessage = "Tap a tag to start..."
                };

                _session.BeginSession();
                _isSessionEnabled = true;
                System.Diagnostics.Debug.WriteLine("========> Session enabled");
            }
            finally
            {
                _lockSemaphore.Release();
            }
        }
Example #10
0
 public async Task StartListeningAsync()
 {
     _session = new NFCNdefReaderSession(this, DispatchQueue.CurrentQueue, true);
     _session.BeginSession();
     var reader  = new NfcReader();
     var message = await reader.ScanAsync();
 }
Example #11
0
 public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
 {
     _data?.Clear();
     foreach (NFCNdefMessage message in messages)
     {
         foreach (NFCNdefPayload record in message.Records)
         {
             var typeNameFormat = record.TypeNameFormat;
             //var identifier = record.Identifier?.ToArray();
             var type    = record.Type;
             var payload = record.Payload;
             if (payload.Length > 0)
             {
                 ReadData(payload.ToArray());
             }
             else
             {
                 ReadData(type.ToArray());
             }
         }
     }
     if (_data.ToString().Length > 0)
     {
         MessagingCenter.Send <string>(_data.ToString(), "data");
     }
 }
Example #12
0
        public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
        {
            var bytes   = messages[0].Records[0].Payload.Skip(3).ToArray();
            var message = Encoding.UTF8.GetString(bytes);

            _tcs.SetResult(message);
        }
Example #13
0
        public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
        {
            LogMessage("NFC Tag detected!");

            // Check if there are any NDEF messages
            if (messages.Length == 0)
            {
                LogMessage("No NDEF messages found!");
                return;
            }

            // Find first record
            var records = messages[0].Records;

            if (records.Length == 0)
            {
                LogMessage("No Records found!");
                return;
            }

            var record = records[0];

            // Extract Uri from record
            var text = (string)new NSString(record.Payload, NSStringEncoding.UTF8);
            var url  = "http://" + text.Substring(1);

            LogMessage("NDEF formatted Tag found.");
            LogMessage("Url: " + url);

            //BeginInvokeOnMainThread(() =>
            //{
            //    UIApplication.SharedApplication.OpenUrl(new NSUrl(url));
            //});
        }
 public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
 {
     foreach (NFCNdefMessage msg in messages)
     {
         DetectedMessages.Add(msg);
     }
     DispatchQueue.MainQueue.DispatchAsync(() => { this.TableView.ReloadData(); });
 }
 partial void Scan(UIBarButtonItem sender)
 {
     Session = new NFCNdefReaderSession(this, null, true);
     if (Session != null)
     {
         Session.BeginSession();
     }
 }
Example #16
0
 /// <summary>
 /// Starts tags detection
 /// </summary>
 public void StartListening()
 {
     NfcSession = new NFCNdefReaderSession(this, DispatchQueue.CurrentQueue, true)
     {
         AlertMessage = UIMessages.NFCDialogAlertMessage
     };
     NfcSession?.BeginSession();
 }
Example #17
0
 private void BeginNfcSession()
 {
     nfcSession = new NFCNdefReaderSession(this, DispatchQueue.MainQueue, true)
     {
         AlertMessage = "Acerque tarjeta NFC"
     };
     nfcSession?.BeginSession();
 }
Example #18
0
 /// <summary>
 /// Starts tags detection
 /// </summary>
 public void StartListening()
 {
     NfcSession = new NFCNdefReaderSession(this, DispatchQueue.CurrentQueue, true)
     {
         AlertMessage = Configuration.Messages.NFCDialogAlertMessage
     };
     NfcSession?.BeginSession();
     OnTagListeningStatusChanged?.Invoke(true);
 }
Example #19
0
        public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
        {
            Console.WriteLine("ServiceToolStandard DidDetect msgs " + messages.Length);
            var bytes   = messages[0].Records[0].Payload.Skip(3).ToArray();
            var message = Encoding.UTF8.GetString(bytes);

            Console.WriteLine("ServiceToolStandard DidDetect msg " + message);
            _tcs.SetResult(message);
        }
Example #20
0
 public override void DidInvalidate(NFCNdefReaderSession session, NSError error)
 {
     // filter which codes are errors
     System.Diagnostics.Debug.WriteLine(error);
     if (error.Code != 0xC8)
     {
         reader.Error?.Invoke(reader, EventArgs.Empty);
     }
 }
Example #21
0
        private void OnScanButtonClicked(object sender, EventArgs e)
        {
            LogMessage("Scanning startet.");

            // Initialize NDEF reading session and set delegate to this ViewController.
            session = new NFCNdefReaderSession(this, null, true);
            session.AlertMessage = "Approach NFC Tag to top of phone";

            session.BeginSession();
        }
Example #22
0
        public override async void DidInvalidate(NFCNdefReaderSession session, NSError error)
        {
            System.Diagnostics.Debug.WriteLine($"========> DidInvalidate {error}");
            await DisableSessionAsync();

            if ((NFCReaderError)(long)error.Code == NFCReaderError.ReaderSessionInvalidationErrorSessionTimeout)
            {
                SessionTimeout?.Invoke(this, EventArgs.Empty);
            }
        }
Example #23
0
 public void invoke_lector()
 {
     InvokeOnMainThread(() =>
     {
         Session = new NFCNdefReaderSession(this, null, true);
         if (Session != null)
         {
             Session.BeginSession();
         }
     });
 }
Example #24
0
        public override async void DidDetectTags(NFCNdefReaderSession session, INFCNdefTag[] tags)
        {
            System.Diagnostics.Debug.WriteLine("========> DidDetectTags");

            _tag = tags[0];
            await session.ConnectToTagAsync(_tag);

            TagDetected?.Invoke(this, new NfcTagDetectedEventArgs(
                                    tagId: string.Empty, //// TODO: CHECK HOW TO GET ID
                                    ndefMessage: await ReadNdefAsync()));
        }
Example #25
0
        public void DidInvalidate(NFCNdefReaderSession session, NSError error)
        {
            var readerError = (NFCReaderError)(long)error.Code;

            if (readerError != NFCReaderError.ReaderSessionInvalidationErrorFirstNDEFTagRead &&
                readerError != NFCReaderError.ReaderSessionInvalidationErrorUserCanceled)
            {
                EndSession();
                // some error handling
                MessagingCenter.Send <string>(readerError.ToString(), "data");
            }
        }
Example #26
0
 private void StartSession()
 {
     if (_isNFCCapable)
     {
         try
         {
             _nfcSession = new NFCNdefReaderSession(this, null, false);
             _nfcSession?.BeginSession();
         }
         catch { }
     }
 }
Example #27
0
        public async Task <string> ScanAsync()
        {
            if (!NFCNdefReaderSession.ReadingAvailable)
            {
                throw new InvalidOperationException("Reading NDEF is not available");
            }

            _tcs     = new TaskCompletionSource <string>();
            _session = new NFCNdefReaderSession(this, null, true);
            _session.BeginSession();

            return(await _tcs.Task);
        }
        public Task <NFCNdefMessage[]> ScanAsync()
        {
            if (!NFCNdefReaderSession.ReadingAvailable)
            {
                throw new InvalidOperationException("Reading NDEF is not available");
            }

            _tcs     = new TaskCompletionSource <NFCNdefMessage[]>();
            _session = new NFCNdefReaderSession(this, DispatchQueue.CurrentQueue, true);
            _session.BeginSession();

            return(_tcs.Task);
        }
Example #29
0
 public void DidDetectTags(NFCNdefReaderSession session, INFCNdefTag[] tags)
 {
     try
     {
         string user_id_tag = AppDelegate.user_id_tag;
         if (user_id_tag == "?")
         {
             Task task = App.DisplayAlertAsync("¡Primero escanea este Tag para escribirlo!");
             session.InvalidateSession();
             session.Dispose();
             AppDelegate.user_id_tag = "?";
         }
         else
         {
             if ((Convert.ToInt32(user_id_tag) == Convert.ToInt32(MainViewModel.GetInstance().User.UserId.ToString())) || (0 == Convert.ToInt32(user_id_tag)))
             {
                 var nFCNdefTag = tags[0];
                 session.ConnectToTag(nFCNdefTag, CompletionHandler);
                 string         dominio        = "http://boxweb.azurewebsites.net/";
                 string         user           = MainViewModel.GetInstance().User.UserId.ToString();
                 string         tag_id         = "";
                 string         url            = dominio + "index3.aspx?user_id=" + user + "&tag_id=" + tag_id;
                 NFCNdefPayload payload        = NFCNdefPayload.CreateWellKnownTypePayload(url);
                 NFCNdefMessage nFCNdefMessage = new NFCNdefMessage(new NFCNdefPayload[] { payload });
                 nFCNdefTag.WriteNdef(nFCNdefMessage, delegate
                 {
                     Console.WriteLine("ok");
                 });
                 //Task task = App.DisplayAlertAsync(user_id_tag);
             }
             else
             {
                 Task task2 = App.DisplayAlertAsync("¡Este Tag esta vinculado con otro usuario!");
                 session.Dispose();
                 session.InvalidateSession();
                 AppDelegate.user_id_tag = "?";
             }
             AppDelegate.user_id_tag = "?";
             PopupNavigation.Instance.PopAsync();
             session.InvalidateSession();
             _tagSession.InvalidateSession();
             Thread.Sleep(4000);
         }
     }
     catch (Exception ex)
     {
         Console.Write(ex);
         modo_escritura = false;
     }
 }
        public void DidInvalidate(NFCNdefReaderSession session, NSError error)
        {
            var readerError = (NFCReaderError)(long)error.Code;

            if (readerError != NFCReaderError.ReaderSessionInvalidationErrorFirstNDEFTagRead &&
                readerError != NFCReaderError.ReaderSessionInvalidationErrorUserCanceled)
            {
                BeginInvokeOnMainThread(() => {
                    var alertController = UIAlertController.Create("Session Invalidated", error.LocalizedDescription, UIAlertControllerStyle.Alert);
                    alertController.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null));
                    PresentViewController(alertController, true, null);
                });
            }
        }