WPS: Add an example python script for NFC operations
[mech_eap.git] / wpa_supplicant / examples / wps-nfc.py
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
9 import os
10 import sys
11 import time
12
13 import nfc
14 import nfc.ndef
15
16 import wpactrl
17
18 wpas_ctrl = '/var/run/wpa_supplicant'
19
20 def wpas_tag_read(message):
21     ifaces = []
22     if os.path.isdir(wpas_ctrl):
23         try:
24             ifaces = [os.path.join(wpas_ctrl, i) for i in os.listdir(wpas_ctrl)]
25         except OSError, error:
26             print "Could not find wpa_supplicant: ", error
27             return
28
29     if len(ifaces) < 1:
30         print "No wpa_supplicant control interface found"
31         return
32
33     for ctrl in ifaces:
34         try:
35             wpas = wpactrl.WPACtrl(ctrl)
36             print wpas.request("WPS_NFC_TAG_READ " + message.encode("hex"))
37         except wpactrl.error, error:
38             print "Error: ", error
39             pass
40
41 def main():
42     clf = nfc.ContactlessFrontend()
43
44     try:
45         while True:
46             print "Waiting for a tag to be touched"
47
48             while True:
49                 tag = clf.poll()
50                 if tag and tag.ndef:
51                     break
52                 if tag:
53                     print "Not an NDEF tag"
54                     while tag.is_present:
55                         time.sleep(0.2)
56
57             if len(tag.ndef.message):
58                 message = nfc.ndef.Message(tag.ndef.message)
59                 print "message type " + message.type
60
61                 for record in message:
62                     print "record type " + record.type
63                     if record.type == "application/vnd.wfa.wsc":
64                         print "WPS tag - send to wpa_supplicant"
65                         wpas_tag_read(tag.ndef.message)
66                         break
67             else:
68                 print "Empty tag"
69
70             print "Remove tag"
71             while tag.is_present:
72                 time.sleep(0.2)
73
74             print "Ok"
75
76     except KeyboardInterrupt:
77         raise SystemExit
78     finally:
79         clf.close()
80
81     raise SystemExit
82
83 if __name__ == '__main__':
84     main()