David Smerkous
Published © Apache-2.0

Linkit One Wireless RFID reader

Ultimate Wireless RFID with Wireless connections

IntermediateWork in progress3,050
Linkit One Wireless RFID reader

Things used in this project

Hardware components

MFRC522
×1
Jumper wires (generic)
Jumper wires (generic)
×1
Micro usb
×1

Story

Read more

Code

RFIDWireless4.2

C/C++
Upload this to the Link it one with the Debug port
//Libraries
#include <LTask.h>
#include <LWiFi.h>
#include <LWiFiClient.h>
#include <SPI.h>
#include <MFRC522.h>
//End Libraries

//Wireless
#define WIFI_AP "Your routers SSID"
#define WIFI_PASSWORD "Your routers Password"
#define IP "The Ip address of your router"
#define PORT 8080
#define WIFI_AUTH LWIFI_WPA
//End Wireless

//RFID
#define Reset_Pin 9
#define Slave_Select_Pin 8
#define times 5
//Bytes
byte sector = 0;
byte blockAddr = 0; //Access sectors within card
byte trailerBlock = 1;
//End Bytes
//End RFID

//Gui
#define red 3
#define blue 4
#define green 5
//End Gui

//Instances
MFRC522 mfrc522(Slave_Select_Pin, Reset_Pin);

MFRC522::MIFARE_Key key;
//End Instances

signed long timeout;

void setup() {
   pinMode(red, OUTPUT);
   pinMode(blue, OUTPUT); //Init the RGB LED
   pinMode(green, OUTPUT);
   Reset();
   digitalWrite(blue, LOW);
   digitalWrite(red, LOW);
  LWiFi.begin();
  Serial.begin(115200);
  while(!Serial);
  // keep retrying until connected to AP
  Serial.println("Connecting to AP");
  int timeouts = 0;
  while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD)) && timeouts < times)
  {
    delay(1000);
    timeouts++;
  }

  printWifiStatus();

  Serial.println("Started Wifi");
  SPI.begin();
  mfrc522.PCD_Init();
  
 for (byte i = 0; i < 6; i++) {   // Prepare the key (used both as key A and as key B)
  key.keyByte[i] = 0xFF;        // using FFFFFFFFFFFFh which is the default at chip delivery from the factory
  }
  
  dump_byte_array(key.keyByte, MFRC522::MF_KEY_SIZE);     //Get key byte size
  timeout = 0;
  delay(100);
  Reset();
  Serial.println("Start scanning a card");
  digitalWrite(blue, LOW);
  delay(500);
}

void loop() {
   // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
    {
        return;
    }
    Serial.println("Got a card");

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

        digitalWrite(blue, HIGH); //Show user that card has been read

    byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

    // Check for compatibility with Mifare card
    if (    piccType != MFRC522::PICC_TYPE_MIFARE_MINI
        &&  piccType != MFRC522::PICC_TYPE_MIFARE_1K
        &&  piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
        Error();
        return;
    }
    
  byte status;
  byte buffer[18];
  byte size = sizeof(buffer);


  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    Error();
    return;
  }

  
  // Read data from the block
  status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Read() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    Error();
  }
      // Halt PICC 
    mfrc522.PICC_HaltA();
    // Stop encryption on PCD
    mfrc522.PCD_StopCrypto1();
  String out = "";
  LWiFiClient client;
  client.connect(IP, PORT);
  while(0 == client.connected())
       delay(10);
  const String ID = dump_byte_array(buffer, size);
  client.println(ID);
  Serial.println("Sent: " + (String) ID);
  delay(50);
 while(0==client.available());
 
          int v;
          int sizes;
          
          while((sizes = client.available()) > 0)
            {
              int v = client.read();
              char f = (char)v;
              Serial.println("I got: " + (String) f);
              if((String)f == (String)"1")
              {
                    Pass();
              }
              else
              {
                    Error();
              }
              //free(msg);
            }
close:
          client.stop();
  Reset();
  digitalWrite(blue, LOW);
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(LWiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = LWiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  Serial.print("subnet mask: ");
  Serial.println(LWiFi.subnetMask());

  Serial.print("gateway IP: ");
  Serial.println(LWiFi.gatewayIP());

  // print the received signal strength:
  long rssi = LWiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

// TURN THE BUFFER ARRAY INTO A SINGLE STRING THAT IS UPPERCASE WHICH EQUALS OUR ID OF THE SECTOR AND BLOCK
String dump_byte_array(byte *buffer, byte bufferSize) {
          String out = "";
    for (byte i = 0; i < bufferSize; i++) {
        //Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        //Serial.print(buffer[i], HEX);
        out += String(buffer[i] < 0x10 ? " 0" : " ") + String(buffer[i], HEX);
    }
    out.toUpperCase();
    out.replace(" ", "");
    return out;
}
//END DUMP_BYTE_ARRAY

void Error()
{
  digitalWrite(red, LOW);
  delay(700);
  digitalWrite(red, HIGH);
}

void Pass()
{
  digitalWrite(green, LOW);
  delay(700);
  digitalWrite(green, HIGH);
}

void Reset()
{
   digitalWrite(red, HIGH);
   digitalWrite(blue, HIGH);
   digitalWrite(green, HIGH);
}

Server

C#
Use this on your computer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Net.Sockets;
using System.Configuration;


namespace LTS
{
    class DB
    {
        public static MySqlConnection getconn()
        {
            String connStr = "server=localhost;user=root;database=test;password=removekebab;";
            //String.Format(connStr, ConfigurationManager.AppSettings["mysql_user"], ConfigurationManager.AppSettings["mysql_db"], ConfigurationManager.AppSettings["mysql_pass"]);
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = connStr;
            conn.Open();
            if (conn != null)
            {
                Console.WriteLine(conn.ToString());
                return conn;
            }
            else
            {
                throw new SystemException();
            }
        }
    }
    class LTS
    {
        public bool is_initialized;
        int ID;
        string _first_name;
        string _last_name;
        string _notes;
        int _location;
        string _rfid;

        public LTS(int id)
        {
            this.ID = id;
            this.is_initialized = true;
        }

        public static LTS learner_from_rfid(string rfid)
        {
            var conn = DB.getconn();
            string query = "SELECT learner_id FROM learners WHERE rfid = @rfid";

            MySqlCommand cmd = new MySqlCommand(query, conn);
            cmd.Parameters.AddWithValue("@rfid", rfid);

            MySqlDataReader reader = cmd.ExecuteReader();
            Int64 id = -1;
            while (reader.Read()) { id = reader.GetInt64(0); }
            conn.Close();
            return new LTS((int)id);
        }

        public string first_name
        {
            get
            {
                MySqlConnection conn;
                string query;
                MySqlCommand cmd;
                string final;

                conn = DB.getconn();

                query = "SELECT first_name FROM learners WHERE learner_id = @id";
                cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);

                MySqlDataReader reader = cmd.ExecuteReader();
                // The reason i set final now is  that in case reader doesnt read
                final = "Didnt work";
                while (reader.Read()) { final = reader.GetString(0); }
                conn.Close();
                return final;
            }
            set
            {
                var conn = DB.getconn();

                string query = @"UPDATE learners
                                SET first_name = @new_name
                                WHERE learner_id = @id";

                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);
                cmd.Parameters.AddWithValue("@new_name", value);
                int status = cmd.ExecuteNonQuery();

                query = "SELECT first_name FROM learners WHERE learner_id = @id";
                cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);

                MySqlDataReader reader = cmd.ExecuteReader();
                string final = "Didnt work";
                while (reader.Read()) { final = reader.GetString(0); }
                conn.Close();
                this._first_name = final;
            }

        }
        public string last_name
        {
            get
            {
                var conn = DB.getconn();

                string query = "SELECT last_name FROM learners WHERE learner_id = @id";
                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);

                MySqlDataReader reader = cmd.ExecuteReader();
                string final = "Didnt work";
                while (reader.Read()) { final = reader.GetString(0); }
                conn.Close();
                return final;
            }
            set
            {
                var conn = DB.getconn();

                string query = @"UPDATE learners
                                SET last_name = @new_name
                                WHERE learner_id = @id";
                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);
                cmd.Parameters.AddWithValue("@new_name", value);

                int status = cmd.ExecuteNonQuery();
                query = "SELECT last_name FROM learners WHERE learner_id = @id";
                cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);

                MySqlDataReader reader = cmd.ExecuteReader();
                string final = "Didnt work";
                while (reader.Read()) { final = reader.GetString(0); }
                conn.Close();
                this._last_name = final;
            }

        }
        public string notes
        {
            get
            {
                var conn = DB.getconn();

                string query = "SELECT notes FROM learners WHERE learner_id = @id";
                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);

                MySqlDataReader reader = cmd.ExecuteReader();
                string final = "Didnt work";
                while (reader.Read()) {
                    try {
                        final = reader.GetString(0);
                    }
                    catch (System.Data.SqlTypes.SqlNullValueException e)
                    {
                        final = "";
                    }
                }
                conn.Close();
                return final;
            }
            set
            {
                var conn = DB.getconn();

                string query = @"UPDATE learners
                                SET notes = @new_notes
                                WHERE learner_id = @id";
                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);
                cmd.Parameters.AddWithValue("new_notes", value);

                query = "SELECT notes FROM learners WHERE learner_id = @id";
                cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);

                MySqlDataReader reader = cmd.ExecuteReader();
                string final = "Didnt work";
                while (reader.Read())
                {
                    try
                    {
                        final = reader.GetString(0);
                    }
                    catch (System.Data.SqlTypes.SqlNullValueException e)
                    {
                        final = "";
                    }
                }
                conn.Close();
                this._notes = final;
            }
        }
        public int location
        {
            get
            {
                var conn = DB.getconn();

                string query = "SELECT location FROM learners WHERE learner_id = @id";
                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);

                MySqlDataReader reader = cmd.ExecuteReader();
                Int64 final = -1;
                while (reader.Read()) { final = reader.GetInt64(0); }
                conn.Close();
                // I hope you dont overflow... That'd have to be a lot of locations tho
                return (int)final;
            }
            set
            {
                var conn = DB.getconn();

                string query = @"UPDATE learners
                                SET location = @new_location
                                WHERE learner_id = @id";
                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);
                cmd.Parameters.AddWithValue("new_location", value);

                int status = cmd.ExecuteNonQuery();

                query = "SELECT location FROM learners WHERE learner_id = @id";
                cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);

                MySqlDataReader reader = cmd.ExecuteReader();
                Int64 final = -1;
                while (reader.Read()) { final = reader.GetInt64(0); }
                conn.Close();
                // I hope you dont overflow... That'd have to be a lot of locations tho
                this._location = (int)final;
            }
        }
        public string rfid
        {
            get
            {
                var conn = DB.getconn();
                string query = "SELECT rfid FROM learners WHERE learner_id = @id";

                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);

                MySqlDataReader reader = cmd.ExecuteReader();
                string final = "Didnt work";
                while (reader.Read()) { final = reader.GetString(0); }
                conn.Close();
                return final;
        }
            set
            {
                var conn = DB.getconn();
                string query = @"UPDATE learners
                                SET rfid = @new_rfid
                                WHERE learner_id = @id";

                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);
                cmd.Parameters.AddWithValue("new_rfid", value);

                int status = cmd.ExecuteNonQuery();
                query = "SELECT rfid FROM learners WHERE learner_id = @id";

                cmd = new MySqlCommand(query, conn);
                cmd.Parameters.AddWithValue("@id", this.ID);

                MySqlDataReader reader = cmd.ExecuteReader();
                string final = "Didnt work";
                while (reader.Read()) { final = reader.GetString(0); }
                conn.Close();
                this._rfid = final;
            }
        }
    }
}


namespace Server
{
    class Program
    {
        public static void Logger(String lines)
        {

            System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\Users\\Visual Studio 2015\\Projects\\ConsoleApplication1\\logs\\logs.txt", true);
            file.WriteLine(lines);

            file.Close();
        }

        static void startTCP()
        {
            TcpListener server = new TcpListener(8080);
            TcpClient client = default(TcpClient);
            server.Start();
            Console.WriteLine("Server Started");
            while (true)
            {
                try
                {
                    client = server.AcceptTcpClient();
                    Console.WriteLine("\nAccepted Client Connection\n");
                    NetworkStream stream = client.GetStream();
                    byte[] bytesFrom = new byte[10025];
                    stream.Read(bytesFrom, 0, 32);
                    string FromClient = Encoding.ASCII.GetString(bytesFrom);
                    FromClient = FromClient.Substring(0, 32);
                    Console.WriteLine("\nGot data: " + FromClient + "\n");
                    Byte[] sendByte = Encoding.ASCII.GetBytes(received(FromClient));
                    stream.Write(sendByte, 0, sendByte.Length);
                    stream.Flush();
                    Console.WriteLine("\nSuccesfully sent state\n");
                    client.Close();
                    Console.WriteLine("\nClosing the Client\n");
                }
                catch (Exception error)
                {
                    string time = DateTime.Now.ToString("MM/dd/yyyy h:mm tt");
                    string errorstring = error.ToString();
                    string trace = error.StackTrace;
                    string errorlog = time + "-" + errorstring + "-" + trace;
                    Logger(errorlog);
                    Console.WriteLine("\nThere was an error:\n" + error.ToString() + "\n");
                }
            }
        }

        static String received(String rec)
        {
            Console.WriteLine("\nSQL collection started\n");
            LTS.LTS learner = LTS.LTS.learner_from_rfid(rec);
            learner.location = 3;
            Console.WriteLine("\nSQL collection done\n");
            return "1"; //This is what to send back either "0" or "1" notpass/pass
        }

        static void Main(string[] args)
        {
            var learner = LTS.LTS.learner_from_rfid("B0529B1168080400626364656667686991FD");
            Console.WriteLine(learner.first_name);
            Console.WriteLine(learner.last_name);
            learner.last_name = "Sworne";
            Console.WriteLine(learner.last_name);
            Console.ReadKey();

            startTCP();
        }
    }
}

Credits

David Smerkous

David Smerkous

8 projects • 87 followers
Currently an Artificial Intelligence Ph.D. student at Oregon State University. Long-time hardware enthusiast. Profile is old.
Thanks to Media Tek SDK and Miguel.

Comments