예제 #1
0
        private void PublishRecord(NdefRecord record, bool writeToTag)
        {
            if (_device == null)
            {
                return;
            }
            // Make sure we're not already publishing another message
            StopPublishingMessage(false);
            // Wrap the NDEF record into an NDEF message
            var message = new NdefMessage {
                record
            };
            // Convert the NDEF message to a byte array
            var msgArray = message.ToByteArray();

            try
            {
                // Publish the NDEF message to a tag or to another device, depending on the writeToTag parameter
                // Save the publication ID so that we can cancel publication later
                _publishingMessageId = _device.PublishBinaryMessage((writeToTag ? "NDEF:WriteTag" : "NDEF"), msgArray.AsBuffer(), MessageWrittenHandler);
                // Update status text for UI
                SetStatusOutput(string.Format(_loader.GetString(writeToTag ? "StatusWriteToTag" : "StatusWriteToDevice"), msgArray.Length, _publishingMessageId));
                // Update enabled / disabled state of buttons in the User Interface
                UpdateUiForNfcStatusAsync();
            }
            catch (Exception e)
            {
                SetStatusOutput(string.Format(_loader.GetString("StatusPublicationError"), e.Message));
            }
        }
예제 #2
0
파일: AndroidTag.cs 프로젝트: Azyyyyyy/XNFC
        /// <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);
        }
예제 #3
0
        private void WriteToTagExecute()
        {
            var spRecord = new NdefSpRecord
            {
                Uri       = shortenedNote,
                NfcAction = NdefSpActRecord.NfcActionType.DoAction
            };

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

            if (tagSize >= msg.ToByteArray().Length)
            {
                nfcService.WriteNdefMessageToTag(msg);
                uxService.ShowToastNotification("NFC", AppResources.NfcMessageWritten);
            }
            else
            {
                uxService.ShowToastNotification("NFC", AppResources.NfcMessageTooLong);
                LogMessage(AppResources.NfcMessageTooLong, NfcLogItem.WARNING_ICON);
            }
        }
예제 #4
0
파일: Nfc.cs 프로젝트: melihercan/Xamarinme
        public async Task WriteNdefAsync(NdefMessage ndefMessage)
        {
            Android.Nfc.Tech.Ndef ndef = null;

            try
            {
                await _lockSemaphore.WaitAsync();

                if (!_isNfcEnabled)
                {
                    throw new Exception("NFC is not enabled");
                }

                ndef = Android.Nfc.Tech.Ndef.Get(_tag);
                ndef.Connect();
                await ndef.WriteNdefMessageAsync(new Android.Nfc.NdefMessage(ndefMessage.ToByteArray()));

                ndef.Close();
            }
            catch (Exception ex)
            {
                if (ndef.IsConnected)
                {
                    ndef.Close();
                }
                throw ex;
            }
            finally
            {
                _lockSemaphore.Release();
            }
        }
예제 #5
0
        private static void WriteTagFile(string pathName, string tagName, NdefMessage ndefMessage)
        {
            // NDEF message
            var ndefMessageBytes = ndefMessage.ToByteArray();

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

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

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

            using (var fs = File.Create(Path.Combine(pathName, hexFileName)))
            {
                using (var logFileWriter = new StreamWriter(fs))
                {
                    logFileWriter.Write(ConvertToHexByteString(ndefMessageBytes));
                }
            }
        }
예제 #6
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);
        }
예제 #7
0
        public async Task<WriteResult> WriteTag(NdefMessage message, CancellationToken cancellationToken, TimeSpan timeout)
        {
            if (!IsSupported)
            {
                if (_dontThrowExpceptionWhenNotSupported)
                {
                    return null;
                }
                throw new NotSupportedException("This device does not support NFC (or perhaps it's disabled)");
            }
            Task timeoutTask = null;
            if (timeout != default(TimeSpan))
            {
                timeoutTask = Task.Delay(timeout);
            }
            long subscription;

            TaskCompletionSource<WriteResult> resultSource = new TaskCompletionSource<WriteResult>(); //needs a message type

            using (cancellationToken.Register((s => ((TaskCompletionSource<WriteResult>)s).TrySetCanceled()), resultSource))
            {
                
                byte[] theMessage=message.ToByteArray();
                subscription = _proximityDevice.PublishBinaryMessage("NDEF:WriteTag", theMessage.AsBuffer(), (sender, id) =>
                {
                    WriteResult result = new WriteResult();
                    result.NFCTag = new NFCTag();
                    result.ReasonForFailure = FailureReasons.DidNotFail;
                    resultSource.TrySetResult(result);
                });                    
                try
                {

                    if (timeoutTask != null)
                    {
                        await Task.WhenAny(timeoutTask, resultSource.Task);



                        if (timeoutTask.IsCompleted)
                        {
                            throw new TimeoutException("NFC message not recieved in time");
                        }
                    }
                    if (resultSource.Task.IsCanceled)
                    {
                        return null;
                    }
                    return await resultSource.Task;
                }
                finally
                {
                    _proximityDevice.StopPublishingMessage(subscription);

                }
            }
        }
예제 #8
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));
            }
        }
예제 #9
0
        public async Task <WriteResult> WriteTag(NdefMessage message, CancellationToken cancellationToken, TimeSpan timeout)
        {
            if (!IsSupported)
            {
                if (_dontThrowExpceptionWhenNotSupported)
                {
                    return(null);
                }
                throw new NotSupportedException("This device does not support NFC (or perhaps it's disabled)");
            }
            Task timeoutTask = null;

            if (timeout != default(TimeSpan))
            {
                timeoutTask = Task.Delay(timeout);
            }
            long subscription;

            TaskCompletionSource <WriteResult> resultSource = new TaskCompletionSource <WriteResult>(); //needs a message type

            using (cancellationToken.Register((s => ((TaskCompletionSource <WriteResult>)s).TrySetCanceled()), resultSource))
            {
                byte[] theMessage = message.ToByteArray();
                subscription = _proximityDevice.PublishBinaryMessage("NDEF:WriteTag", theMessage.AsBuffer(), (sender, id) =>
                {
                    WriteResult result      = new WriteResult();
                    result.NFCTag           = new NFCTag();
                    result.ReasonForFailure = FailureReasons.DidNotFail;
                    resultSource.TrySetResult(result);
                });
                try
                {
                    if (timeoutTask != null)
                    {
                        await Task.WhenAny(timeoutTask, resultSource.Task);



                        if (timeoutTask.IsCompleted)
                        {
                            throw new TimeoutException("NFC message not recieved in time");
                        }
                    }
                    if (resultSource.Task.IsCanceled)
                    {
                        return(null);
                    }
                    return(await resultSource.Task);
                }
                finally
                {
                    _proximityDevice.StopPublishingMessage(subscription);
                }
            }
        }
예제 #10
0
 public void WriteNdefMessage(NdefMessage msg)
 {
     if (msg != null)
     {
         ndefDataToWrite = msg.ToByteArray();
     }
     else
     {
         ndefDataToWrite = null;
     }
 }
예제 #11
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     var device = ProximityDevice.GetDefault();
     if (device == null) return;
     var record = new NdefSpRecord {
         Uri = "cloudsdale://clouds/" + cloud.id,
         NfcAction = NdefSpActRecord.NfcActionType.DoAction
     };
     record.AddTitle(new NdefTextRecord { Text = cloud.name, LanguageCode = "en" });
     var message = new NdefMessage { record };
     messageIds.Add(device.PublishBinaryMessage("NDEF", message.ToByteArray().AsBuffer()));
 }
예제 #12
0
 private void PeerFinder_TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs args)
 {
     if (args.State == TriggeredConnectState.PeerFound)
     {
         proximityDevice = ProximityDevice.GetDefault();
         var message = new NdefMessage {
             new NdefUriRecord {
                 Uri = "tracktimer:addFriend?" + App.MobileService.CurrentUser.UserId
             }
         };
         proximityDevice.PublishBinaryMessage("NDEF", message.ToByteArray().AsBuffer(), MessageWrittenHandler);
     }
 }
예제 #13
0
        public string Write()
        {
            Log.Debug("Card write");

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

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

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

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

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

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

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

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

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

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

            return(null);
        }
예제 #14
0
 public NFCMessage Ndef_WriteMessage(Ndef ndf, NdefMessage msg)
 {
     if (!ndf.IsWritable)
     {
         return(NFCMessage.NFC_UN_WRITABLE_TAG);
     }
     if (ndf.MaxSize < msg.ToByteArray().Length)
     {
         return(NFCMessage.NFC_INVALID_MSG);
     }
     ndf.WriteNdefMessage(msg);
     OnWriting_NdefMessage?.Invoke(msg);
     return(NFCMessage.NFC_TAG_WRITTEN);
 }
예제 #15
0
        /*
         * Method Name: Write Message
         * Purpose: This is to control the writing of a card once a NDE tag has been detected
         */
        private async Task <bool> WriteMessage(Tag cardTag, NdefMessage cardContent)
        {
            try
            {
                var ndefTagConnection = Ndef.Get(cardTag);
                if (ndefTagConnection == null)
                {
                    AlertBoxComponent cardTagMissingAlertBox = new AlertBoxComponent(_context);
                    cardTagMissingAlertBox.Setup("Card Not Found", "Please try tapping the card again.");
                    cardTagMissingAlertBox.Show();
                }

                await ndefTagConnection.ConnectAsync();

                if (!ndefTagConnection.IsWritable)
                {
                    AlertBoxComponent cardUnwritableAlertBox = new AlertBoxComponent(_context);
                    cardUnwritableAlertBox.Setup("Card Unwritable", "This card is read only. Please try a different card.");
                    cardUnwritableAlertBox.Show();
                }

                var messageSize = cardContent.ToByteArray().Length;
                if (ndefTagConnection.MaxSize < messageSize)
                {
                    AlertBoxComponent cardFullAlertBox = new AlertBoxComponent(_context);
                    cardFullAlertBox.Setup("Card Storage Exceeded", "This card does not have enough storage. Please try a different card.");
                    cardFullAlertBox.Show();
                }

                await ndefTagConnection.WriteNdefMessageAsync(cardContent);

                ndefTagConnection.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();

                return(true);
            }
            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();
            }

            return(false);
        }
예제 #16
0
        private void ParseNdefIntent(Intent intent)
        {
            var rawMessages = intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages);

            if (rawMessages == null || rawMessages.Length != 1)
            {
                ShowToast("Can't handle this tag.");
                BackToMain();
                return;
            }

            NdefMessage msg = rawMessages[0] as NdefMessage;
            Tag         tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

            ndefHandler.SetExtraSignDataFromTag(tag);
            ndefHandler.SetKeys(AppSettings.Global.PubKey, AppSettings.Global.PrivKey);

            try
            {
                tagData = ndefHandler.ParseNdefMessage(msg.ToByteArray());

                if (ndefHandler.HasPubKey() && (tagData.ContainsKey(NdefHandler.SIG_VALID_KEY) || AppSettings.Global.KioskMode))
                {
                    bool sigValid = Convert.ToBoolean(tagData.GetValueOrDefault(NdefHandler.SIG_VALID_KEY, bool.FalseString));
                    if (!sigValid)
                    {
                        ShowToast("Invalid Tag Signature!");
                        BackToMain();
                        return;
                    }
                }

                CheckForSettings();
                UpdateTextView();
            }
            catch (NdefHandlerException e)
            {
                ShowToast(e.Message);
                BackToMain();
            }
            finally
            {
                ndefHandler.ClearExtraSignData();
                ndefHandler.ClearKeys();
            }
        }
예제 #17
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); }
        }
예제 #18
0
        /// <summary>
        /// This method will try and write the specified message to the provided tag.
        /// </summary>
        /// <param name="tag">The NFC tag that was detected.</param>
        /// <param name="ndefMessage">An NDEF message to write.</param>
        /// <returns>true if the tag was written to.</returns>
        private bool 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)
                {
                    DisplayMessage("Tag is read-only.");
                    return(false);
                }

                // NFC tags can only store a small amount of data, this depends on the type of tag its.
                var size = ndefMessage.ToByteArray().Length;
                if (ndef.MaxSize < size)
                {
                    DisplayMessage(String.Format("Tag doesn't have enough space ({0} > {1})", size, ndef.MaxSize));
                }
                else
                {
                    try
                    {
                        ndef.WriteNdefMessage(ndefMessage);
                        DisplayMessage("Succesfully wrote tag.");
                        //ActOnFoundTagActivity.LaunchActivity(this, InteractionMode.GunCalibration, "0000", InteractionMode.GunCalibration.Directive);
                        return(true);
                    }
                    catch (Java.IO.IOException e)
                    {
                        DisplayMessage("Error writing tag... maybe it needed formatting?\n" + e.Message);
                        return(false);
                    }
                }
            }

            return(false);
        }
예제 #19
0
파일: Nfc.cs 프로젝트: melihercan/Xamarinme
        public async Task <NdefMessage> WriteReadNdefAsync(NdefMessage ndefMessage)
        {
            await WriteNdefAsync(ndefMessage);

            // Compare the write content to read content to make sure that device responded.
            // Try this few times with timeout before generating error.
            for (int i = 0; i < 5; i++)
            {
                await Task.Delay(70);

                var rdNdefMessage = await ReadNdefAsync();

                if (!rdNdefMessage.ToByteArray().SequenceEqual(ndefMessage.ToByteArray()))
                {
                    return(rdNdefMessage);
                }
            }

            throw new Exception("WriteReadNdefAsync failed!!!");
        }
예제 #20
0
        private void PublishRecord(NdefRecord record, bool writeToTag)
        {
            if (_device == null)
            {
                return;
            }

            // Make sure we're not already publishing another message
            StopPublishingMessage(false);
            // Wrap the NDEF record into an NDEF message
            var message = new NdefMessage {
                record
            };
            // Convert the NDEF message to a byte array
            var msgArray = message.ToByteArray();

            // Publish the NDEF message to a tag or to another device, depending on the writeToTag parameter
            // Save the publication ID so that we can cancel publication later
            _publishingMessageId = _device.PublishBinaryMessage((writeToTag ? "NDEF:WriteTag" : "NDEF"), msgArray.AsBuffer(), MessageWrittenHandler);
        }
예제 #21
0
        private void Device_DeviceArrived(ProximityDevice sender)
        {
            var data = new { Employee = new { Id = 2572923226000L, Name = "TestUser" } };
            var payload = JsonConvert.SerializeObject(data);

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

            var msg = new NdefMessage { spRecord };

            long publishingId = device.PublishBinaryMessage("NDEF:WriteTag", msg.ToByteArray().AsBuffer(), (d0, id) => {
                device.DeviceArrived -= Device_DeviceArrived;
                Debug.WriteLine(" published. id = " + id);
                var notify = new MessageDialog("The message has been published.");
            });
        }
예제 #22
0
        /// <summary>
        /// This method will try and write the specified message to the provided tag.
        /// </summary>
        /// <param name="tag">The NFC tag that was detected.</param>
        /// <param name="ndefMessage">An NDEF message to write.</param>
        /// <returns>true if the tag was written to.</returns>
        private bool TryAndWriteToTag(Tag tag, NdefMessage ndefMessage)
        {
            bool returnVal = false;
            var  ndef      = Ndef.Get(tag);

            if (ndef != null)
            {
                bool connected = ndef.IsConnected;
                try
                {
                    ndef.Connect();

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

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

                    ndef.WriteNdefMessage(ndefMessage);
                    ndef.Close();
                    DisplayMessage("Succesfully wrote tag.");
                    returnVal = true;
                }
                catch
                {
                    DisplayMessage("Write failed. Was the Tag removed too soon?");
                }
            }
            return(returnVal);
        }
예제 #23
0
        //Currently this writes plaintext to tag in NDEF format
        //TODO: Other tag types
        //      Limit to how much data can be fit to tag
        static void write_to_tag(String bytes_in)
        {
            string command_prefix = "FF D6 00 ";
            string command;
            String Hex_address;

            NdefMessage write_this = new NdefMessage {
                new NdefUriRecord {
                    Uri = bytes_in
                }
            };

            byte[]      ndef_prefix = { 0x03, (byte)write_this.ToByteArray().Length };
            List <byte> concat      = new List <byte>();

            concat.AddRange(ndef_prefix);
            concat.AddRange(write_this.ToByteArray());
            byte[] ndef_bytes = concat.ToArray();

            foreach (var item in ndef_bytes)
            {
                Console.WriteLine(HexFormatting.ToHexString(item));
            }

            //Byte[] Input_bytes = hex_string_to_byte_array(string_to_hex_string(bytes_in));
            byte[]   send_chunk = new byte[4];
            RespApdu write_four_bytes;
            int      count = 0;
            int      mod4  = ndef_bytes.Length % 4;


            for (int i = 0; i < ndef_bytes.Length; ++i)
            {
                send_chunk[count] = ndef_bytes[i];
                ++count;
                if (count == 4)
                {
                    count       = 0;
                    Hex_address = String.Format("{0:X}", Convert.ToInt32((i / 4) + 4));
                    if ((i / 4) + 4 < 16)
                    {
                        Hex_address = "0" + Hex_address;
                    }
                    Console.WriteLine(Hex_address);

                    command = command_prefix + Hex_address + " 04 " + HexFormatting.ToHexString(send_chunk, true);
                    Console.WriteLine(command);
                    write_four_bytes = reader.Exchange(command);
                }
            }

            if (count != 0)
            {
                for (int i = count; i < send_chunk.Length; i++)
                {
                    send_chunk[i] = 0x00;
                }
                send_chunk[2] = 254;
                Hex_address   = String.Format("{0:X}", Convert.ToInt32(((ndef_bytes.Length - count) / 4) + 4));
                if ((((ndef_bytes.Length - count) / 4) + 4) < 16)
                {
                    Hex_address = "0" + Hex_address;
                }
                command          = command_prefix + Hex_address + " 04 " + HexFormatting.ToHexString(send_chunk, true);
                write_four_bytes = reader.Exchange(command);
            }



            //command = command + "04" + " 04 " + hexString;
            //write_four_bytes = reader.Exchange(command);

            /*if (Input_bytes.Length % 4 != 0)
             * {
             *  int mod_of_input = Input_bytes.Length % 4;
             *  for (int i = 0; i < mod_of_input; i++)
             *  {
             *
             *
             *  }
             * }*/

/*
 *          for (int i = 0; i < Input_bytes.Length; i = i + 4)
 *          {
 *              for (int j = 0; j < 4; j++)
 *              {
 *                  if (j + i < Input_bytes.Length)
 *                  {
 *                      send_chunk[j] = Input_bytes[j + i];
 *                  }
 *              }
 *
 *              value = Convert.ToInt32(byte_num);
 *              Hex_address = String.Format("{0:X}", value);
 *              command = command + Hex_address + " 04 " + HexFormatting.ToHexString(send_chunk, true);
 *              write_four_bytes = reader.Exchange(command);
 *              byte_num = byte_num + 1;
 *          }*/
        }
예제 #24
0
 public void NDEFWrite(NdefMessage Message)
 {
     WriteAll(Message.ToByteArray());
 }
예제 #25
0
        private void PublishRecord(NdefRecord record, bool writeToTag)
        {
            if (_device == null)
            return;

              // Make sure we're not already publishing another message
              StopPublishingMessage(false);
              // Wrap the NDEF record into an NDEF message
              var message = new NdefMessage { record };
              // Convert the NDEF message to a byte array
              var msgArray = message.ToByteArray();
              // Publish the NDEF message to a tag or to another device, depending on the writeToTag parameter
              // Save the publication ID so that we can cancel publication later
              _publishingMessageId = _device.PublishBinaryMessage((writeToTag ? "NDEF:WriteTag" : "NDEF"), msgArray.AsBuffer(), MessageWrittenHandler);
        }
예제 #26
0
     //   private Windows.UI.Core.CoreDispatcher _dispatcher =
     //Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;

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

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

        private void PublishRecord(NdefRecord record, bool writeToTag)
        {
            if (_device == null) return;
            // Make sure we're not already publishing another message
            StopPublishingMessage(false);
            // Wrap the NDEF record into an NDEF message
            var message = new NdefMessage { record };
            // Convert the NDEF message to a byte array
            var msgArray = message.ToByteArray();
            // Publish the NDEF message to a tag or to another device, depending on the writeToTag parameter
            // Save the publication ID so that we can cancel publication later
            _publishingMessageId = _device.PublishBinaryMessage((writeToTag ? "NDEF:WriteTag" : "NDEF"), msgArray.AsBuffer(), MessageWrittenHandler);
            // Update status text for UI
           //_publishingMessageId = -1;
            SetStatusOutput(string.Format((writeToTag ? AppResources.StatusWriteToTag : AppResources.StatusWriteToDevice), msgArray.Length, _publishingMessageId));
           
        }
예제 #27
0
        public async Task WriteNdefAsync(NdefMessage ndefMessage)
        {
            try
            {
                await _lockSemaphore.WaitAsync();

                if (!_isSessionEnabled)
                {
                    throw new Exception("NFC is not enabled");
                }


                // Start writing NDEF TLV starting from _ndefTlvPage.
                // First reset TLV length.
                byte[] tlvPage = { NdefTlv, 0, 0, 0 };
                UpdateBinary(0, _ndefTlvPage, tlvPage);

                // Write NDEF data (TLV payload).
                int ndefTlvLen    = ndefMessage.ToByteArray().Length;
                int numTotalPages = 0;
                int payloadOffset = 0;

                if (ndefTlvLen >= 0xFF)
                {
                    // Calculate number of total pages to write.
                    numTotalPages = ndefTlvLen / 4 + (ndefTlvLen % 4 == 0 ? 0 : 1) + 1;

                    // Payload offset.
                    payloadOffset = 4;
                }
                else
                {
                    // Calculate number of total pages to write.
                    numTotalPages = ndefTlvLen / 4 + (ndefTlvLen % 4 < 3 ? 0 : 1) + 1;

                    // Payload offset.
                    payloadOffset = 2;
                }

                if (numTotalPages > 0x84)
                {
                    throw new Exception();
                }

                byte[] command = new byte[numTotalPages * 4];
                Buffer.BlockCopy(tlvPage, 0, command, 0, 4);
                Buffer.BlockCopy(ndefMessage.ToByteArray(), 0, command, payloadOffset, ndefTlvLen);

                byte[] page = new byte[4];
                int    idx  = 0;
                for (byte i = _ndefTlvPage; i < _ndefTlvPage + numTotalPages; i++)
                {
                    Buffer.BlockCopy(command, idx, page, 0, 4);
                    idx += 4;
                    UpdateBinary(0, i, page);
                }

                // Calculate TLV total length.
                int ndefTlvTotalLen = 0;
                if (payloadOffset == 4)
                {
                    ndefTlvTotalLen = 4 + ndefTlvLen;
                }
                else
                {
                    ndefTlvTotalLen = 2 + ndefTlvLen;
                }

                Debug.WriteLine($"{DateTime.Now.TimeOfDay}" + $"####WRITE:" +
                                BitConverter.ToString(ndefMessage.ToByteArray()).Replace("-", string.Empty));

                // Add TLV terminator.
                byte   tlvTerminatePage = 0;
                byte[] tlvTerminate     = new byte[4];
                if (ndefTlvTotalLen % 4 == 0)
                {
                    tlvTerminatePage = (byte)(_ndefTlvPage + numTotalPages);
                    tlvTerminate[0]  = 0xFE;
                }
                else
                {
                    tlvTerminatePage = (byte)(_ndefTlvPage + numTotalPages - 1);
                    Buffer.BlockCopy(command, (numTotalPages - 1) * 4, tlvTerminate, 0, 4);
                    tlvTerminate[ndefTlvTotalLen % 4] = 0xFE;
                }
                UpdateBinary(0, tlvTerminatePage, tlvTerminate);

                // Update TLV length.
                // Should be the last write.
                Buffer.BlockCopy(command, 0, tlvPage, 0, 4);
                if (payloadOffset == 4)
                {
                    tlvPage[1] = 0xFF;
                    tlvPage[2] = (byte)(ndefTlvLen >> 8);
                    tlvPage[3] = (byte)(ndefTlvLen);
                }
                else
                {
                    tlvPage[1] = (byte)(ndefTlvLen);
                }
                UpdateBinary(0, _ndefTlvPage, tlvPage);
            }
            finally
            {
                _lockSemaphore.Release();
            }
        }
예제 #28
0
파일: CardWriter.cs 프로젝트: edjo23/shop
        public string Write()
        {
            Log.Debug("Card write");

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

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

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

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

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

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

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

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

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

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

            return null;
        }
예제 #29
0
 private void PublishRecord(NdefRecord record, bool writeToTag)
 {
     if (_device == null) return;
     // Make sure we're not already publishing another message
     StopPublishingMessage(false);
     // Wrap the NDEF record into an NDEF message
     var message = new NdefMessage { record };
     // Convert the NDEF message to a byte array
     var msgArray = message.ToByteArray();
     try
     {
         // Publish the NDEF message to a tag or to another device, depending on the writeToTag parameter
         // Save the publication ID so that we can cancel publication later
         _publishingMessageId = _device.PublishBinaryMessage((writeToTag ? "NDEF:WriteTag" : "NDEF"), msgArray.AsBuffer(), MessageWrittenHandler);
         // Update status text for UI
         SetStatusOutput(string.Format(_loader.GetString(writeToTag ? "StatusWriteToTag" : "StatusWriteToDevice"), msgArray.Length, _publishingMessageId));
         // Update enabled / disabled state of buttons in the User Interface
         UpdateUiForNfcStatusAsync();
     }
     catch (Exception e)
     {
         SetStatusOutput(string.Format(_loader.GetString("StatusPublicationError"), e.Message));
     }
 }
예제 #30
0
        /// <summary>
        /// Reverse function to parseRecords() - this one takes
        /// the information stored in the individual record instances and assembles
        /// it into the payload of the base class.
        /// </summary>
        /// <remarks>
        /// As the URI is mandatory, the payload will not be assembled
        /// if no URI is defined.
        /// </remarks>
        /// <returns>Whether assembling the payload was successful.</returns>
        private bool AssemblePayload()
        {
            // Uri is mandatory - don't assemble the payload if it's not set
            if (RecordUri == null) return false;

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

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

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

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

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

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

            SetPayloadAndParse(message.ToByteArray(), false);

            return true;
        }
예제 #31
0
        private void WriteDataIntoCard(string data)
        {
            if (!connActive)
            {
                return;
            }

            NdefTextRecord textRecord = new NdefTextRecord()
            {
                Text = data, TextEncoding = NdefTextRecord.TextEncodingType.Utf8
            };
            NdefRecord  record  = new NdefRecord(textRecord);
            NdefMessage message = new NdefMessage {
                record
            };

            byte[] bytes = message.ToByteArray();

            int startBlockNum = 4, totalDataLength = bytes.Length + 3;
            int totalBlock = (totalDataLength % 4 == 0 ? (totalDataLength / 4) : (totalDataLength / 4 + 1));

            byte[] totalData     = new byte[totalBlock * 4];
            int    dataPageIndex = 0;

            totalData[0] = 0x03;
            totalData[1] = (byte)bytes.Length;

            for (int i = 0; i < bytes.Length; i++)
            {
                totalData[i + 2] = bytes[i];
            }
            totalData[totalData[1] + 2] = 0xFE;

            for (int iBlock = startBlockNum; iBlock < totalBlock + startBlockNum; iBlock++)
            {
                ClearBuffers();
                SendBuff[0] = 0xFF;         // CLA
                SendBuff[1] = 0xD6;         // INS
                SendBuff[2] = 0x00;         // P1
                SendBuff[3] = (byte)iBlock; // P2: Starting Block No.
                SendBuff[4] = 0x04;         // P3 : Data length

                for (int idx = 0; idx < 4; idx++)
                {
                    SendBuff[idx + 5] = totalData[(dataPageIndex * 4) + idx];
                }
                SendLen = 9;
                RecvLen = 0x02;

                retCode = SendAPDU(2);

                string tmpStr = string.Empty;
                if (retCode == ModWinsCard.SCARD_S_SUCCESS)
                {
                    tmpStr = "";
                    for (int idx = 0; idx <= RecvLen - 1; idx++)
                    {
                        tmpStr = tmpStr + string.Format("{0:X2}", RecvBuff[idx]);
                    }
                }
                if (tmpStr.Trim() == "9000")
                {
                }
                else
                {
                    WriteLog(4, 0, "Write block error!>>" + tmpStr.Trim());
                }

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

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

            var childBytes = childMsg.ToByteArray();

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

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

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

            _payload = newPayload;
        }
예제 #33
0
        public void SetPublishCrew(string personnel)
        {
            if (_proximity != null)
            {
                if (_subscribedMessageId != -1)
                {
                    _proximity.StopSubscribingForMessage(_subscribedMessageId);

                    _subscribedMessageId = -1;
                }

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

                    /*
                     * This section is based on MSDN and same function with using NDEF Library.
                     * But it was not verified
                     */
                    //string launchArgs = "user="******"!" + praid;
                    //string launchAppMessage = launchArgs + "\tWindows\t" + appName;
                    //var dataWriter = new Windows.Storage.Streams.DataWriter();
                    //dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                    //dataWriter.WriteString(launchAppMessage);
                    //_proximity.PublishBinaryMessage("LaunchApp:WriteTag", dataWriter.DetachBuffer(), messageTransmitted);
                    //NotifyUser("Publishing Message: \n" + launchArgs, NotifyType.StatusMessage);
                    
                }
                catch (Exception e)
                {
                    _subscribedMessageId = _proximity.SubscribeForMessage("NDEF", messageReceived);
                    this.NotifyUser(e.Message, NotifyType.ErrorMessage);
                }
            }
            else
                this.NotifyUser("NFC Device could not be found...", NotifyType.ErrorMessage);
        }
예제 #34
0
        private void PublishRecord(NdefRecord record, bool writeToTag)
        {
            if (_device == null) return;
            // Make sure we're not already publishing another message
            StopPublishingMessage(false);
            // Wrap the NDEF record into an NDEF message
            var message = new NdefMessage { record };
            // Convert the NDEF message to a byte array
            var msgArray = message.ToByteArray();
            // Publish the NDEF message to a tag or to another device, depending on the writeToTag parameter
            // Save the publication ID so that we can cancel publication later
            _publishingMessageId = _device.PublishBinaryMessage((writeToTag ? "NDEF:WriteTag" : "NDEF"), msgArray.AsBuffer(), MessageWrittenHandler);
            // Update status text for UI
            SetStatusOutput(string.Format((writeToTag ? AppResources.StatusWriteToTag : AppResources.StatusWriteToDevice), msgArray.Length, _publishingMessageId));
            // Update enabled / disabled state of buttons in the User Interface
            SetStatusOutput(string.Format("You said \"{0}\"\nPlease touch a tag to write the message.", recordresult));
           



            recordresult = "";
            UpdateUiForNfcStatus();
        }
예제 #35
0
        private static void WriteTagFile(string pathName, string tagName, NdefMessage ndefMessage)
        {
            // NDEF message
            var ndefMessageBytes = ndefMessage.ToByteArray();

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

            // Write NDEF message to hex file
            var hexFileName = String.Format(FileNameHex, tagName);
            using (var fs = File.Create(Path.Combine(pathName, hexFileName)))
            {
                using (var logFileWriter = new StreamWriter(fs))
                {
                    logFileWriter.Write(ConvertToHexByteString(ndefMessageBytes));
                }
            }
        }
예제 #36
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="timeout">Maximum time the Tappy will wait for a tag. Time out is in seconds. 0 = No time out</param>
 /// <param name="willLock">If true will lock the tag</param>
 /// <param name="ndefMessage">Ndef message to write to a tag</param>
 public WriteCustomNdef(byte timeout, bool willLock, NdefMessage message)
 {
     this.parameters.Add(timeout);
     this.parameters.Add(Convert.ToByte(willLock));
     this.parameters.AddRange(message.ToByteArray());
 }