Beispiel #1
0
def main():
    # Instantiate reader
    mifare = nxppy.Mifare()
    # dict with presence signed in
    registro = {}
    while True:
        try:
            # Select tag
            uid = mifare.select()
            # Read NDEF data
            ndef_data = mifare.read_ndef()
            # Parse NDEF data
            ndef_records = list(ndef.message_decoder(ndef_data))
            print(ndef_records)
            stringa = str(ndef_records[0])
            code = code_finder(stringa, 5)
            print(code)
            current_time = time.strftime("%d-%m-%Y %H:%M:%S", time.gmtime())
            print(current_time)
            if code not in registro:
                registro[code] = current_time
        except nxppy.SelectError:
            # SelectError is raised if no card is in the field.
            pass

        print(registro)
        time.sleep(3)
Beispiel #2
0
    def __init__(self):
        try:
            self.mifare = nxppy.Mifare()
        except SystemError:
            import mock_nxppy

            self.mifare = mock_nxppy.Mifare()
Beispiel #3
0
def lectureCarte():
    """Fonction qui renvoie l'UID de la carte ou None si aucune carte n'est présente"""
    mifare = nxppy.Mifare(
    )  #Création d'un objet Mifare permettant la lecture NFC
    try:
        uid = mifare.select()  #Détection de la carte
        return str(uid)
    except nxppy.SelectError:  #Erreur levée lorque aucune carte n'est présenté
        return None
Beispiel #4
0
 def test_detect_mifare_absent(self):
     """Test that an absent card results in a None response.
     
     Either this test or the "present" test above will pass, but never both.
     """
     import nxppy
     reader = nxppy.Mifare()
     self.assertIsInstance(reader, nxppy.Mifare)
     self.assertIsNone(reader.select(), "Card UID is not None")
Beispiel #5
0
 def test_detect_mifare_present(self):
     """Test that we can read the UID from a present Mifare card.
     
     Either this test or the "absent" test below will pass, but never both.
     """
     import nxppy
     reader = nxppy.Mifare()
     self.assertIsInstance(reader, nxppy.Mifare)
     self.assertIsInstance(reader.select(), str, "Card UID is not a string")
def get_card_id():
    '''Checks the NXP nfc card reader for a card identity'''
    mifare = nxppy.Mifare()
    while True:
        try:
            cardid = mifare.select()
            if cardid is not None:
                return cardid
        except nxppy.SelectError:
            pass
Beispiel #7
0
 def __init__(self, wuInterval, syncInterval, pollInterval):
     self.wuInterval = wuInterval
     self.syncInterval = syncInterval
     self.pollInterval = pollInterval
     self.mifare = nxppy.Mifare()
     self.armed = 0
     self.alarmDevices = HCL_ALARM_DEVICES
     self.allDevices = HCL_ALL_DEVICES
     GP.setwarnings(False)
     GP.setmode(GP.BOARD)
     GP.setup(11, GP.OUT)
     GP.output(11, False)
Beispiel #8
0
def RFIDManager():
    print("YEAH BABY")
    tancar()
    stopped = threading.Event()
    mifare = nxppy.Mifare()
    while not stopped.wait(0.1):
        try:
            uid = mifare.select()
            print(uid)
            if (uid == '2118140B'):
                obrir()
                time.sleep(2)
                tancar()
        except nxppy.SelectError:
            pass
Beispiel #9
0
def getNFCTag():
    print('NFC TAG')
    mifare = nxppy.Mifare()

    # Print card UIDs as they are detected
    while True:
        try:
            uid = mifare.select()
            print(uid)
            return uid
        except nxppy.SelectError:
            # SelectError is raised if no card is in the field.
            # print('nxppy.SelectError')
            pass
        time.sleep(1)
Beispiel #10
0
def scan_card():

	"""Return the uid and NDEF card as a response for jsonify and Flask API."""

	# Instantiate reader
	mifare = nxppy.Mifare()
	
	try:
		# Select tag
		uid = mifare.select()
	
		# Print card UIDs as they are detected

		if len(uid) == 8:
			
			try:
				# mifare classic not implemented in nxppy
				# can detect uid
				# requirement to authenticate for read / write access
				return {"uid":uid, "text":"", "status":"success"}


			except nxppy.ReadError:
				return {"error": "cannot read data"}

		if len(uid) == 14:
			try:
				# Read NDEF data
				ndef_data = mifare.read_ndef()
				
				# print(ndef_data)
				
				# Parse NDEF data
				ndef_records = list(ndef.message_decoder(ndef_data))	
				
				record = ndef_records[0]
						
				return {"uid":uid, "text":record.text, "status":"success"}
				
			except nxppy.ReadError:
				return {"error": "cannot read ndef_data"}	
		
			
	except nxppy.SelectError:
		# SelectError is raised if no card is in the field.
		return {"error": "card not found"}
Beispiel #11
0
def main():
    mifare = nxppy.Mifare()

    while True:
        try:
            uid = mifare.select()
            print(uid)
            ndef_data = mifare.read_ndef()
            print(ndef_data[4:])
            data = json.loads(ndef_data[4:])
            check_booking(data)
        except nxppy.SelectError:
            pass
        except MemoryError:
            print('Could not read chip')
            pass
        except ValueError:
            print('Could not parse data from JSON')
            pass
        time.sleep(1)
Beispiel #12
0
    def start_scanner(self):
        print("Ready to scan")
        hasScanned = False
        bb = nxppy.Mifare()
        while not hasScanned:
            try:

                uid = bb.select()
                if uid:
                    print("id: " + str(uid))
                    hasScanned = True
                    if self.isAlowedToEnter(uid):
                        self.currUID = uid
                        self.stm.send('card_valid')

                    else:
                        self.stm.send('card_invalid')
                    return
            except nxppy.SelectError:
                pass
            time.sleep(1)
Beispiel #13
0
    def _read_card_thread(self):
        import nxppy
        mifare = nxppy.Mifare()

        while self._running:
            try:
                time.sleep(0.1)
                read_card_id = mifare.select()
            except nxppy.SelectError:
                read_card_id = None

            if time.time(
            ) - self._last_seen_timestamp > self.config.card_associate_login_timeout:
                # Reset last seen state if timeout occurred
                self._last_seen_id = None
                self._last_fetched_id = None
            if read_card_id is not None and self._last_seen_id != read_card_id:
                # Save the read card data if different
                self._last_seen_id = read_card_id
                self._last_fetched_id = read_card_id.hex()
                self._last_seen_timestamp = time.time()
Beispiel #14
0
def indexPage():
    print('NFC TAG')
    mifare = nxppy.Mifare()

    # Print card UIDs as they are detected
    while True:
        try:
            nfcid = mifare.select()
            print(nfcid)
            user = dao.query(User).filter(User.nfcid == nfcid).first()
            if user is None:
                raise NoneUserName
            new_access = Access(user.name, user.nfcid)
            dao.add(new_access)
            dao.commit()
            print(new_access.name + " Access")
        except NoneUserName as e:
            print(e)
        except nxppy.SelectError:
            # SelectError is raised if no card is in the field.
            # print('nxppy.SelectError')
            print('NFC Tag를 접촉해주세요')
        time.sleep(1)
import nxppy
import time
import json
import urllib.request
import datetime
import os.path
import RPi.GPIO as GPIO

# Make sure this points towards your own hosted API
url = "http://192.168.1.10:58938/api/Terminal"

card = nxppy.Mifare()
bool = 'false'  # json returns a string

currentCard = 'none'

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)


# pin = pin number based on the board (pin40 = gpio pin 21 etc.)
def singleBlinkLed(pin, timer):
    GPIO.setup(pin, GPIO.OUT)
    GPIO.output(pin, 1)
    time.sleep(timer)
    GPIO.output(pin, 0)
    time.sleep(timer)


def duoBlinkLed(pin1, pin2, timer):
    GPIO.setup(pin1, GPIO.OUT)
Beispiel #16
0
import nxppy

try:
    print nxppy.Mifare().select()
except:
    # We do not care
    pass
Beispiel #17
0
'''
Variabili globali
'''
# istanza base di tkinter (manca settare le dimensioni e la posizione centrale del label)
text_waiting = "Appoggiare badge sul lettore..."
text_succeed = "Ingresso confermato!"
label = tk.Label(window,
                 fg="blue",
                 bg="white",
                 height="30",
                 font=("Courier", 30))
#label['text'] = text_waiting
label.pack()
#label.grid(row=0,column=0)

mifare = nxppy.Mifare()  #istanza del reader
registro = {}  #dizionario che contiene i valori registrati
''' ESEMPIO DI UTILIZZO
def task():
	global text1
	global text2
	global counter
	label1 = tk.Label(window,text=text1,fg="black")
	label2 = tk.Label(window,text=text2,fg="white")
	label1.grid(row=0,column=0)
	label2.grid(row=0,column=1)
	if counter % 2 == 0:
		#mostro text1
		label1.config(fg="black")
		label2.config(fg="white")
	else:
Beispiel #18
0
 def __init__(self):
     self.mifare = nxppy.Mifare()
Beispiel #19
0
import nxppy
import time
import paho.mqtt.client as mqtt

mifare = nxppy.Mifare()


def on_connect(client, userdata, flags, rc):
    print("Connected")


def on_disconnect(client):
    print("Disconnected")


mqttsender = mqtt.Client('marconfc')
mqttsender.on_connect = on_connect
mqttsender.on_disconnect = on_disconnect
mqttsender.connect('localhost', 1883)

# Print card UIDs as they are detected
while True:
    try:
        uid = mifare.select()
        print(mqttsender.publish('/nfc/cardnumber', uid))
    except nxppy.SelectError:
        # SelectError is raised if no card is in the field.
        pass
    mqttsender.loop()
    time.sleep(1)
Beispiel #20
0
def raspberry_explorer_board():

    logger = Logger().getLogger()
    config = Configuration()
    # Connect to MPD
    client = MPDClient() 
    client.connect("localhost", int(config.iniFile.get('mpd','port')))

    # Connect to NFC Explorer board
    logger.info('Connect to nxppy Mifare')
    mifare = nxppy.Mifare()

    # Initialize storage
    logger.info('Connect to Redis')
    storage = redis.StrictRedis(host='localhost', port=int(config.iniFile.get('redis','port')), db=0)

    # Count pauses to make sure it is not a error reading
    nbPause = 0
    # Keep previous uid to compare with current one
    previous_uid = None
    # Data from taf
    data = None

    if mifare is None:
        logger.info("Error while loading NFC Explorer Board")
    else:
        logger.info("Reader NFC Raspberry is now running")

        while True:
            try:
                uid = mifare.select()
                if uid is not None:
                    if uid == previous_uid:
                        nbPause = 0
                        if data:
                            status = client.status()
                            if status['state'] == 'stop':
                                logger.info("Play")
                                storage.set('current-tag-id', uid)
                                client.play(0)
                            if status['state'] == 'pause':
                                logger.info("Continue")
                                storage.set('current-tag-id', uid)
                                client.pause(0)
                        else:
                            pass
                    else:
                        previous_uid = uid

                        logger.info("New chip detected : %s" % uid)
                        # Save current-tag-id in memory to be used by services
                        storage.set('current-tag-id', uid)

                        # Stop mpd and 
                        client.stop()   
                        client.clear()

                        # Get from storage list of songs to play
                        tag = storage.get("tags:" + uid)

                        if tag is None:
                            logger.info("Unknown chip %s" % uid)
                            data = None
                        else:
                            # Load data
                            data = json.loads(tag)

                            logger.info(data)

                            # Configure MPD server
                            client.random(1 if data['random'] else 0)
                            client.repeat(1 if data['repeat'] else 0)

                            # Add songs
                            for song in data['songs']:
                                client.add(song)

                            if data['random']:
                                client.shuffle()

                            client.play(0)
                    
            except nxppy.SelectError:

                # Random error reading. Avoi
                if nbPause == 2:
                    nbPause = 0
                    # If play then 
                    if client.status()['state'] == 'play':
                        logger.info("Detect missing chip")
                        logger.info("Pause")
                        storage.delete('current-tag-id')
                        client.pause(1)
                    # If us
                    elif previous_uid and not data:
                        previous_uid = None
                        storage.delete('current-tag-id')
                else:
                    nbPause = nbPause + 1
            except Exception as e:
                logger.critical('Exception')
                logger.critical('%s' % str(e))