Esempio n. 1
0
def main(args):
    if args['--debug']:
        loglevel = logging.DEBUG - (1 if args['--verbose'] else 0)
        logging.getLogger("nfc.clf").setLevel(loglevel)
        logging.getLogger().setLevel(loglevel)

    try:
        try:
            waittime = float(args['--wait'])
        except ValueError:
            assert 0, "the '--wait T' argument must be a number"
        assert waittime >= 0, "the '--wait T' argument must be positive"
        try:
            timeout = float(args['--time'])
        except ValueError:
            assert 0, "the '--time T' argument must be a number"
        assert timeout >= 0, "the '--time T' argument must be positive"
    except AssertionError as error:
        print(str(error), file=sys.stderr)
        return 2

    try:
        clf = nfc.ContactlessFrontend(args['--device'])
    except IOError as error:
        print("no device found on path %r" % args['--device'], file=sys.stderr)
        return 3

    try:
        while True:
            try:
                target = None
                if args['tt2']: target = listen_tta(timeout, clf, args)
                if args['tt3']: target = listen_ttf(timeout, clf, args)
                if args['tt4']: target = listen_tta(timeout, clf, args)
                if args['dep']: target = listen_dep(timeout, clf, args)
                if target:
                    print("{0} {1}".format(time.strftime("%X"), target))
            except nfc.clf.CommunicationError as error:
                if args['--verbose']: logging.error("%r", error)
            except AssertionError as error:
                print(str(error), file=sys.stderr)
                return 2

            if args['--repeat']: time.sleep(waittime)
            else: return (0 if target else 1)

    except nfc.clf.UnsupportedTargetError as error:
        logging.error("%r", error)
        return 2

    except IOError as error:
        if error.errno != errno.EIO: logging.error("%r", error)
        else: logging.error("lost connection to local device")
        return 3

    except KeyboardInterrupt:
        pass

    finally:
        clf.close()
Esempio n. 2
0
def main(args):
    for device in args.device:
        try: clf = nfc.ContactlessFrontend(device); break
        except IOerror: pass
    else:
        log.error("no contactless reader found")
        raise SystemExit(1)

#    connected = clf.connect({'tag': {}})
#    if connected == 'tag':
#        nfc.tag.get_ndef()
#        while nfc.tag.connected():
#            sleep(0.1)

    while True:
        try:
            if args.mode is None or args.mode == "t":
                dta_lis_p2p(clf, args)                
            if args.mode is None or args.mode == "i":
                dta_pol_p2p(clf, args)
                #sleep(1)
        except KeyboardInterrupt:
            clf.close()
            raise SystemExit
    
    return
Esempio n. 3
0
def main(args):
    for device in args.device:
        try:
            clf = nfc.ContactlessFrontend(device)
            break
        except IOError:
            pass
    else:
        log.error("no contactless reader found")
        raise SystemExit(1)

#    connected = clf.connect({'tag': {}})
#    if connected == 'tag':
#        nfc.tag.get_ndef()
#        while nfc.tag.connected():
#            sleep(0.1)

    while True:
        try:
            if args.mode is None or args.mode == "t":
                dta_lis_p2p(clf, args)
            if args.mode is None or args.mode == "i":
                dta_pol_p2p(clf, args)
                # sleep(1)
        except KeyboardInterrupt:
            clf.close()
            raise SystemExit

    return
Esempio n. 4
0
 def run(self):
     try:
         clf = nfc.ContactlessFrontend('usb')
     except IOError as error:
         raise SystemExit(1)
     try:
         return clf.connect(rdwr={'on-connect': self.card_connected})
     finally:
         clf.close()
Esempio n. 5
0
	def read(self,web):
        # Seleccion de la interfaz con la que se leera la tarjeta
		clf = nfc.ContactlessFrontend("usb")                     
        # Seleccion del objetivo de la lectura
		target1 = nfc.clf.RemoteTarget("106A")          
		str2 = str(clf.sense(target1, iterations=100, interval=0.5))[13:21]
        # Request al servidor web de los datos del alumno
		response = urllib2.urlopen(web+str2+'&lugar=LabPBE')
	   	clf.close()
		return (response, str2)
Esempio n. 6
0
def main(args):
    if args['--debug']:
        loglevel = logging.DEBUG - (1 if args['--verbose'] else 0)
        logging.getLogger("nfc.clf").setLevel(loglevel)
        logging.getLogger().setLevel(loglevel)

    try:
        try: waittime = float(args['--wait'])
        except ValueError: assert 0, "the '--wait T' argument must be a number"
        assert waittime >= 0, "the '--wait T' argument must be positive"
        try: timeout = float(args['--time'])
        except ValueError: assert 0, "the '--time T' argument must be a number"
        assert timeout >= 0, "the '--time T' argument must be positive"
    except AssertionError as error:
        print(str(error), file=sys.stderr); return 2

    try:
        clf = nfc.ContactlessFrontend(args['--device'])
    except IOError as error:
        print("no device found on path %r" % args['--device'], file=sys.stderr)
        return 3
    
    try:
        while True:
            try:
                target = None
                if args['tt2']: target = listen_tta(timeout, clf, args)
                if args['tt3']: target = listen_ttf(timeout, clf, args)
                if args['tt4']: target = listen_tta(timeout, clf, args)
                if args['dep']: target = listen_dep(timeout, clf, args)
                if target:
                    print("{0} {1}".format(time.strftime("%X"), target))
            except nfc.clf.CommunicationError as error:
                if args['--verbose']: logging.error("%r", error)
            except AssertionError as error:
                print(str(error), file=sys.stderr); return 2

            if args['--repeat']: time.sleep(waittime)
            else: return (0 if target else 1)

    except nfc.clf.UnsupportedTargetError as error:
        logging.error("%r", error)
        return 2

    except IOError as error:
        if error.errno != errno.EIO: logging.error("%r", error)
        else: logging.error("lost connection to local device")
        return 3

    except KeyboardInterrupt:
        pass

    finally:
        clf.close()
Esempio n. 7
0
def main(args):
    if args["--debug"]:
        loglevel = logging.DEBUG - (1 if args["--verbose"] else 0)
        logging.getLogger("nfc.clf").setLevel(loglevel)

    try:
        time_to_return = time.time() + float(args['--time'])
    except ValueError as e:
        logging.error("while parsing '--time' " + str(e))
        sys.exit(-1)

    clf = nfc.ContactlessFrontend()
    if clf.open(args['--device']):
        try:
            assert isinstance(clf.device, nfc.clf.pn53x.Device), \
                "rfstate.py does only work with PN53x based devices"
            chipset = clf.device.chipset

            regs = [("CIU_FIFOLevel", 0b10000000)]  # clear fifo
            regs.extend(zip(25 * ["CIU_FIFOData"], bytearray(25)))
            regs.extend([
                ("CIU_Command", 0b00000001),  # Configure command
                ("CIU_Control", 0b00000000),  # act as target (b4=0)
                ("CIU_TxControl", 0b10000000),  # disable output on TX1/TX2
                ("CIU_TxAuto", 0b00100000),  # wake up when rf level detected
                ("CIU_CommIRq", 0b01111111),  # clear interrupt request bits
                ("CIU_DivIRq", 0b01111111),  # clear interrupt request bits
            ])
            chipset.write_register(*regs)

            if args["--verbose"]:
                time_t0 = time.time()
                chipset.read_register("CIU_Status1", "CIU_Status2")
                delta_t = time.time() - time_t0
                print("approx. %d samples/s" % int(1 / delta_t))

            status = chipset.read_register("CIU_Status1", "CIU_Status2")
            rfstate = "ON" if status[1] & 0b00100000 else "OFF"
            time_t0 = time.time()
            print("%.6f RF %s" % (time_t0, rfstate))

            while time.time() < time_to_return:
                status = chipset.read_register("CIU_Status1", "CIU_Status2")
                if rfstate == "OFF" and status[1] & 0x20 == 0x20:
                    rfstate = "ON"
                    time_t1 = time.time()
                    delta_t = time_t1 - time_t0
                    print("%.6f RF ON  after %.6f" % (time_t1, delta_t))
                    time_t0 = time_t1
                if rfstate == "ON" and status[1] & 0x20 == 0x00:
                    rfstate = "OFF"
                    time_t1 = time.time()
                    delta_t = time_t1 - time_t0
                    print("%.6f RF OFF after %.6f" % (time_t1, delta_t))
                    time_t0 = time_t1
        except nfc.clf.UnsupportedTargetError as error:
            print(repr(error))
        except IOError as error:
            if error.errno == errno.EIO:
                print("lost connection to local device")
            else:
                print(repr(error))
        except (NotImplementedError, AssertionError) as error:
            print(str(error))
        except KeyboardInterrupt:
            pass
        finally:
            clf.close()
Esempio n. 8
0
def main(args):
    if args.debug:
        loglevel = logging.DEBUG - (1 if args.verbose else 0)
        logging.getLogger("nfc.clf").setLevel(loglevel)
        logging.getLogger().setLevel(loglevel)

    if args.atr and len(args.atr) < 16:
        print("--atr must supply at least 16 byte")

    clf = nfc.ContactlessFrontend()
    if clf.open(args.device):
        targets = list()
        for target in args.targets:
            target_pattern_match = target_pattern.match(target)
            if not target_pattern_match:
                logging.error("invalid target pattern {!r}".format(target))
            else:
                brty, attributes = target_pattern_match.groups()
                target = nfc.clf.RemoteTarget(brty)
                if attributes:
                    for attr in map(str.strip, attributes.split(' ')):
                        name, value = map(str.strip, attr.split('='))
                        value = bytearray.fromhex(value)
                        setattr(target, name, value)
                logging.debug("add to target list: %s", target)
                targets.append(target)

        try:
            while True:
                target = clf.sense(*targets,
                                   iterations=args.iterations,
                                   interval=args.interval)
                print("{0} {1}".format(time.strftime("%X"), target))

                if (target and args.atr and target.brty in brty_for_dep and (
                    (target.sel_res and target.sel_res[0] & 0x40) or
                    (target.sensf_res and target.sensf_res[1:3] == '\1\xFE'))):
                    atr_req = args.atr[:]
                    if atr_req[0] == 0xFF: atr_req[0] = 0xD4
                    for i in (1, 12, 13, 14):
                        if atr_req[i] == 0xFF: atr_req[i] = 0x00
                    if target.sensf_res:
                        for i in range(2, 10):
                            if atr_req[i] == 0xFF:
                                atr_req[i] = target.sensf_res[i - 1]
                    if atr_req[15] == 0xFF:
                        atr_req[15] = 0x30 | (len(atr_req) > 16) << 1
                    try:
                        data = chr(len(atr_req) + 1) + atr_req
                        if target.brty == "106A": data.insert(0, 0xF0)
                        data = clf.exchange(data, 1.0)
                        if target.brty == "106A": assert data.pop(0) == 0xF0
                        assert len(data) == data.pop(0)
                        target.atr_res = data
                        target.atr_req = atr_req
                    except nfc.clf.CommunicationError as error:
                        print(repr(error) + " for NFC-DEP ATR_REQ")
                    except AssertionError:
                        print("invalid ATR_RES: %r" % str(data.encode("hex")))

                if target and target.atr_res:
                    did = target.atr_req[12]
                    psl = "06D404%02x1203" % did  # PSL_REQ
                    rls = ("04D40A%02x" % did) if did else "03D40A"
                    if target.brty == "106A": psl = "F0" + psl
                    psl, rls = map(bytearray.fromhex, (psl, rls))
                    try:
                        clf.exchange(psl, 1.0)
                    except nfc.clf.CommunicationError as error:
                        print(repr(error) + " for NFC-DEP PSL_REQ")
                    else:
                        target.brty = "424F"
                        try:
                            clf.exchange(rls, 1.0)
                        except nfc.clf.CommunicationError as error:
                            print(repr(error) + " for NFC-DEP RLS_REQ")

                if (target and target.sensf_res
                        and target.sensf_res[1:3] != '\x01\xFE'):
                    request_system_code = "\x0A\x0C" + target.sensf_res[1:9]
                    try:
                        clf.exchange(request_system_code, timeout=1.0)
                    except nfc.clf.CommunicationError as error:
                        print(repr(error) + " for Request System Code Command")

                if not args.repeat: break
                time.sleep(args.waittime)
        except IOError as error:
            if error.errno == errno.EIO:
                print("lost connection to local device")
            else:
                print(error)
        except nfc.clf.UnsupportedTargetError as error:
            print error
        except KeyboardInterrupt:
            pass
        finally:
            clf.close()
Esempio n. 9
0
 def test_close(self, clf):
     clf.device.close.side_effect = IOError
     clf.close()
Esempio n. 10
0
def main(args):
    if args["--debug"]:
        loglevel = logging.DEBUG - (1 if args["--verbose"] else 0)
        logging.getLogger("nfc.clf").setLevel(loglevel)

    try:
        time_to_return = time.time() + float(args['--time'])
    except ValueError as e:
        logging.error("while parsing '--time' " + str(e)); sys.exit(-1)
    
    clf = nfc.ContactlessFrontend()
    if clf.open(args['--device']):
        try:
            assert isinstance(clf.device, nfc.clf.pn53x.Device), \
                "rfstate.py does only work with PN53x based devices"
            chipset = clf.device.chipset
            
            regs = [("CIU_FIFOLevel", 0b10000000)] # clear fifo
            regs.extend(zip(25*["CIU_FIFOData"], bytearray(25)))
            regs.extend([
                ("CIU_Command",   0b00000001), # Configure command
                ("CIU_Control",   0b00000000), # act as target (b4=0)
                ("CIU_TxControl", 0b10000000), # disable output on TX1/TX2
                ("CIU_TxAuto",    0b00100000), # wake up when rf level detected
                ("CIU_CommIRq",   0b01111111), # clear interrupt request bits
                ("CIU_DivIRq",    0b01111111), # clear interrupt request bits
            ])
            chipset.write_register(*regs)

            if args["--verbose"]:
                time_t0 = time.time()
                chipset.read_register("CIU_Status1", "CIU_Status2")
                delta_t = time.time() - time_t0
                print("approx. %d samples/s" % int(1/delta_t))
            
            status = chipset.read_register("CIU_Status1", "CIU_Status2")
            rfstate = "ON" if status[1] & 0b00100000 else "OFF"
            time_t0 = time.time()
            print("%.6f RF %s" % (time_t0, rfstate))
            
            while time.time() < time_to_return:
                status = chipset.read_register("CIU_Status1", "CIU_Status2")
                if rfstate == "OFF" and status[1] & 0x20 == 0x20:
                    rfstate = "ON"
                    time_t1 = time.time()
                    delta_t = time_t1 - time_t0
                    print("%.6f RF ON  after %.6f" % (time_t1, delta_t))
                    time_t0 = time_t1
                if rfstate == "ON" and status[1] & 0x20 == 0x00:
                    rfstate = "OFF"
                    time_t1 = time.time()
                    delta_t = time_t1 - time_t0
                    print("%.6f RF OFF after %.6f" % (time_t1, delta_t))
                    time_t0 = time_t1
        except nfc.clf.UnsupportedTargetError as error:
            print(repr(error))
        except IOError as error:
            if error.errno == errno.EIO:
                print("lost connection to local device")
            else: print(repr(error))
        except (NotImplementedError, AssertionError) as error:
            print(str(error))
        except KeyboardInterrupt:
            pass
        finally:
            clf.close()
Esempio n. 11
0
def main(args):
    if args.debug:
        loglevel = logging.DEBUG - (1 if args.verbose else 0)
        logging.getLogger("nfc.clf").setLevel(loglevel)

    if args.atr and len(args.atr) < 16:
        print("--atr must supply at least 16 byte")

    clf = nfc.ContactlessFrontend()
    if clf.open(args.device):
        targets = list()
        for target in args.targets:
            target_pattern_match = target_pattern.match(target)
            if not target_pattern_match:
                logging.error("invalid target pattern {!r}".format(target))
            else:
                brty, attributes = target_pattern_match.groups()
                target = nfc.clf.RemoteTarget(brty)
                if attributes:
                    for attr in map(str.strip, attributes.split(' ')):
                        name, value = map(str.strip, attr.split('='))
                        value = bytearray.fromhex(value)
                        setattr(target, name, value)
                targets.append(target)

        try:
            while True:
                target = clf.sense(*targets, iterations=args.iterations,
                                   interval=args.interval)
                print("{0} {1}".format(time.strftime("%X"), target))
                
                if (target and args.atr and target.brty in brty_for_dep and
                    ((target.sel_res and target.sel_res[0] & 0x40) or
                     (target.sensf_res and target.sensf_res[1:3]=='\1\xFE'))):
                    atr_req = args.atr[:]
                    if atr_req[0] == 0xFF: atr_req[0] = 0xD4
                    for i in (1, 12, 13, 14):
                        if atr_req[i] == 0xFF: atr_req[i] = 0x00
                    if target.sensf_res:
                        for i in range(2, 10):
                            if atr_req[i] == 0xFF:
                                atr_req[i] = target.sensf_res[i-1]
                    if atr_req[15] == 0xFF:
                        atr_req[15] = 0x30 | (len(atr_req)>16)<<1
                    try:
                        data = chr(len(atr_req)+1) + atr_req
                        if target.brty == "106A": data.insert(0, 0xF0)
                        data = clf.exchange(data, 1.0)
                        if target.brty == "106A": assert data.pop(0) == 0xF0
                        assert len(data) == data.pop(0)
                        target.atr_res = data
                        target.atr_req = atr_req
                    except nfc.clf.CommunicationError as error:
                        print(repr(error) + " for NFC-DEP ATR_REQ")
                    except AssertionError:
                        print("invalid ATR_RES: %r" % str(data.encode("hex")))
                
                if target and target.atr_res:
                    did = target.atr_req[12]
                    psl = "06D404%02x1203" % did # PSL_REQ
                    rls = ("04D40A%02x"%did) if did else "03D40A"
                    if target.brty == "106A": psl = "F0" + psl
                    psl, rls = map(bytearray.fromhex, (psl, rls))
                    try: clf.exchange(psl, 1.0)
                    except nfc.clf.CommunicationError as error:
                        print(repr(error) + " for NFC-DEP PSL_REQ")
                    else:
                        target.brty = "424F"
                        try: clf.exchange(rls, 1.0)
                        except nfc.clf.CommunicationError as error:
                            print(repr(error) + " for NFC-DEP RLS_REQ")

                if (target and target.sensf_res and
                    target.sensf_res[1:3] != '\x01\xFE'):
                    request_system_code = "\x0A\x0C"+target.sensf_res[1:9]
                    try: clf.exchange(request_system_code, timeout=1.0)
                    except nfc.clf.CommunicationError as error:
                        print(repr(error) + " for Request System Code Command")
                
                if not args.repeat: break
                time.sleep(args.waittime)
        except IOError as error:
            if error.errno == errno.EIO:
                print("lost connection to local device")
            else: print(error)
        except nfc.clf.UnsupportedTargetError as error:
            print error
        except KeyboardInterrupt:
            pass
        finally:
            clf.close()
Esempio n. 12
0
 def test_close(self, clf):
     clf.device.close.side_effect = IOError
     clf.close()
Esempio n. 13
0
 def run_once(self):
     clf = nfc.ContactlessFrontend(self.reader_path)
     try:
         return clf.connect(rdwr={'on-connect': self.__on_rdwr_connect})
     finally:
         clf.close()