reader.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from smartcard.CardType import AnyCardType
  2. from smartcard.CardRequest import CardRequest
  3. from smartcard.util import toHexString
  4. from smartcard.ATR import ATR
  5. import logging
  6. # 通过下面的方式进行简单配置输出方式与日志级别
  7. # logging.basicConfig(filename='E:\logger.log', level=logging.INFO)
  8. # 初始化读卡器
  9. def init():
  10. print('初始化读卡器')
  11. card_type = AnyCardType()
  12. card_request = CardRequest(timeout=500, cardType=card_type)
  13. card_service = card_request.waitforcard()
  14. card_service.connection.connect()
  15. atr = ATR(card_service.connection.getATR())
  16. return card_service
  17. def trace_command(apdu):
  18. logging.info('sending: ' + toHexString(apdu))
  19. def trace_response(response, sw1, sw2):
  20. if response is None:
  21. response = []
  22. print(
  23. 'serial no.: ',
  24. toHexString(response),
  25. ' status words: ',
  26. "%x %x" % (sw1, sw2)
  27. )
  28. logging.info('serial no.: ' +
  29. toHexString(response) +
  30. ' status words: ' +
  31. "%x %x" % (sw1, sw2))
  32. def bytes2hexstr(data_bytes):
  33. data_number = len(data_bytes)
  34. data_hex_str = ''
  35. for i in range(0, data_number):
  36. data_int = int(str(data_bytes[i]))
  37. data_hex_str += "{:02X} ".format(data_int)
  38. return data_hex_str
  39. #发送指令
  40. def sendCommand(card_service,command):
  41. trace_command(command)
  42. res, s1, s2 = card_service.connection.transmit(command)
  43. trace_response(res, s1, s2)
  44. return res,s1,s2
  45. # 读取芯片UID
  46. def read_uid(card_service):
  47. rf_command_bytes = [0xFF,0xCA,0x00,0x00,0x00]
  48. res,s1,s2 = sendCommand(card_service,rf_command_bytes)
  49. return bytes2hexstr(res)