wps-nfc.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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_connect():
  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 None
  23. if len(ifaces) < 1:
  24. print "No wpa_supplicant control interface found"
  25. return None
  26. for ctrl in ifaces:
  27. try:
  28. wpas = wpactrl.WPACtrl(ctrl)
  29. return wpas
  30. except wpactrl.error, error:
  31. print "Error: ", error
  32. pass
  33. return None
  34. def wpas_tag_read(message):
  35. wpas = wpas_connect()
  36. if (wpas == None):
  37. return
  38. print wpas.request("WPS_NFC_TAG_READ " + message.encode("hex"))
  39. def main():
  40. clf = nfc.ContactlessFrontend()
  41. try:
  42. while True:
  43. print "Waiting for a tag to be touched"
  44. while True:
  45. tag = clf.poll()
  46. if tag and tag.ndef:
  47. break
  48. if tag:
  49. print "Not an NDEF tag"
  50. while tag.is_present:
  51. time.sleep(0.2)
  52. if len(tag.ndef.message):
  53. message = nfc.ndef.Message(tag.ndef.message)
  54. print "message type " + message.type
  55. for record in message:
  56. print "record type " + record.type
  57. if record.type == "application/vnd.wfa.wsc":
  58. print "WPS tag - send to wpa_supplicant"
  59. wpas_tag_read(tag.ndef.message)
  60. break
  61. else:
  62. print "Empty tag"
  63. print "Remove tag"
  64. while tag.is_present:
  65. time.sleep(0.2)
  66. print "Ok"
  67. except KeyboardInterrupt:
  68. raise SystemExit
  69. finally:
  70. clf.close()
  71. raise SystemExit
  72. if __name__ == '__main__':
  73. main()