macOSでNFC

Posted by: lesser

Pythonで簡単にNFCが使えるということなので試してみました。
nfcpyというモジュールをimportするのですが、libusbが必要です。
libusb を macOS Big Sur Ver. 11.4 で使う』に簡単な説明があります。
libusbの準備が出来たら、ターミナルを起動し、


% pip install nfcpy

で完了です。
リーダーはSONY製。

githubで公開されているnfcpy sampleが、とりあえず動作確認するのに便利です。

下は、さらに簡略化したサンプルです:)
SuicaやPasmo、NanacoなどのType3TagのIDを読み取って出力します。

import sys
import os
import time
import binascii

import nfc

def connected(tag):
    if tag.TYPE == 'Type3Tag':
        idm  = binascii.hexlify(tag.idm).decode()
        print("Type3Tag ID=%s" % (idm))
    else:
        print("error: not a Type3Tag")
        print(tag)

def main():
    try:
        clf = nfc.ContactlessFrontend('usb')
        clf.connect(rdwr={'on-connect': connected})
    except Exception as e:
        print("error: %s" % e)

    return

if __name__ == '__main__':
    main()

以上。