wps-nfc.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/python
  2. #
  3. # Example nfcpy to wpa_supplicant wrapper for WPS NFC operations
  4. # Copyright (c) 2012, Jouni Malinen <j@w1.fi>
  5. #
  6. # This software may be distributed under the terms of the BSD license.
  7. # See README for more details.
  8. import os
  9. import sys
  10. import time
  11. import nfc
  12. import nfc.ndef
  13. import wpactrl
  14. wpas_ctrl = '/var/run/wpa_supplicant'
  15. def wpas_tag_read(message):
  16. ifaces = []
  17. if os.path.isdir(wpas_ctrl):
  18. try:
  19. ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
  20. except OSError, error:
  21. print "Could not find wpa_supplicant: ", error
  22. return
  23. if len(ifaces) < 1:
  24. print "No wpa_supplicant control interface found"
  25. return
  26. for ctrl in ifaces:
  27. try:
  28. wpas = wpactrl.WPACtrl(ctrl)
  29. print wpas.request("WPS_NFC_TAG_READ " + message.encode("hex"))
  30. except wpactrl.error, error:
  31. print "Error: ", error
  32. pass
  33. def main():
  34. clf = nfc.ContactlessFrontend()
  35. try:
  36. while True:
  37. print "Waiting for a tag to be touched"
  38. while True:
  39. tag = clf.poll()
  40. if tag and tag.ndef:
  41. break
  42. if tag:
  43. print "Not an NDEF tag"
  44. while tag.is_present:
  45. time.sleep(0.2)
  46. if len(tag.ndef.message):
  47. message = nfc.ndef.Message(tag.ndef.message)
  48. print "message type " + message.type
  49. for record in message:
  50. print "record type " + record.type
  51. if record.type == "application/vnd.wfa.wsc":
  52. print "WPS tag - send to wpa_supplicant"
  53. wpas_tag_read(tag.ndef.message)
  54. break
  55. else:
  56. print "Empty tag"
  57. print "Remove tag"
  58. while tag.is_present:
  59. time.sleep(0.2)
  60. print "Ok"
  61. except KeyboardInterrupt:
  62. raise SystemExit
  63. finally:
  64. clf.close()
  65. raise SystemExit
  66. if __name__ == '__main__':
  67. main()