Skip to content

Instantly share code, notes, and snippets.

@marchbold
Created October 19, 2015 07:51
Show Gist options
  • Save marchbold/ce7dd52e54d17b09ff73 to your computer and use it in GitHub Desktop.
Save marchbold/ce7dd52e54d17b09ff73 to your computer and use it in GitHub Desktop.
Bluetooth LE: Connecting to a discovered peripheral
var activePeripheral:Peripheral = null;
BluetoothLE.service.centralManager.addEventListener( PeripheralEvent.DISCOVERED, central_peripheralDiscoveredHandler );
BluetoothLE.service.centralManager.addEventListener( PeripheralEvent.CONNECT, central_peripheralConnectHandler );
BluetoothLE.service.centralManager.addEventListener( PeripheralEvent.CONNECT_FAIL, central_peripheralConnectFailHandler );
BluetoothLE.service.centralManager.addEventListener( PeripheralEvent.DISCONNECT, central_peripheralDisconnectHandler );
BluetoothLE.service.centralManager.scanForPeripherals();
...
private function central_peripheralDiscoveredHandler( event:PeripheralEvent ):void
{
trace( "connecting to peripheral: "+ event.peripheral.name );
// You should make some decision about whether this peripheral is the one you wish to connect to
// either store the peripheral and ask the user or determine by services available
// For this example we are just going to blindly connect to every discovered peripheral
BluetoothLE.service.centralManager.connect( event.peripheral );
}
private function central_peripheralConnectHandler( event:PeripheralEvent ):void
{
trace( "peripheral connected: "+ event.peripheral.toString() );
// Store the peripheral for further interaction
activePeripheral = event.peripheral;
}
private function central_peripheralConnectFailHandler( event:PeripheralEvent ):void
{
trace( "peripheral connect fail: "+ event.peripheral.name );
activePeripheral = null;
}
private function central_peripheralDisconnectHandler( event:PeripheralEvent ):void
{
trace( "peripheral disconnect: "+ event.peripheral.name );
activePeripheral = null;
}
// com.distriqt.BluetoothLE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment