WPS: Add support for NFC connection handover with nfcpy
authorJouni Malinen <j@w1.fi>
Sun, 4 Nov 2012 14:04:42 +0000 (16:04 +0200)
committerJouni Malinen <j@w1.fi>
Sun, 4 Nov 2012 14:04:42 +0000 (16:04 +0200)
This helper script can now handle both reading of a NFC tag and
initiation of NFC connection handover if a peer NFC device is touched.

Signed-hostap: Jouni Malinen <j@w1.fi>

wpa_supplicant/examples/wps-nfc.py

index 634ea6b..0cfc1f6 100755 (executable)
@@ -12,6 +12,8 @@ import time
 
 import nfc
 import nfc.ndef
+import nfc.llcp
+import nfc.handover
 
 import wpactrl
 
@@ -47,6 +49,62 @@ def wpas_tag_read(message):
     print wpas.request("WPS_NFC_TAG_READ " + message.encode("hex"))
 
 
+def wpas_get_handover_req():
+    wpas = wpas_connect()
+    if (wpas == None):
+        return None
+    return wpas.request("NFC_GET_HANDOVER_REQ NDEF WPS").rstrip().decode("hex")
+
+
+def wpas_put_handover_sel(message):
+    wpas = wpas_connect()
+    if (wpas == None):
+        return
+    print wpas.request("NFC_RX_HANDOVER_SEL " + str(message).encode("hex"))
+
+
+def wps_handover_init(peer):
+    print "Trying to initiate WPS handover"
+
+    data = wpas_get_handover_req()
+    if (data == None):
+        print "Could not get handover request message from wpa_supplicant"
+        return
+    print "Handover request from wpa_supplicant: " + data.encode("hex")
+    message = nfc.ndef.Message(data)
+    print "Parsed handover request: " + message.pretty()
+
+    nfc.llcp.activate(peer);
+    time.sleep(0.5)
+
+    client = nfc.handover.HandoverClient()
+    try:
+        print "Trying handover";
+        client.connect()
+        print "Connected for handover"
+    except nfc.llcp.ConnectRefused:
+        print "Handover connection refused"
+        nfc.llcp.shutdown()
+        client.close()
+        return
+
+    print "Sending handover request"
+
+    if not client.send(message):
+        print "Failed to send handover request"
+
+    print "Receiving handover response"
+    message = client._recv()
+    print "Handover select received"
+    print message.pretty()
+    wpas_put_handover_sel(message)
+
+    print "Remove peer"
+    nfc.llcp.shutdown()
+    client.close()
+    print "Done with handover"
+
+
 def wps_tag_read(tag):
     if len(tag.ndef.message):
         message = nfc.ndef.Message(tag.ndef.message)
@@ -71,13 +129,18 @@ def main():
 
     try:
         while True:
-            print "Waiting for a tag to be touched"
+            print "Waiting for a tag or peer to be touched"
 
             while True:
-                tag = clf.poll()
+                general_bytes = nfc.llcp.startup({})
+                tag = clf.poll(general_bytes)
                 if tag == None:
                     continue
 
+                if isinstance(tag, nfc.DEP):
+                    wps_handover_init(tag)
+                    break
+
                 if tag.ndef:
                     wps_tag_read(tag)
                     break