Esempio n. 1
0
def write_time_record(tag):
    if tag.ndef is None:
        return
    timerecord = ndef.TextRecord(datetime.datetime.now().strftime(
        "JaDoor last opened on %d/%m/%Y - %H:%M:%S"))
    second_record = ndef.TextRecord(
        'Don\'t forget to unit test your projects -- <3 Ndr')
    print('Writing time record')
    tag.ndef.records = [timerecord, second_record]
Esempio n. 2
0
def write_current_album(tag):
    res = find_current_album()
    if not res:
        print "No album found"
        return False

    album, artist = res
    print "Current Album '%s' Artist '%s'" % (album, artist)
    uri = find_uri_from_spotify(album, artist)

    print "URI is %s" % uri

    print "Formatting tag"
    tag.format()

    print "Tag Formatted %s" % tag
    record = ndef.TextRecord(uri)
    tag.ndef.records = [record]

    print "Finished writing NDEF"

    say_command = "Finished creating tag for artist %s and album %s" % (artist,
                                                                        album)
    url = "/".join((usersettings.sonoshttpaddress, usersettings.sonosroom,
                    "say", say_command))
    requests.get(url)
    return True
Esempio n. 3
0
def cmd(message, **kwargs):
    """The *text* command creates an NFC Forum Text Record with the given
    input text. The text language defaults to 'en' and can be set
    with --language followed by the IANA language code.

    \b
    Examples:
      ndeftool text '' | hexdump -Cv
      ndeftool text 'Created with the nfcpy ndeftool.' print
      ndeftool text 'first record' text 'second record' print
      ndeftool text -l en 'English' text -l de 'Deutsch' print

    """
    dmsg(__name__ + ' ' + str(kwargs))

    if message is None:
        message = []

    content = kwargs['text']
    language = kwargs['language']
    encoding = kwargs['encoding']

    record = ndef.TextRecord(content, language, encoding)

    message.append(record)
    return message
Esempio n. 4
0
    def test_08(self, llc):
        """Skip meaningless records"""

        client = handover_connect(llc, self.options)
        try:
            bt_record = ndef.BluetoothEasyPairingRecord("01:02:03:04:05:06")
            bt_record.name = "carrier-1"
            bt_record.device_name = "Handover Test Client"
            bt_record.device_class = 0x10010C
            bt_record.add_service_class(0x1105)
            bt_record.add_service_class(0x1106)

            hr_record = ndef.HandoverRequestRecord("1.2", os.urandom(2))
            hr_record.add_alternative_carrier("active", bt_record.name)

            handover_send(client, [hr_record, ndef.TextRecord("X"), bt_record])
            records = handover_recv(client, timeout=3.0)
            info("received {}".format(records[0].type))
            hs_record, bt_record = records

            if len(hs_record.alternative_carriers) != 1:
                raise TestFail("one selected carrier is expected")
            if bt_record.type != "application/vnd.bluetooth.ep.oob":
                raise TestFail("a Bluetooth carrier is expected")
        finally:
            client.close()
Esempio n. 5
0
def write_current_album(tag):
   res = find_current_album()
   if not res:
      print("No album found")
      return False

   album, artist = res
   print('Current album ' + str(album) + "by artist " + str(artist)) 
   uri = find_uri_from_spotify(album, artist)

   print('URI is '+ str(uri))

   print("Formatting tag")
   tag.format()

   print("Tag Formatted " + str(tag))
   record = ndef.TextRecord(uri)
   tag.ndef.records = [record]
 
   print("Finished writing NDEF")  

   say_command = "Finished creating tag for artist %s and album %s" % (artist, album)
   url = "/".join((usersettings.sonos_http_address,usersettings.sonos_room, "say",say_command))
   requests.get(url)
   return True 
Esempio n. 6
0
    def write_tag_data(self, tag, record_dict):
        """Writies data from the provided dictionary to the tag

        Preconditions: both keys and values of the dictionary are strings

        Args:
            tag (A Type3Tag (e.g. nfc.tag.tt2_nxp.NTAG215)): The tag for which we want to write the data
            record_dict (dict): The dictionary to be written to the tag (tag.ndef.records)

        throws IOError if the write fails
        """ 

        # Check to make sure that we're only trying to write strings
        if False in [ str is type(x) for x in record_dict.keys() ]:
            raise IOError('Bad type passed in for name/id of tag records')
        if False in [ str is type(x) for x in record_dict.values() ]:
            raise IOError('Bad type passed in for value of tag records')

        tags_to_write = []
        
        for k in record_dict.keys():
            tRec = ndef.TextRecord(record_dict[k])
            tRec.name = k
            tags_to_write.append(tRec)

        # TODO:  We should probably check the size of the things we're trying to write here
        #        to ensure we're not trying to write too much to the tag

        tag.ndef.records = tags_to_write
Esempio n. 7
0
def write_id(id_):
    """
    Writes a spotify id it an NFC tag.
    :param id_: A spotifyId object to write.
    """
    with nfc_open('usb') as tag:
        record = ndef.TextRecord(str(id_))
        tag.ndef.records = [record]
Esempio n. 8
0
    def ecriture(filename, verbose):
        num_capt = 0
        ndef_messages = []
        deveuis = []
        donnees = {}

        # ouverture et lecture du fichier csv
        if filename.endswith(".csv"):
            file = open(f'entrees_csv\\{filename}')
        else:
            file = open(f'entrees_csv\\{filename}.csv')

        # on récupère les titres des valeurs
        tab_file = []
        line_num = 0
        titres = file.readline().split(';')
        for i in range(0, len(titres)):
            titres[i] = titres[i].replace('\n', "")

        # on récupère les données de configuration du fichier CSV
        for line in file:
            settings = ''
            line = line.split(';')
            for j in range(0, len(line)):
                line[j] = line[j].replace('\n', '')
                settings += f'{titres[j]}:{line[j]}\n'
                if titres[j] == 'DevEui':
                    deveuis.append(line[j])
            ndef_messages.append(settings)
        file.close()

        for setting in ndef_messages:
            if verbose:
                print(setting)
            record = ndef.TextRecord(setting)

            print('\nPlacez le capteur sur le lecteur\nDevEui :',
                  deveuis[num_capt])
            # connexion à la carte NFC par le lecteur USB
            clf = nfc.ContactlessFrontend('usb')

            # récupération des données du capteur
            tag = clf.connect(rdwr={'on-connect': lambda tag: False})

            data = tag.ndef.records[0].text.split('\n')

            donnees = outil_nfc.conf_to_dict(data, donnees, num_capt)

            if donnees.get('DevEui') == deveuis[num_capt]:
                # écriture de la configuration dans le capteur
                tag.ndef.records = [record]
            else:
                print('Erreur: DevEui different.')

            clf.close()
            num_capt += 1
Esempio n. 9
0
def on_connect(tag):
    old_record = tag.ndef.records
    # product_idをセットする
    new_record = [ndef.TextRecord("5", "en")]
    if old_record == new_record:
        logger.warning("already written")
    else:
        tag.ndef.records = new_record
        logger.info("Complete!")
    return True
Esempio n. 10
0
 def test_write_without_terminator_tlv(self, tag):
     tag.clf.exchange.side_effect = [
         tag.target.rid_res[:2] +
         fromhex("01 02 03 04  05 06 07 00  e1 10 02 00  03 09 d1 01"
                 "05 54 02 65  6e 61 62 FE"),
         fromhex("0d 00"),
         fromhex("10 06"),
         fromhex("17 63"),
         fromhex("0d 0a"),
     ]
     assert tag.ndef is not None
     assert tag.ndef.records == [ndef.TextRecord("ab")]
     tag.ndef.records = [ndef.TextRecord("abc")]
     assert tag.clf.exchange.mock_calls == [
         mock.call(fromhex('00 00 00 01020304'), 0.1),
         mock.call(fromhex('53 0d 00 01020304'), 0.1),
         mock.call(fromhex('53 10 06 01020304'), 0.1),
         mock.call(fromhex('53 17 63 01020304'), 0.1),
         mock.call(fromhex('53 0d 0a 01020304'), 0.1),
     ]
Esempio n. 11
0
def encode_message_text(array_of_strings):
    """
    Receives an array of strings and returns a message that contains these in a bytearray that can be transferred to a NFC tag.
    """

    print(f"Array of strings send: {array_of_strings}")

    # create list of ndef records
    message = []
    for string in array_of_strings:
        message += [ndef.TextRecord(string)]
    print(f"NDEF Records created: {message}")

    # create ndef encoder generator
    encoder = ndef.message_encoder(message)

    # convert ndef encoder to payload octets
    payload = b''.join(encoder)
    print(f"NDEF payload created: {payload}")

    return payload
Esempio n. 12
0
def write_text(tag):
    record = ndef.TextRecord("Hello sigsec readers!")
    tag.ndef.records = [record]
Esempio n. 13
0
def run_send_text_action(args, llc):
    record = ndef.TextRecord(args.text)
    if args.lang:
        record.language = args.lang
    send_message(args, llc, [record])
Esempio n. 14
0
def beam(llc):
    snep_client = nfc.snep.SnepClient(llc)
    #snep_client.put_records([ndef.UriRecord('https://ikenoji.com')])
    snep_client.put_records([ndef.TextRecord('Hello Test Record')])
Esempio n. 15
0
    def handle_read(self, tag):
        """ Handle a tag being scanned by the reader """
        count = None
        tag_uid = None
        records = []

        if not tag:
            time.sleep(0.1)
            Logger.log(LOG_LEVEL["error"],
                       f"Worker {self.key} NFC Tag Read Error")
            return

        tag_serial = tag.identifier.hex()
        self.last_tag = tag
        _tag_data = self.parse_tag(tag)
        tag_uid = _tag_data.get('tag_uid')

        self.fire(_tag_data)

        if tag_serial not in self._tags:
            Logger.log(
                LOG_LEVEL["info"],
                f"New NFC Tag Scanned: {FONT_CYAN}{tag_serial}{FONT_RESET}")
            self._tags[tag_serial] = _tag_data
            event_data = {'event': 'NFCNewTagScanned'}
            event_data.update(_tag_data)
            self.fire(event_data)
            if self.save_tags:
                self.config.setdefault('tags', {})[tag_serial] = _tag_data
                self.mudpi.save_config()
        else:
            Logger.log(
                LOG_LEVEL["info"],
                f"Existing NFC Tag Scanned: {FONT_CYAN}{tag_serial}{FONT_RESET}"
            )

            # Check if UID is registered
            if self._tags[tag_serial].get('tag_uid'):
                if tag_uid:
                    if tag_uid != self._tags[tag_serial]['tag_uid']:
                        event_data = {
                            'event': 'NFCTagUIDMismatch',
                            "existing_tag_uid":
                            self._tags[tag_serial]['tag_uid']
                        }
                        event_data.update(_tag_data)
                        self.fire(event_data)
                        Logger.log(
                            LOG_LEVEL["debug"],
                            f"WARNING: Tag Data UID Mismatch for tag: {FONT_CYAN}{tag_serial}{FONT_RESET}"
                        )
                else:
                    event_data = {
                        'event': 'NFCTagUIDMissing',
                        "existing_tag_uid": self._tags[tag_serial]['tag_uid']
                    }
                    event_data.update(_tag_data)
                    self.fire(event_data)
                    Logger.log(
                        LOG_LEVEL["debug"],
                        f"Notice: Tag UID registered but Missing on tag: {FONT_CYAN}{tag_serial}{FONT_RESET}"
                    )

        # Register the UID and check for duplicates
        if tag_uid:
            if tag_uid not in self._uids:
                self._uids[tag_uid] = {'tags': [tag_serial]}
            else:
                _prev_tags = self._uids[tag_uid].setdefault('tags', [])
                if tag_serial not in _prev_tags:
                    self._uids[tag_uid]['tags'].append(tag_serial)
                    if len(_prev_tags) > 2:
                        event_data = {
                            'event': 'NFCDuplicateUID',
                            "existing_tag_id":
                            self._tags[tag_serial]['tag_uid']
                        }
                        event_data.update(_tag_data)
                        self.fire(event_data)
                        Logger.log(
                            LOG_LEVEL["debug"],
                            f"WARNING: Same Tag UID found in multiple tags: {FONT_CYAN}{_prev_tags}{FONT_RESET}"
                        )

        # Handle the ndef records and tracking info
        if not tag.ndef:
            if self.tracking:
                self.write(tag, self.add_default_records())
        else:
            if tag.ndef.records:
                for record in tag.ndef.records:
                    if record.type == TYPE_TEXT:
                        if self.persist_records:
                            if not record.text.startswith('count:'):
                                records.append(record)
                    elif record.type == TYPE_URI:
                        if self.persist_records:
                            records.append(record)
                    else:
                        if self.persist_records:
                            records.append(record)

            if self.tracking:
                if _tag_data.get('count') is None:
                    count = 0
                    records.append(ndef.TextRecord(f"count:{count}"))
                else:
                    count = _tag_data['count'] + 1
                    records.append(ndef.TextRecord(f"count:{count}"))

            if self.tracking:
                _defaults = self.add_default_records(records, tag_serial)
                self.write(tag, _defaults)

        # Create a UUID if one was not set
        if tag_uid is None:
            if self.writing:
                Logger.log(
                    LOG_LEVEL["debug"],
                    f"No Tag UID Found for Tag: {FONT_CYAN}{tag_serial}{FONT_RESET}. A new one was generated and saved."
                )
                _tag_data = self.parse_tag(tag)
                _tag_data['tag_uid'] = self.last_uid
                self._tags[tag_serial] = _tag_data
                event_data = {'event': 'NFCNewUIDCreated'}
                event_data.update(_tag_data)
                self.fire(event_data)
                if self.save_tags:
                    self.config.setdefault('tags', {})[tag_serial].update(
                        self._tags[tag_serial])
                    self.mudpi.save_config()
            else:
                Logger.log(
                    LOG_LEVEL["debug"],
                    f"No Tag UID Found for Tag: {FONT_CYAN}{tag_serial}{FONT_RESET}. A new one can not be saved because `writing` is disabled."
                )

        if self.store_logs:
            _tag_log = {
                'tag_id': tag_serial,
                'tag_uid': tag_uid,
                'count': count,
                'updated_at':
                str(datetime.datetime.now().replace(microsecond=0))
            }
            self._logs.append(_tag_log)
            if len(self._logs) > self.log_length:
                self._logs.pop(0)
            self.store_current_logs()
        return True
Esempio n. 16
0
with open('./keys/%s.key' % uid, 'wb') as writer:
    writer.write(bytearray(encrypted))

print('Disposing unnecessary data')

del passphrase
del pub

print('Waiting for NFC tag')

clf = nfc.ContactlessFrontend('usb')
tag = clf.connect(rdwr={'on-connect': lambda t: False})

print('Writing')

uid_record = ndef.TextRecord(uid)
uid_record.name = 'touchkey:uid'

prv_record = ndef.TextRecord(base64.b64encode(prv.encode()))
prv_record.name = 'touchkey:prv'

tag.ndef.records = [uid_record, prv_record]

print('Cleaning up')

del uid_record
del prv_record
del prv
del uid

print('All done!')
Esempio n. 17
0
    def add_default_records(self, records=[], tag_id=None):
        """ Return default records to write to a tag """
        _default_records = None
        if tag_id:
            if tag_id in self.tags:
                if self.tags[tag_id].get('default_records'):
                    _default_records = self.tags[tag_id]['default_records']

        if _default_records is None and self.default_records is not None:
            _default_records = self.default_records

        if _default_records is None:
            _txt_mudpi = ndef.TextRecord("MudPi")
            if _txt_mudpi not in records:
                records.insert(0, _txt_mudpi)

            _uri_mudpi = ndef.UriRecord("https://mudpi.app/docs/extension-nfc")
            if _uri_mudpi not in records:
                records.insert(1, _uri_mudpi)

            _txt_count_label = ndef.TextRecord("Matthew 15:13")
            if _txt_count_label not in records:
                records.insert(2, _txt_count_label)
        else:
            if isinstance(_default_records, list):
                for default_record in _default_records:
                    _record = None
                    if default_record.get('type', '').lower() == 'text':
                        if default_record.get('data'):
                            _record = ndef.TextRecord(default_record['data'])
                    elif default_record.get('type', '').lower() == 'uri':
                        if default_record.get('data'):
                            _record = ndef.UriRecord(default_record['data'])

                    if _record:
                        if _record not in records:
                            if default_record.get('position') is not None:
                                try:
                                    _position = int(default_record['position'])
                                    records.insert(_position, _record)
                                except Exception:
                                    records.append(_record)
                            else:
                                records.append(_record)

        _has_count = False
        _has_uid = False
        _to_remove = []
        for r in records:
            if r.type == TYPE_TEXT:
                if r.text.startswith('count:'):
                    if not _has_count:
                        _has_count = True
                    else:
                        # count already found, remove duplicate
                        _to_remove.append(r)
                elif r.text.startswith('uid:'):
                    if not _has_uid:
                        _has_uid = True
                    else:
                        # uid already found, remove duplicate
                        _to_remove.append(r)
                elif r.text.startswith('last_scan:'):
                    if self.tracking:
                        # remove it to replace with updated data
                        _to_remove.append(r)

        if _to_remove:
            for record in _to_remove:
                records.remove(record)

        if not _has_uid:
            self.last_uid = uid = str(uuid4())
            records.append(ndef.TextRecord(f"uid:{uid}"))

        if self.tracking:
            if not _has_count:
                records.append(ndef.TextRecord("count:0"))

            records.append(
                ndef.TextRecord(
                    f"last_scan:{datetime.datetime.now().replace(microsecond=0).strftime('%Y-%m-%d %H:%M:%S')}"
                ))

        return records
Esempio n. 18
0
 def send_ndef_message(self, llc):
     if self.URLparser():
         sp = ndef.UriRecord(self.data)
     else:
         sp = ndef.TextRecord(self.data)
     nfc.snep.SnepClient(llc).put_records([sp])
Esempio n. 19
0
    Allows reading and writing to
    NFC cards and tags.
"""
import nfc
import ndef
import time
import datetime
import threading
from uuid import uuid4
from mudpi.workers import Worker
from mudpi.extensions import BaseExtension
from mudpi.logger.Logger import Logger, LOG_LEVEL
from mudpi.constants import FONT_RESET, FONT_CYAN

NAMESPACE = 'nfc'
TYPE_TEXT = ndef.TextRecord().type
TYPE_URI = ndef.UriRecord().type


class Extension(BaseExtension):
    namespace = NAMESPACE
    update_interval = 0.5

    def init(self, config):
        """ Setup the readers for nfc """
        self.config = config
        self.readers = {}
        self.tags = self.mudpi.cache.setdefault(NAMESPACE,
                                                {}).setdefault('tags', {})

        if not isinstance(config, list):
Esempio n. 20
0
 def set_text_record(self, data):
     return ndef.TextRecord(data)