
# Downloads contacts from the phonebook.
# BluetoothAutomation

from bluetoothautomation import *
import time
import code

deviceAddress = "<phone_bdaddress>"

# Use this for USB dongles.
# x = iOSUSBProvider.alloc().init()

x = iOSSerialProvider.alloc().initWithAddress_(bytearray((0x00, 0x11, 0x22, 0x33, 0x44, 0x55)))
paths = BAMDevice.allDevicePathsWithTransport_(x)
if len(paths) <= 0:
    raise Exception("Atleast one Bluetooth serial board must be plugged in.")

y = BAMDevice.deviceWithTransport_atPath_(x, paths[0])
y.setAllowConnect_(True)
y.setAllowDiscover_(True)

y.setEnabledServices_(kBAMServicePBAP)

try:
    if not y.pairWithDevice_service_(deviceAddress, y.enabledServices()):
        raise Exception("Failed to pair with PBAP.")

    print "Downloading all contacts."
    length = y.pbap().lengthOfPhonebook_repository_(kBAMPBAPPhonebookMain, kBAMPBAPRepositoryLocal)
    vCards = y.pbap().allvCardsInPhonebook_repository_(kBAMPBAPPhonebookMain, kBAMPBAPRepositoryLocal)
    
    if length != len(vCards):
        raise Exception("All contacts weren't downloaded.")

    if length > 0:
        print "The first contact is %s." % vCards[0][kBAMvCardName]

except:
	y.unpairFromDevice_(deviceAddress)
	raise

y.unpairFromDevice_(deviceAddress)
