예제 #1
0
    def read_loop(self):
        log.debug("READER: start new reading loop...")
        if not self._clf:
            try:
                self._clf = nfc.ContactlessFrontend(probe=nfc.dev.__all__)
                log.debug("READER: CLF found: " + str(self._clf))
            except LookupError:
                log.warning("READER: Reader device not found. Exiting")
                self.Exit()
                return
        try:
            log.debug("READER: Now start reading")
            while not self._exit_reading:
                if not self._pause_reading:
                    tag = self._clf.poll(general_bytes=None)
                else:
                    tag = None
                if not tag:
                    time.sleep(0.5)
                    continue
                if isinstance(tag, nfc.Type3Tag):
                    log.debug("READER: New tag found: " + str(tag))
                    last_tag = {'idm': tag.idm, 'pmm': tag.pmm}
                    if tag.ndef is not None:
                        log.debug("READER: NDEF is present")
                        self._last_idm = tag.idm
                        last_tag['version'] = tag.ndef.version
                        last_tag['writeable'] = tag.ndef.writeable
                        last_tag['capacity'] = tag.ndef.capacity
                        last_tag['size'] = len(tag.ndef.message)

                        self._message = Message(tag.ndef.message)
                        log.debug("READER: NDEF Message detected: ")
                        log.debug("READER:     type=%s" % self._message.type)
                        if last_tag['size']:
                            log.debug("READER: size: %d" % last_tag['size'])
                            self.NDEFMessage(tag.ndef.message)  # emit
                        self.TagInfo(pickle.dumps(last_tag))

                while tag.is_present:
                    time.sleep(1)
                log.debug("READER: Tag removed")

        except IOError:
            log.warning("READER: IO Error occured. restarting...")
            read_thread = Thread(target=self.read_loop, name="ReadThread")
            read_thread.start()
예제 #2
0
    def WriteNDEF(self, message_string):
        log.info("WRITER: Writting...")
        self._pause_reading = True
        self._message = Message(str(message_string))
        log.info("WRITER: Write message with type " + self._message.type)
        if not self._clf:
            try:
                self._clf = nfc.ContactlessFrontend(probe=nfc.dev.__all__)
            except LookupError:
                log.warning("WRITER: Reader/Writer not found. Exiting")
                self.Exit()
        tag = None
        while not tag:
            tag = self._clf.poll(general_bytes=None)

        if tag:
            log.debug("WRITER: found tag with IDm " + tag.idm)
            tag.ndef.message = self._message.tostring()
            log.debug("WRITER: Writing successfully finished.")
        else:
            log.info("WRITER: No tag found...")
        self._pause_reading = False
        return
예제 #3
0
    def read_loop(self):
        log.debug("READER: start new reading loop...")
        if not self._clf:
            try:
                self._clf = nfc.ContactlessFrontend(probe=nfc.dev.__all__)
                log.debug("READER: CLF found: " + str(self._clf))
            except LookupError:
                log.warning("READER: Reader device not found. Exiting")
                self.Exit()
                return
        try:
            log.debug("READER: Now start reading")
            while not self._exit_reading:
                if not self._pause_reading:
                    tag = self._clf.poll(general_bytes = None)
                else:
                    tag = None
                if not tag:
                    time.sleep(0.5)
                    continue
                if isinstance(tag, nfc.Type3Tag):
                    log.debug("READER: New tag found: " + str(tag))
                    last_tag = {'idm': tag.idm,
                                'pmm': tag.pmm}
                    if tag.ndef is not None:
                        log.debug("READER: NDEF is present")
                        self._last_idm = tag.idm
                        last_tag['version'] = tag.ndef.version
                        last_tag['writeable'] = tag.ndef.writeable
                        last_tag['capacity'] = tag.ndef.capacity
                        last_tag['size'] = len(tag.ndef.message)

                        self._message = Message(tag.ndef.message)
                        log.debug("READER: NDEF Message detected: ")
                        log.debug("READER:     type=%s" 
                                  % self._message.type)
                        if last_tag['size']:
                            log.debug("READER: size: %d" % last_tag['size'])
                            self.NDEFMessage(tag.ndef.message) # emit
                        self.TagInfo(pickle.dumps(last_tag))
                
                while tag.is_present:
                    time.sleep(1)
                log.debug("READER: Tag removed")

        except IOError:
            log.warning("READER: IO Error occured. restarting...")
            read_thread = Thread(target=self.read_loop, name="ReadThread")
            read_thread.start()
예제 #4
0
 def WriteNDEF(self, message_string):
     log.info("WRITER: Writting...")
     self._pause_reading = True
     self._message = Message(str(message_string))
     log.info("WRITER: Write message with type " + self._message.type)
     if not self._clf:
         try:
             self._clf = nfc.ContactlessFrontend(probe=nfc.dev.__all__)
         except LookupError:
             log.warning("WRITER: Reader/Writer not found. Exiting")
             self.Exit()
     tag = None
     while not tag:
         tag = self._clf.poll(general_bytes = None)
     
     if tag: 
         log.debug("WRITER: found tag with IDm " + tag.idm)
         tag.ndef.message = self._message.tostring()
         log.debug("WRITER: Writing successfully finished.")
     else:
         log.info("WRITER: No tag found...")
     self._pause_reading = False
     return
예제 #5
0
class TagReader(dbus.service.Object):
    def __init__(self, bus, mainloop, path="/nfcpy/tagreader"):
        log.debug("READER: Create Reader/Writer object...")
        self.running = False
        dbus.service.Object.__init__(self, conn=bus, object_path=path)
        if bus.name_has_owner(BUS_NAME):
            # Another instance exists. Inform user and exit.
            owner = bus.get_name_owner(BUS_NAME)
            log.warning("READER: Another instance is running. You can access " 
                     + "or exit it via DBus by the name 'org.nfcpy.TagReader'" 
                     + "or by the unique name " + owner + ".")
            return
        log.debug("READER: Request Service name")
        req_responce = bus.request_name(BUS_NAME,
                                        dbus.bus.NAME_FLAG_DO_NOT_QUEUE)
        # debugging:
        if req_responce == dbus.bus.REQUEST_NAME_REPLY_EXISTS:
            log.debug("READER: reply: exists. %s" % req_responce)
        elif req_responce == dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER:
            log.debug("READER: reply: primary owner. %s" % req_responce)

        self._mainloop = mainloop
        self._message = None
        self._last_tag = dict()
        self._exit_reading = False
        self._pause_reading = False
        self._last_idm = None
        self._clf = None
        read_thread = Thread(target=self.read_loop, name="ReadThread")
        read_thread.start()
        self.running = True
        
    @property
    def running(self):
        return self._running
    
    @running.setter
    def running(self, value):
        self._running = value
        
    @dbus.service.signal(dbus_interface='org.nfcpy.TagReader',
                         signature='ay') # byte-array, subclass of str
    def NDEFMessage(self, new_message_string):
        log.debug("READER: Emit message!")
        if new_message_string:
            return new_message_string
        else:
            return ""
    
    @dbus.service.signal(dbus_interface='org.nfcpy.TagReader',
                         signature='ay') # byte-array, subclass of str
    def TagInfo(self, tag_str):
        log.debug("READER: Emit Tag Info!")
#        return new_message_string

    @dbus.service.method('org.nfcpy.TagReader', in_signature="", 
                         out_signature="")
    def Exit(self):
        log.info("READER: exiting...")
        self._exit_reading = True
        log.debug("READER: release connection to" + str(self.connection))
        self.connection.release_name(BUS_NAME)
        log.debug("READER: Stop the mainloop")
        self._mainloop.quit()
        log.debug("READER: End program")
        
    @dbus.service.method('org.nfcpy.TagReader', in_signature="ay", 
                         out_signature="", byte_arrays=True)
    def WriteNDEF(self, message_string):
        log.info("WRITER: Writting...")
        self._pause_reading = True
        self._message = Message(str(message_string))
        log.info("WRITER: Write message with type " + self._message.type)
        if not self._clf:
            try:
                self._clf = nfc.ContactlessFrontend(probe=nfc.dev.__all__)
            except LookupError:
                log.warning("WRITER: Reader/Writer not found. Exiting")
                self.Exit()
        tag = None
        while not tag:
            tag = self._clf.poll(general_bytes = None)
        
        if tag: 
            log.debug("WRITER: found tag with IDm " + tag.idm)
            tag.ndef.message = self._message.tostring()
            log.debug("WRITER: Writing successfully finished.")
        else:
            log.info("WRITER: No tag found...")
        self._pause_reading = False
        return
        
    @dbus.service.method('org.nfcpy.TagReader', in_signature="", 
                         out_signature="b")
    def FormatTag(self):
        self._pause_reading = True
        if not self._clf:
            try:
                self._clf = nfc.ContactlessFrontend(probe=nfc.dev.__all__)
            except LookupError:
                log.warning("WRITER: Reader/Writer not found. Exiting")
                self.Exit()
        
        tag = None
        while not tag:
            try:
                tag = self._clf.poll(general_bytes = None)
            except KeyboardInterrupt:
                log.warning("WRITER: Aborted by user. Exit formatting...")
                return False
        log.info("Tag found: " + str(tag))
        if tag:
            log.info(str(tag))
            if isinstance(tag, nfc.Type3Tag):
                tt3_format(tag)
                success = True
            else:
                print "unable to format {0}".format(str(tag))
                self._pause_reading = False
                success = False
        else:
            print "No tag"
        self._pause_reading = False
        return success

    def read_loop(self):
        log.debug("READER: start new reading loop...")
        if not self._clf:
            try:
                self._clf = nfc.ContactlessFrontend(probe=nfc.dev.__all__)
                log.debug("READER: CLF found: " + str(self._clf))
            except LookupError:
                log.warning("READER: Reader device not found. Exiting")
                self.Exit()
                return
        try:
            log.debug("READER: Now start reading")
            while not self._exit_reading:
                if not self._pause_reading:
                    tag = self._clf.poll(general_bytes = None)
                else:
                    tag = None
                if not tag:
                    time.sleep(0.5)
                    continue
                if isinstance(tag, nfc.Type3Tag):
                    log.debug("READER: New tag found: " + str(tag))
                    last_tag = {'idm': tag.idm,
                                'pmm': tag.pmm}
                    if tag.ndef is not None:
                        log.debug("READER: NDEF is present")
                        self._last_idm = tag.idm
                        last_tag['version'] = tag.ndef.version
                        last_tag['writeable'] = tag.ndef.writeable
                        last_tag['capacity'] = tag.ndef.capacity
                        last_tag['size'] = len(tag.ndef.message)

                        self._message = Message(tag.ndef.message)
                        log.debug("READER: NDEF Message detected: ")
                        log.debug("READER:     type=%s" 
                                  % self._message.type)
                        if last_tag['size']:
                            log.debug("READER: size: %d" % last_tag['size'])
                            self.NDEFMessage(tag.ndef.message) # emit
                        self.TagInfo(pickle.dumps(last_tag))
                
                while tag.is_present:
                    time.sleep(1)
                log.debug("READER: Tag removed")

        except IOError:
            log.warning("READER: IO Error occured. restarting...")
            read_thread = Thread(target=self.read_loop, name="ReadThread")
            read_thread.start()
예제 #6
0
class TagReader(dbus.service.Object):
    def __init__(self, bus, mainloop, path="/nfcpy/tagreader"):
        log.debug("READER: Create Reader/Writer object...")
        self.running = False
        dbus.service.Object.__init__(self, conn=bus, object_path=path)
        if bus.name_has_owner(BUS_NAME):
            # Another instance exists. Inform user and exit.
            owner = bus.get_name_owner(BUS_NAME)
            log.warning(
                "READER: Another instance is running. You can access " +
                "or exit it via DBus by the name 'org.nfcpy.TagReader'" +
                "or by the unique name " + owner + ".")
            return
        log.debug("READER: Request Service name")
        req_responce = bus.request_name(BUS_NAME,
                                        dbus.bus.NAME_FLAG_DO_NOT_QUEUE)
        # debugging:
        if req_responce == dbus.bus.REQUEST_NAME_REPLY_EXISTS:
            log.debug("READER: reply: exists. %s" % req_responce)
        elif req_responce == dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER:
            log.debug("READER: reply: primary owner. %s" % req_responce)

        self._mainloop = mainloop
        self._message = None
        self._last_tag = dict()
        self._exit_reading = False
        self._pause_reading = False
        self._last_idm = None
        self._clf = None
        read_thread = Thread(target=self.read_loop, name="ReadThread")
        read_thread.start()
        self.running = True

    @property
    def running(self):
        return self._running

    @running.setter
    def running(self, value):
        self._running = value

    @dbus.service.signal(dbus_interface='org.nfcpy.TagReader',
                         signature='ay')  # byte-array, subclass of str
    def NDEFMessage(self, new_message_string):
        log.debug("READER: Emit message!")
        if new_message_string:
            return new_message_string
        else:
            return ""

    @dbus.service.signal(dbus_interface='org.nfcpy.TagReader',
                         signature='ay')  # byte-array, subclass of str
    def TagInfo(self, tag_str):
        log.debug("READER: Emit Tag Info!")


#        return new_message_string

    @dbus.service.method('org.nfcpy.TagReader',
                         in_signature="",
                         out_signature="")
    def Exit(self):
        log.info("READER: exiting...")
        self._exit_reading = True
        log.debug("READER: release connection to" + str(self.connection))
        self.connection.release_name(BUS_NAME)
        log.debug("READER: Stop the mainloop")
        self._mainloop.quit()
        log.debug("READER: End program")

    @dbus.service.method('org.nfcpy.TagReader',
                         in_signature="ay",
                         out_signature="",
                         byte_arrays=True)
    def WriteNDEF(self, message_string):
        log.info("WRITER: Writting...")
        self._pause_reading = True
        self._message = Message(str(message_string))
        log.info("WRITER: Write message with type " + self._message.type)
        if not self._clf:
            try:
                self._clf = nfc.ContactlessFrontend(probe=nfc.dev.__all__)
            except LookupError:
                log.warning("WRITER: Reader/Writer not found. Exiting")
                self.Exit()
        tag = None
        while not tag:
            tag = self._clf.poll(general_bytes=None)

        if tag:
            log.debug("WRITER: found tag with IDm " + tag.idm)
            tag.ndef.message = self._message.tostring()
            log.debug("WRITER: Writing successfully finished.")
        else:
            log.info("WRITER: No tag found...")
        self._pause_reading = False
        return

    @dbus.service.method('org.nfcpy.TagReader',
                         in_signature="",
                         out_signature="b")
    def FormatTag(self):
        self._pause_reading = True
        if not self._clf:
            try:
                self._clf = nfc.ContactlessFrontend(probe=nfc.dev.__all__)
            except LookupError:
                log.warning("WRITER: Reader/Writer not found. Exiting")
                self.Exit()

        tag = None
        while not tag:
            try:
                tag = self._clf.poll(general_bytes=None)
            except KeyboardInterrupt:
                log.warning("WRITER: Aborted by user. Exit formatting...")
                return False
        log.info("Tag found: " + str(tag))
        if tag:
            log.info(str(tag))
            if isinstance(tag, nfc.Type3Tag):
                tt3_format(tag)
                success = True
            else:
                print "unable to format {0}".format(str(tag))
                self._pause_reading = False
                success = False
        else:
            print "No tag"
        self._pause_reading = False
        return success

    def read_loop(self):
        log.debug("READER: start new reading loop...")
        if not self._clf:
            try:
                self._clf = nfc.ContactlessFrontend(probe=nfc.dev.__all__)
                log.debug("READER: CLF found: " + str(self._clf))
            except LookupError:
                log.warning("READER: Reader device not found. Exiting")
                self.Exit()
                return
        try:
            log.debug("READER: Now start reading")
            while not self._exit_reading:
                if not self._pause_reading:
                    tag = self._clf.poll(general_bytes=None)
                else:
                    tag = None
                if not tag:
                    time.sleep(0.5)
                    continue
                if isinstance(tag, nfc.Type3Tag):
                    log.debug("READER: New tag found: " + str(tag))
                    last_tag = {'idm': tag.idm, 'pmm': tag.pmm}
                    if tag.ndef is not None:
                        log.debug("READER: NDEF is present")
                        self._last_idm = tag.idm
                        last_tag['version'] = tag.ndef.version
                        last_tag['writeable'] = tag.ndef.writeable
                        last_tag['capacity'] = tag.ndef.capacity
                        last_tag['size'] = len(tag.ndef.message)

                        self._message = Message(tag.ndef.message)
                        log.debug("READER: NDEF Message detected: ")
                        log.debug("READER:     type=%s" % self._message.type)
                        if last_tag['size']:
                            log.debug("READER: size: %d" % last_tag['size'])
                            self.NDEFMessage(tag.ndef.message)  # emit
                        self.TagInfo(pickle.dumps(last_tag))

                while tag.is_present:
                    time.sleep(1)
                log.debug("READER: Tag removed")

        except IOError:
            log.warning("READER: IO Error occured. restarting...")
            read_thread = Thread(target=self.read_loop, name="ReadThread")
            read_thread.start()