
# Configures the Bluetooth device as a LE peripheral.
# BluetoothAutomation

from bluetoothautomation import *
import code


class PythonCallback(NSObject):
    def peripheralAdvertiseCompleted_(self, status):
        print("******** peripheralAdvertiseCompleted callback called with status: %d ***********", status)
    
    def peripheralDidConnect_(self, status):
        print("******** peripheralDidConnect callback called with status: %d ************", status)

x = ServiceProvider.alloc().init()

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.hardReset()

# Configure the device for LE.
y.setVerboseLogging_(kBAMLogLE | kBAMLogCore)
y.setEnabledServices_(kBAMServiceLE)
#y.setAllowConnect_(True)
#y.setAllowDiscover_(True)
y.le().setEnablePeripheral_(True)
y.le().initializeWithInputCapability_WithOutputCapability_(kBAMLEInputCapabilityKeyboard, kBAMLEOutputCapabilityDisplay)
y.le().setAddress_(kBAMLEAddressPublic)
y.le().setPasskey_(123456)


callback = PythonCallback.alloc().init().retain()
y.setBAMDeviceDelegate_(callback)

manager = BAMLEPeripheralManager.alloc().initWithDevice_(y)
hidService = LEHIDService.alloc().init()
batteryService = LEBatteryServerService.alloc().initWithLevel_(bytearray((0x32,0x00)))
diService = LEDIService.alloc().init()

manager.addService_(hidService)
manager.addService_(batteryService)
manager.addService_(diService)

manager.publish()

y.le().startUndirectedAdvertisingAsLimited_undirectedMode_txPower_data_solicitingServices_(False, kBAMLEAdModeConnectableUndirected, 1, bytearray((0x09, 0x08, 0x07)), None)

# Allow the user to input stuff.
code.interact(local=locals())

# Bye bye.
y.le().stopAdvertising()
