Code Monkey home page Code Monkey logo

android-things-rc522's Introduction

Android Things RC522

An Android Things libray to control RFID readers based on the RC522 reader.

Based on pi-rc522 by user ondryaso

Bintray license Android Things

Features

  • Detect MIFARE 1k tags (not tested in other tags)
  • Authenticate, read and write to tags
  • Change authentication keys and access bits (must be done manually)
  • Increment, decrement, transfer and restore for value blocks
  • Easier way of changing keys and access bits

Planned features

  • Helper functions
  • Better error handling

Connections

The connections vary based on the board used.

RST pin is configured programatically.

Raspberry Pi 3

rfid-rc522_bb

RC522 Pin RPi Pin name RPi Pin number
SDA GPIO8, CE0 24
SCK GPIO11, SCKL 23
MOSI GPIO10, MOSI 19
MISO GPIO9, MISO 21
GND GND 6, 9, 20, 25
RST Any GPIO pin --
3.3V 3V3V 1, 17

Installing

This library is available at jCenter. To install add this to your module's build.gradle

dependencies {
    compile 'com.galarzaa.android-things:rc522:1.0.0'

Usage

The use of interruptions is not supported yet.

The RC522 must be polled until a card is found, and then perform any operations you want.

Unfortunately, in Android, the UI thread shouldn't be blocked, so the polling has to be done on a separate thread e.g. AsyncTask, Runnable, etc.

To use the libary, a SpiDevice object must be passed in the constructor, along with a Gpio object for the RST pin.

Polling state

import com.galarzaa.androidthings.Rc522;
public class MainActivty extends AppCompatActivity{
    private Rc522 mRc522;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PeripheralManagerService pioService = new PeripheralManagerService();
        try {
            /* Names based on Raspberry Pi 3 */
            SpiDevice spiDevice = pioService.openSpiDevice("SPI0.0");
            Gpio resetPin = pioService.openGpio("BCM25");
            /* Names based on NXP Pico i.MX7D I/O */
            SpiDevice spiDevice = pioService.openSpiDevice("SPI3.0");
            Gpio resetPin = pioService.openGpio("GPIO5_IO00");
            mRc522 = new Rc522(this, spiDevice, resetPin);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private void readRFid(){
        while(true){
            boolean success = mRc522.request();
            if(!success){
                continue;
            }
            success = mRc522.antiCollisionDetect();
            if(!success){
                continue;
            }
            byte[] uid = mRc522.getUid();
            mRc522.selectTag(uid);
            break;
        }
        // Factory Key A:
        byte[] key = {(byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF};
        // Data that will be written
        byte[] newData = {0x0F,0x0E,0x0D,0x0C,0x0B,0x0A,0x09,0x08,0x07,0x06,0x05,0x04,0x03,0x02,0x01,0x00};
        // Get the address of the desired block
        byte block = Rc522.getBlockAddress(3, 2);
        //We need to authenticate the card, each sector can have a different key
        boolean result = rc522.authenticateCard(Rc522.AUTH_A, block, key);
        if (!result) {
            //Authentication failed
            return;
        }
        result = rc522.writeBlock(block, newData);
        if(!result){
            //Could not write, key might have permission to read but not write
            return;
        }
        //Buffer to hold read data
        byte[] buffer = new byte[16];
        //Since we're still using the same block, we don't need to authenticate again
        result = rc522.readBlock(block, buffer);
        if(!result){
            //Could not read card
            return;
        }
        //Stop crypto to allow subsequent readings
        rc522.stopCrypto();
            
        
    }
}

Contributing

This library is still in development, suggestions, improvements and fixes are welcome. Please submit a pull request

Resources

android-things-rc522's People

Contributors

fleker avatar galarzaa90 avatar mangini avatar wegoandroid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

android-things-rc522's Issues

NFC reading not working

I managed to install and run the example app. My NFC reader also lights up. However, when I try to read a card nothing happens. After some debugging I managed to find out that it stucks in

protected Boolean doInBackground(Object... params) 

Any one an idea what I can do?

cannot authenticate Card after writing

Hi,
at first, here is my code:

           String resultsText = "";
           String data = "";

           byte[] key = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
           for (int sector = 1; sector <= 16; sector++) {
               byte address = Rc522.getBlockAddress(sector, 1);
               boolean result = rc522.authenticateCard(Rc522.AUTH_A, address, key);
               if (!result) {
                   result = rc522.authenticateCard(Rc522.AUTH_B, address, key);
               }
               if (!result) {
                   return;
               }
               for (int block = 1; block <= 3; block++) {
                   address = Rc522.getBlockAddress(sector, block);
                   String txt = "12412341 Block "+block;
                   byte[] newData = txt.getBytes();
                   try {
                      result = rc522.writeBlock(address, newData);
                      if(!result){
                        return;
                      }
                       byte[] buffer = new byte[16];
                       result = rc522.readBlock(address, buffer);
                       if (!result) {
                           return;
                       }
                       resultsText += Rc522.dataToHexString(buffer);
                       for(int i = 0; i < 16; i++) {
                           String temp_char = Character.toString((char) buffer[i]);
                            data += temp_char;
                        }
                        Log.e("","");
                    } catch (Exception ex) {
                       Log.e("","");
                   }finally{
                       Log.e("","");
                   }
               }
           }
           rc522.stopCrypto();
       }

My Problem is:
If I write the Text on the card I only can write to the first sektor. authentification on sektor 2 failes.
If I just read a new card, i can read every sector. If I had written some Data on the card i cannot authentificate on sector one and i can throw the card to trash, even my smartphone cant read, write or delete the card. Im using Mifare Classic 1k.

So whats wrong with my code? any suggestions?
Thanks :)

boolean success = rc522.request(); Condition 'success' is always 'false'!!!why?

public class MainActivity extends Activity {

    private TextView textView;

    private Rc522 rc522;
    private SpiDevice spiDevice;
    private Gpio gpioReset;

    private static final String SPI_PORT = "SPI0.0";
    private static final String PIN_RESET = "BCM25";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            PeripheralManager pioService = PeripheralManager.getInstance();
            spiDevice = pioService.openSpiDevice(SPI_PORT);
            gpioReset = pioService.openGpio(PIN_RESET);
            rc522 = new Rc522(spiDevice, gpioReset);
        } catch (IOException e) {
            e.printStackTrace();
        }

        textView = findViewById(R.id.textView);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readRFiID();
            }
        });
    }


    private void readRFiID() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    }

                    // TODO: 2018/7/18 ↓↓↓↓↓ Condition 'success' is always 'false' ↓↓↓↓↓
                    // TODO: 2018/7/18 ↓↓↓↓↓ Condition 'success' is always 'false' ↓↓↓↓↓
                    // TODO: 2018/7/18 ↓↓↓↓↓ Condition 'success' is always 'false' ↓↓↓↓↓

                    boolean success = rc522.request();
                    if (!success) {
                        continue;
                    }
                    success = rc522.antiCollisionDetect();
                    if (!success) {
                        continue;
                    }
                    byte[] uid = rc522.getUid();
                    rc522.selectTag(uid);
                    break;
                }
                byte[] key = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
                byte[] newData = {0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
                byte block = Rc522.getBlockAddress(3, 2);
                boolean result = rc522.authenticateCard(Rc522.AUTH_A, block, key);
                if (!result) {
                    return;
                }
                result = rc522.writeBlock(block, newData);
                if (!result) {
                    return;
                }
                byte[] buffer = new byte[16];
                result = rc522.readBlock(block, buffer);
                if (!result) {
                    return;
                }
                rc522.stopCrypto();
                final String str = Rc522.dataToHexString(buffer);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText("Result:" + str);
                    }
                });
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (spiDevice != null) {
                spiDevice.close();
            }
            if (gpioReset != null) {
                gpioReset.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Getting this on a Raspberry Pi 3

Process: com.creoit.android.rfidtest, PID: 2743
java.lang.IncompatibleClassChangeError: Found interface com.google.android.things.pio.SpiDevice, but class was expected (declaration of 'com.google.android.things.pio.SpiDevice' appears in /system/framework/com.google.android.things.jar)
at com.galarzaa.androidthings.Rc522.initializePeripherals(Rc522.java:124)
at com.galarzaa.androidthings.Rc522.(Rc522.java:116)
at com.creoit.android.rfidtest.MainActivity.onCreate(MainActivity.kt:51)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Activity.performCreate(Activity.java:6991)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Can't able to Write

i've tried writing a card with write function but it is always getting failed. Please look at my code

            byte blockAddress = 4;
            byte dataBlock[]    = {
                    0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
                    0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
                    0x08, 0x09, (byte) 0xff, 0x0b, //  9, 10, 255, 12,
                    0x0c, 0x0d, 0x0e, 0x0f  // 13, 14,  15, 16
            };
            if (mRrc522.write(blockAddress, dataBlock)) {
                mTag.setVisibility(View.VISIBLE);
                mTag.setText("SUCCESS");
            } else {
                mTag.setVisibility(View.VISIBLE);
                mTag.setText("FAIL");
            }

App not installed!

Hi
After execute: "there was a problem parsing the package!!!"
We compiled in android studio 2.3.3

Thanks.

Write String

Hi,
how do i write a String on the Tag? Do i have to split my String into 16 bytes arrays and write them to different sectors?
When i write at the first sector, an app on my android smartphone cannot read the written data on the tag, why?

Enabling SPI1

How were you able to enable SPI1.? on raspberry pi 3 with Android things?

For me it only supports SPI0

UID is different

Hi,
i'm using MIFARE Classic 1k cards. When I try to read the UID of the Tag, then I get a different ID than in other Projects with the same card.
I convert the Bytearray to a String using this function:

final protected static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    private String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        int v;
        for ( int j = 0; j < bytes.length; j++ ) {
            v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

The correct UID is: DD17380A but I get DD17380AF8.
The same with another Tag:
DB96007D -> DB96007D30

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.