Skip to content

Instantly share code, notes, and snippets.

@Theminemat
Created January 21, 2026 17:14
Show Gist options
  • Select an option

  • Save Theminemat/ab74132b14ec06d66fac503dd8daba9c to your computer and use it in GitHub Desktop.

Select an option

Save Theminemat/ab74132b14ec06d66fac503dd8daba9c to your computer and use it in GitHub Desktop.
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RescueRobotsCar.Driver.RFID;
namespace RescueRobotsCar.Services
{
public class RfidReader
{
private readonly IMfRc522 _reader;
private static readonly byte[] DefaultKeyA = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
public static RfidReader? Instance { get; private set; }
public RfidReader(IMfRc522 reader)
{
_reader = reader;
}
internal static void SetInstance(RfidReader reader) => Instance = reader;
public async Task<string?> ReadBlock4Async(TimeSpan timeout)
{
using var cts = new CancellationTokenSource(timeout);
try
{
while (!cts.IsCancellationRequested)
{
if (!_reader.ListenToCardIso14443TypeA(out var card, TimeSpan.FromMilliseconds(200)))
{
await Task.Delay(50, cts.Token).ConfigureAwait(false);
continue;
}
if (_reader.AuthenticateMifareA(4, DefaultKeyA, card.NfcId) < 0)
{
_reader.ReselectCard();
continue;
}
if (_reader.Read16Bytes(4, out var data) >= 0 && data != null)
{
_reader.ReselectCard();
int len = 16; while (len > 0 && data[len - 1] == 0) len--;
var s = len > 0 ? Encoding.UTF8.GetString(data, 0, len) : string.Empty;
if (s.Length > 5) s = s.Substring(0, 5);
return s;
}
_reader.ReselectCard();
}
}
catch (OperationCanceledException) { }
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment