view levistone.py @ 0:099871090d7a draft default tip

Add edyReader scripts py HG: added pifacedigitalio.py
author innparusu
date Wed, 13 Dec 2017 20:11:51 +0900
parents
children
line wrap: on
line source

#!/usr/bin/env python

import nfc
import nfc.clf
import nfc.ndef
import binascii

import os
import os.path
import sys
import pifacedigitalio
import threading
import time
from threading import Timer

import ldapaccess
import logging
import logging.handlers

logging.basicConfig(level=logging.INFO)
log = logging.getLogger('main')
path =  os.path.join(os.environ['LOG_DIR'], 'scan_card.log')
handler = logging.handlers.TimedRotatingFileHandler(
        path,
        when="D",
        interval=1,
        backupCount=5
)
handler.setLevel(logging.INFO)

formatter = logging.Formatter('%(levelname)s(%(name)s): %(asctime)s - %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)


class Reader:
        def __init__(self):
                # nfc library
                self.system_code = 0xFE00
                self.service_code = {
                        "suica":  0x090f,
                        "univ":   0x50CB,
                        "edy":    0x110B,
                        "waon":   0x67CF,
                        "nanaco": 0x558B
                }
                
                # piface
                self.piface = pifacedigitalio.PiFaceDigital()

                # thread
                self.event = threading.Event()

                self.ldapAccess = ldapaccess.LdapAccess()

        def turn_off_event(self):
            self.turn_off()

        def balus(self, nfcId):
            print(nfcId + '\n')
            if self.ldapAccess.searchEdyId(nfcId):
                self.turn_on()

        def card_connected(self, tag):
                if tag.type != "Type3Tag":
                        return False

                try:
                        tag.idm, tag.pmm = tag.polling(self.system_code)
                except nfc.tag.tt3.Type3TagCommandError as err:
                        log.error("polling error: " + str(err))
                        return False
                except Exception as e:
                        log.error("card read error: " + str(e))

                for key in sorted(self.service_code.keys()):

                        service_code = self.service_code[key]
                        sc_list = [nfc.tag.tt3.ServiceCode(service_code >> 6, service_code & 0x3f)]
                        try:
                                if tag.request_service(sc_list) == [0xFFFF]:
                                        continue
                        except nfc.tag.tt3.Type3TagCommandError as err:
                                continue
                        except Exception as e:
                                log.error("card read error: " + str(e))
                                continue
                        
                        if isinstance(tag, nfc.tag.tt3_sony.FelicaStandard) or isinstance(tag, nfc.tag.tt3_sony.FelicaMobile):
                                try:
                                        bc = nfc.tag.tt3.BlockCode(0x00, service=0)
                                        data = tag.read_without_encryption(sc_list, [bc])
                                        log.info("block: " + binascii.hexlify(data))
                                except Exception as e:
                                        log.error("card read error: " + str(e))

                                if key == "suica":
                                        print("suica balance: (little endian)%s" % binascii.hexlify(data[10:12]))
                                elif key == "univ":
                                        self.balus(binascii.hexlify(data[0:6]))
                                elif key == "edy":
                                        self.balus(binascii.hexlify(data[2:10]))
                                elif key == "waon":
                                        # self.balus(binascii.hexlify(data[2:10]))
                                        print("waon balance: %s" % binascii.hexlify(data[0:24]))
                                elif key == "nanaco":
                                        self.balus(binascii.hexlify(data[0:8]))
                                else:
                                        log.error("error: tag isn't Type3Tag")
                                break

                return True

        def turn_on(self):
                self.piface.output_pins[1].turn_on()
                Timer(10, self.turn_off_event, ()).start()

        def turn_off(self):
                self.piface.output_pins[1].turn_off()

        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})
                except Exception as e:
                        log.error("card read error: " + str(e))
                        return True
                finally:
                        clf.close()


if __name__ == '__main__':
        reader = Reader()
        # reader.socket_connect()

        while reader.run():
                log.info("*** RESTART ***")