def __init__(self, ip=None, port=None): GPIO.cleanup() self.reader = RFID() self.ip = "localhost" if ip == None else ip self.port = "9004" if port == None else port self.ip_str = "ws://" + str(self.ip) + ":" + str(self.port) + "/ws" self.queue = queue.Queue() try: self.web_socket = web_socket(url=self.ip_str #queue = self.queue ) self.web_socket.start() except Exception as e: raise Exception(e) try: self.util = self.reader.util() self.util.debug = True except Exception as e: if not self.reader == None: try: self.reader.cleanup() except Exception as e: raise Exception(e) raise Exception(e) Thread.__init__(self) self.start()
def main(): client = mqtt_init() try: client.connect(HOST, PORT, 60) except socket.error as err: LOG(err) sys.exit(1) client.loop_start() reader = RFID() try: last_uid_str = None last_time = 0 while True: uid_str = rfid_read(reader) td = time.time() - last_time if uid_str: if (uid_str != last_uid_str) or (td > 1): last_uid_str = uid_str client.publish( EVENT_TOPIC, uid_str, qos=1, retain=False) time.sleep(0.1) last_time = time.time() except KeyboardInterrupt: LOG("KeyboardInterrupt") finally: reader.cleanup() client.publish( STATUS_TOPIC, "rc522 dead", qos=1, retain=True) client.disconnect() sys.exit(0)
class Rfid(Thread): def __init__(self, stop_event): Thread.__init__(self) firebase = pyrebase.initialize_app(FIREBASE_CONFIG) self.db = firebase.database() self.stop_event = stop_event self.logger = libs.logger.get_logger(__name__) self.rdr = RFID() def run(self): self.logger.info("Starting RFID scanner") while (not self.stop_event.is_set()): (error, data) = self.rdr.request() if not error: (error, uid) = self.rdr.anticoll() if not error: mifareUID = Rfid.mifareDataToInt(uid) self.db.child("screens").child(SCREEN_ID).child( "mifare").set(mifareUID) self.db.child("screens").child(SCREEN_ID).child( "identification").set("mifare") self.logger.info("Mifare: %d" % (mifareUID)) self.stop_event.wait(1) self.rdr.cleanup() @staticmethod def mifareDataToInt(data): return struct.unpack("I", bytearray(data[:4]))[0]
class RfidListener: def __init__(self, debug=False): self.lifx = Lifx(1) self.rdr = RFID() self.util = self.rdr.util() self.util.debug = debug self.DEFAULT_KEY = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] with open('./.keys') as fyl: line1 = fyl.readline().strip() line2 = fyl.readline().strip() self.keyA = tuple([x for x in bytes.fromhex(line1)]) self.keyB = tuple([x for x in bytes.fromhex(line2)]) def listen(self): while True: # Wait for tag self.rdr.wait_for_tag() # Request tag (error, data) = self.rdr.request() if not error: (error, uid) = self.rdr.anticoll() if not error: print(uid) if (uid == [43, 107, 171, 33, 202]): self.lifx.toggle_power() sleep(2)
class RfidReader(UsesLock): RFID_ERR_CODE = 228 TIMEOUT_CODE = 42 def __init__(self, lock: Lock): super().__init__(lock) logger.debug('init RFID module') self.rdr = RFID(pin_rst=1, pin_irq=0, pin_mode=GPIO.BCM) logger.debug('(DONE) init RFID module') @logger_wraps() def wait_card(self): err = 1 uid = [] # i = 0 try: while err: _ = time.clock() with self.acquire_lock(): (err, tt) = self.rdr.request() if not err: (err, uid) = self.rdr.anticoll() logger.debug(f'rfid found card: {tt} with error {err}') if tt is not None: return err, uid logger.debug( 'rfid read took: {} seconds'.format(time.clock() - _), 'debug') """ i += 1 if i % 60 == 0: # HACK: periodically reset RFID rfid_reset(rdr) i = 0 """ time.sleep(1) return err, uid except: logger.critical("error in rfid module: {}".format( str(sys.exc_info()))) return self.RFID_ERR_CODE, uid @logger_wraps() def rfid_cleanup(self): try: self.rdr.cleanup() logger.info('done') except: logger.error("rfid cleanup error: {}".format(str(sys.exc_info()))) @logger_wraps() def rfid_reset(self, rfid: RFID): # See: https://github.com/mxgxw/MFRC522-python/blob/master/MFRC522.py COMMAND_REG = 0x01 PCD_RESETPHASE = 0x0F with self.acquire_lock(): rfid.dev_write(COMMAND_REG, PCD_RESETPHASE) time.sleep(1) rfid.init()
def __init__(self, stop_event): Thread.__init__(self) firebase = pyrebase.initialize_app(FIREBASE_CONFIG) self.db = firebase.database() self.stop_event = stop_event self.logger = libs.logger.get_logger(__name__) self.rdr = RFID()
def __init__(self, callback_new_rfid_fn): 'Set up RFID reader' self.rdr = RFID(bus=1, device=0, pin_ce=12, pin_irq=32, pin_rst=15) util = self.rdr.util() util.debug = True self.callbackfn = callback_new_rfid_fn # call this function with a RFIDCard() on new card detected # TODO: use kivy events https://kivy.org/docs/guide/events.html self.last_card = None # to filter out duplicates
def rfid_reset(self, rfid: RFID): # See: https://github.com/mxgxw/MFRC522-python/blob/master/MFRC522.py COMMAND_REG = 0x01 PCD_RESETPHASE = 0x0F with self.acquire_lock(): rfid.dev_write(COMMAND_REG, PCD_RESETPHASE) time.sleep(1) rfid.init()
def __init__(self): self.__rdr = RFID(pin_mode=RPi.GPIO.BCM, pin_irq=24, pin_rst=25) self.__util = self.__rdr.util() if logging.getLogger().isEnabledFor(logging.DEBUG): self.__util.debug = True self.__tag_key = get_tag_key()
def Init(): # Hook the SIGINT GPIO.setmode(GPIO.BOARD) signal.signal(signal.SIGINT, end_read) # Create an object of the class MFRC522 # MIFAREReader = MFRC522.MFRC522() run = True rdr = RFID() util = rdr.util() util.debug = True
def __init__(self): # Since gpiozero uses BCM pin numbering, tell RFID to use that too, # and configure the pins as listed at https://github.com/ondryaso/pi-rc522 self.__rdr = RFID(pin_mode=RPi.GPIO.BCM, pin_irq=24, pin_rst=25) self.__util = self.__rdr.util() if logging.getLogger().isEnabledFor(logging.DEBUG): self.__util.debug = True self.__tag_key = get_tag_key()
def connect_sync(self): self.rdr = RFID(self.port.get(), output_func=self.output) if self.rdr.connected: self.util = self.rdr.util() self.util.debug = True self.toolbar_state('connected') self.output("Ready!") else: self.rdr = None self.toolbar_state('disconnected')
class RFID_util(): def __init__(self, read_queue, command_queue): self.reader = RFID() self.util = self.reader.util() self.run = True self.id_queue = read_queue self.cmd_queue = command_queue def end_read(self, signal, frame): global run self.run = False self.reader.cleanup() sys.exit() #read_while: polling loop with rfid device #will check write queue and when non empty, #will execute write of queue item instead of #reading. def read_while(self): while self.run: self.reader.wait_for_tag() (error, data) = self.reader.request() if not error: print("\nDetected: " + format(data, "02x")) (error, uid) = self.reader.anticoll() if not error: #set card uid for util self.util.set_tag(uid) #we need keys for each keychain, either default at 0xFF or store in db self.util.auth(self.reader.auth_a, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) self.util.do_auth(self.util.block_addr(2, 1)) #since this is where we auth'd block = 9 #check if theres a write command that needs attention if not self.cmd_queue.empty(): self.reader.write(block, self.cmd_queue.get()) print("tag written") else: (error, data) = self.reader.read(block) if not error: #print(data) self.id_queue.put(data) else: print("RFID read error, try again") time.sleep(3) self.util.deauth()
def __init__(self, debug=False): self.lifx = Lifx(1) self.rdr = RFID() self.util = self.rdr.util() self.util.debug = debug self.DEFAULT_KEY = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] with open('./.keys') as fyl: line1 = fyl.readline().strip() line2 = fyl.readline().strip() self.keyA = tuple([x for x in bytes.fromhex(line1)]) self.keyB = tuple([x for x in bytes.fromhex(line2)])
class FloppyReader(PublishSubscribeClientService): def __init__(self, *args, **kwargs): super(FloppyReader, self).__init__(*args, **kwargs) self.latest_reads = [] self.rst_pin_cycle = [] self.current_rst_pin_index = -1 GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) for pin in self.node_params['rst_pins']: self.latest_reads.append(None) self.rst_pin_cycle.append(pin) GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW) self.rc522_reader = RFID() read_loop = LoopingCall(self.cyclic_read) read_loop.start(1 / 100) reactor.addSystemEventTrigger('before', 'shutdown', GPIO.cleanup) def cycle_rst_pin(self): self.current_rst_pin_index = (self.current_rst_pin_index + 1) % len( self.rst_pin_cycle) return self.rst_pin_cycle[self.current_rst_pin_index] def cyclic_read(self): current_rst_pin = self.cycle_rst_pin() GPIO.output(current_rst_pin, GPIO.HIGH) self.rc522_reader.init() request_error, _ = self.rc522_reader.request() if request_error: self.read_callback(self.current_rst_pin_index, None) else: anticoll_error, nfc_uid = self.rc522_reader.anticoll() if anticoll_error: self.read_callback(self.current_rst_pin_index, None) else: self.read_callback(self.current_rst_pin_index, nfc_uid) GPIO.output(current_rst_pin, GPIO.LOW) def read_callback(self, reader_index, nfc_uid): if self.latest_reads[reader_index] != nfc_uid: self.latest_reads[reader_index] = nfc_uid logger.info("reader_index={}, nfc_uid={}".format( reader_index, nfc_uid))
def unseal(ctx): address = ctx.obj['address'] rdr = RFID() util = rdr.util() try: while True: print("Place next tag") rdr.wait_for_tag() (error, tag_type) = rdr.request() if not error: (error, uid) = rdr.anticoll() if not error: print("Tag detected with UID: " + str(uid[0]) + "-" + str(uid[1]) + "-" + str(uid[2]) + "-" + str(uid[3])) util.set_tag(uid) util.auth(rdr.auth_a, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) block = 4 key = '' error = False for s in range(5): if (block + 1) % 4 == 0: block += 1 util.do_auth(block) error, data = rdr.read(block) if error: break else: key += bytes(data).decode() block += 1 if error: print("Error, try again!") time.sleep(2) continue payload = {'key': key.rstrip('\x00')} progress = json.loads( requests.put(address + '/v1/sys/unseal', data=json.dumps(payload)).text) if not progress["sealed"]: print("Vault is unsealed!") break time.sleep(2) except Exception as e: print('Operation failed!') print('Exception message: ' + str(e)) exit(1) except KeyboardInterrupt: print('KeyboardInterrupt') exit(0) finally: rdr.cleanup() util.deauth()
class RFIDReader: # The 2.8TFT uses the hardware SPI pins (SCK, MOSI, MISO, CE0, CE1), #25 and #24. # buttons: #23, #22, #27/#21, and #18 # # Thus, we need to set up the rc522 RFID reader on SPI1, and on unused pins # SDA = BOARD12 # SCK = BOARD40 # MOSI = BOARD38 # MISO = BOARD35 # IRQ = BOARD32 # RST = BOARD15 # self.rdr = RFID(bus=1, device=0, pin_ce=12, pin_irq=32, pin_rst=15) def __init__(self, callback_new_rfid_fn): 'Set up RFID reader' self.rdr = RFID(bus=1, device=0, pin_ce=12, pin_irq=32, pin_rst=15) util = self.rdr.util() util.debug = True self.callbackfn = callback_new_rfid_fn # call this function with a RFIDCard() on new card detected # TODO: use kivy events https://kivy.org/docs/guide/events.html self.last_card = None # to filter out duplicates def on_stop(self): #Logger.debug("on_stop") self.rdr.cleanup() def card_detected(self, uid): 'Is run on each card detected' if uid == self.last_card: # duplicate return self.last_card = uid self.callbackfn(RFIDCard(uid)) def update(self, dt): 'check if we have a new card nearby. Run this periodically' #Logger.info("wating fir tag, %r", dt) (error, data) = self.rdr.request() if not error: Logger.debug("Detected RFID: %s", format(data, "02x")) (error, uid) = self.rdr.anticoll() if error: Logger.error("Error reading RFID: %r <UID: %r>", error, uid) else: Logger.debug("Card read UID: " + str(uid[0]) + "," + str(uid[1]) + "," + str(uid[2]) + "," + str(uid[3])) self.card_detected(uid)
class RfidReader(Thread): def __init__(self): Thread.__init__(self) self.rdr = RFID_driver() self.signal = None self.callback = None self.stop_flag = Event() self.identical_tag_delay = 2 #s self.last_detection_tag = None self.last_detection_tag = time.time() def run(self): while self.stop_flag.is_set() is False: # Wait for tag self.rdr.wait_for_tag() # Analyse tag valid_tag = False (error, tag_type) = self.rdr.request() if not error: (error, tag) = self.rdr.anticoll() if not error: tag = int(''.join([str(i) for i in tag])) if tag != self.last_detection_tag: valid_tag = True else: if (time.time() - self.last_detection_time ) > self.identical_tag_delay: valid_tag = True # Action if valid_tag is True: self.last_detection_tag = tag self.last_detection_time = time.time() if self.callback is not None: self.callback(tag) if self.signal is not None: self.signal.emit(str(tag)) else: time.sleep(0.2) def stop(self): self.stop_flag.set()
def clickRFID(self): run = True rdr = RFID() # util = rdr.util() # util.debug = True print("Starting") while run: self.textEdit_rfid.clear() rdr.wait_for_tag() print("แท๊กบัตรเลย") (error, data) = rdr.request() if not error: print("\nDetected: " + format(data, "02x")) (error, uid) = rdr.anticoll() if not error: # print("Card read UID: " + str(uid[0]) + "," + str(uid[1]) + "," + str(uid[2]) + "," + str(uid[3])) # print("Setting tag") # util.set_tag(uid) # print("\nAuthorizing") # # util.auth(rdr.auth_a, [0x12, 0x34, 0x56, 0x78, 0x96, 0x92]) # util.auth(rdr.auth_b, [0x74, 0x00, 0x52, 0x35, 0x00, 0xFF]) # print("\nReading") # util.read_out(4) # print("\nDeauthorizing") # util.deauth() fullUID = str(uid[0]) + str(uid[1]) + str(uid[2]) + str(uid[3]) print("FullUID :: " + fullUID) self.textEdit_rfid.insertPlainText(fullUID) run = False rdr.cleanup()
def __init__(self, emscene, player): """ Constructor :param emscene: Emma Music Player UI Scene :param player: Lockable MPDClient Instance """ self.emscene = emscene self.player = player self.rdr = RFID( dev='/dev/spidev1.0', pin_rst=37 ) #requires /boot/config.txt modification: dtparam=spi=on dtoverlay=spi1-1cs,cs0_pin=16 self.terminated = False
class RFIDReader(): """Simple RFID Reader running in a thread""" def __init__(self, emscene, player): """ Constructor :param emscene: Emma Music Player UI Scene :param player: Lockable MPDClient Instance """ self.emscene = emscene self.player = player self.rdr = RFID( dev='/dev/spidev1.0', pin_rst=37 ) #requires /boot/config.txt modification: dtparam=spi=on dtoverlay=spi1-1cs,cs0_pin=16 self.terminated = False def terminate(self): """ Stop this thread :return: """ self.terminated = True self.rdr.cleanup() def __call__(self): """ Thread main loop :return: """ while not self.terminated: # Read channel 0 in single-ended mode using the settings above (error, data) = self.rdr.request() if not error: logger.debug("\nDetected: " + format(data, "02x")) (error, uid) = self.rdr.anticoll() if not error: logger.debug("Card read UID: " + str(uid[0]) + "," + str(uid[1]) + "," + str(uid[2]) + "," + str(uid[3])) self.player.play( str(uid[0]) + "." + str(uid[1]) + "." + str(uid[2]) + "." + str(uid[3])) time.sleep(1.0) time.sleep(0.1)
def __init__(self): self.gymgate_repository = gymgate_repository.GymgateRepository() self.is_running = True self.RFID = RFID(bus=0, device=1) self.display = Display() self.servo = Servo(GPIO) self.LED_green = LED(GPIO, 40) self.LED_red = LED(GPIO, 12) signal.signal(signal.SIGINT, self.close_program) print("Gymgate scanner") print("Press Ctrl-C to stop.") self.start_program()
def __init__(self): self.run_flag = True self.rdr = RFID() self.util = self.rdr.util() self.util.debug = True self.fifo = [] self.db =\ {\ (0,0,0,0,0):'Error',\ (70,57,222,19,178):'Alice',\ (70,131,51,20,226):'Bob',\ (121,75,196,197,51):'Ark',\ (99,199,196,197,165):'Eve'\ } signal.signal(signal.SIGINT, self.end_read)
def __init__(self): """ Constructor. """ self.logger = logging.getLogger(self.__class__.__name__) self.initialised = False self.activated = False self.wake_event = threading.Event() self.done_event = threading.Event() self.runner = threading.Thread(target=self.do, args=( self.wake_event, self.done_event, )) self.runner.do_run = False self.rc522 = RFID()
def __init__(self, callback=None, pinRst=15, pinCe=24, pinIrq=13, pinMode=GPIO.BOARD, key=[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], keyName='A', bus=0, device=0, speed=1000000): self._callback = callback self._currentCard = None logging.debug("Listening for RFID card with pins: rst=%d, ce=%d, irq=%d" % (pinRst, pinCe, pinIrq)) logging.debug("RFID key %s is %s" % (keyName, arrayToHexString(key))) self._rfid = RFID(bus, device, speed, pinRst, pinCe, pinIrq, pinMode) self._rfidUtil = self._rfid.util() self.__key = key self.__keyName = keyName #self._rfidUtil.debug = True self._currentCardLock = RLock() self.__stopThread = Event() self.__thread = Thread(target=self._readRfids, name="RfidReader._readRfids") self.__thread.start()
def generate_root(ctx): address = ctx.obj['address'] rdr = RFID() util = rdr.util() try: attempt_result = requests.put(address + '/v1/sys/generate-root/attempt') attempt_object = json.loads(attempt_result.text) nonce = attempt_object["nonce"] progress = None while True: print("Place next tag") rdr.wait_for_tag() (error, tag_type) = rdr.request() if not error: (error, uid) = rdr.anticoll() if not error: print("Tag detected with UID: " + str(uid[0]) + "-" + str(uid[1]) + "-" + str(uid[2]) + "-" + str(uid[3])) util.set_tag(uid) util.auth(rdr.auth_a, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) block = 4 key = '' error = False for s in range(5): if (block + 1) % 4 == 0: block += 1 util.do_auth(block) error, data = rdr.read(block) if error: break else: key += bytes(data).decode() block += 1 if error: print("Error, try again!") time.sleep(2) continue payload = {'key': key.rstrip('\x00'), 'nonce': nonce} update_result = requests.put( address + '/v1/sys/generate-root/update', data=json.dumps(payload)) progress = json.loads(update_result.text) if progress["complete"] == True: break print("Root token generation complete, to get the decoded token run:") print(" vault operator generate-root -decode=" + progress["encoded_root_token"] + " -otp=" + attempt_object["otp"]) except Exception as e: print('Operation failed!') print('Exception message: ' + str(e)) print('The root token generation process will be reset') requests.delete(address + '/v1/sys/generate-root/attempt') exit(1)
def detect_rfid(self): if self.rdr is None: self.rdr = RFID() util = self.rdr.util() # Wait for tag self.rdr.wait_for_tag() # Request tag (error, data) = self.rdr.request() if error: return 'on Err ' + str(error) (error, uid) = self.rdr.anticoll() if error: return 'on Err ' + str(error) uidstr = ("[%s,%s,%s,%s]" % (str(uid[0]), str(uid[1]), str(uid[2]), str(uid[3]))) return 'OK ' + uidstr
class Reader: def __init__(self): self.reader = RFID() def reset(self): self.reader = RFID() def get(self): error, data = self.reader.request() if error: return None error, uid = self.reader.anticoll() if error: return None return ''.join('{:02x}'.format(byte) for byte in uid[:4])
def detect(): #ledpin = 7 #gpio4 #buzzerpin = 15 #gpio22 #GPIO.setmode(GPIO.BOARD) #GPIO.setup(ledpin, GPIO.OUT) #GPIO.setup(buzzerpin, GPIO.OUT) rdr = RFID() util = rdr.util() util.debug = True print("Waiting for Tag...") rdr.wait_for_tag() (error, data) = rdr.request() if not error: print("Tag Detected!") (error, uid) = rdr.anticoll() if not error: #GPIO.output(ledpin, GPIO.HIGH) #GPIO.output(buzzerpin, GPIO.HIGH) #wait 0.1 seconds #time.sleep(100) #GPIO.output(ledpin, GPIO.LOW) #GPIO.output(buzzerpin, GPIO.LOW) kart_uid = str(uid[0]) + " " + str(uid[1]) + " " + str( uid[2]) + " " + str(uid[3]) + " " + str(uid[4]) print(kart_uid) return kart_uid
def main(): import time import RPi.GPIO RPi.GPIO.setwarnings(False) from pirc522 import RFID RFID = RFID rdr = RFID() util = rdr.util() while True: error, data = rdr.request() error, uid = rdr.anticoll() if not error: break time.sleep(0.5) return uid
#!/usr/bin/env python import signal import time import sys from pirc522 import RFID run = True rdr = RFID() util = rdr.util() util.debug = True def end_read(signal,frame): global run print("\nCtrl+C captured, ending read.") run = False rdr.cleanup() sys.exit() signal.signal(signal.SIGINT, end_read) print("Starting") while run: rdr.wait_for_tag() (error, data) = rdr.request() if not error: print("\nDetected: " + format(data, "02x")) (error, uid) = rdr.anticoll()
#!/usr/bin/env python import signal import time from pirc522 import RFID rdr = RFID() util = rdr.util() # Set util debug to true - it will print what's going on util.debug = True while True: # Wait for tag rdr.wait_for_tag() # Request tag (error, data) = rdr.request() if not error: print("\nDetected") (error, uid) = rdr.anticoll() if not error: # Print UID print("Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3])) # Set tag as used in util. This will call RFID.select_tag(uid) util.set_tag(uid) # Save authorization info (key B) to util. It doesn't call RFID.card_auth(), that's called when needed util.auth(rdr.auth_b, [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]) # Print contents of block 4 in format "S1B0: [contents in decimal]". RFID.card_auth() will be called now