CE Controller

Class CEController:

The class is used to interact with the central controller which communicates with BLE:Bit.

Constructing a CEntral Controller object

import cybervelia.sdk.controller.ce.CEController;
import cybervelia.sdk.controller.ce.CEBLEDeviceCallbackHandler;

static void main(){
    CEController ce = new CEController("COM1", new CEBLEDeviceCallbackHandler());
}

Available Member Methods

Connect to a target

There are two methods that could be used for connecting to a target:

A non-blocking method:

public boolean connect(String address, ConnectionTypesCommon.AddressType type) throws IOException

Parameters:

  • byte []addr - The bluetooth address in hexadecimal format i.e FF:EE:BB:FF:AA:BB
  • ConnectionTypesCommon.AddressType type - The address type of target device

Returns Boolean:

True if connection succeeded or False when connection failed.

The method blocks until the device is connected or when the connection has failed/timed-out:

public boolean connectNow(String address, ConnectionTypesCommon.AddressType type) throws IOException

Parameters:

  • byte []addr - The bluetooth address in hexadecimal format i.e FF:EE:BB:FF:AA:BB
  • ConnectionTypesCommon.AddressType type - The address type of target device

Returns Boolean:

True if connection succeeded or False when connection failed.

Read LTK Own Key

public int readLTKOwnKey(byte[] data) throws IOException

Read our own key from BLE:Bit and store the key in parameter data

Parameters:

  • byte[] data - The buffer to store the LTK key

Returns int:

The length of key in bytes

Read LTK Peer Key

public int readLTKPeerKey(byte[] data) throws IOException 

Read the peer key from BLE:Bit and store the key in parameter data

Parameters:

  • byte[] data - The buffer to store the peer's LTK key

Returns int:

The length of key in bytes

Check Initialization

Then a CEController object is created, the device is initialized.

Example: When the port used for a CEController is instead a BLE:Bit PE device, and the port used for a PEController is instead a BLE:Bit CE device, then this method will return false in both object's invocation of method isInitializedCorrectly(). In that case, a call to switchIO() in both objects must follow in order to switch I/O and continue the session. The reason for switching and not re-creating the objects it's because the BLE:Bit devices are already initialized and have already changed state. Recreating the objects is unnecessary.

public boolean isInitializedCorrectly()

Parameters: None

Returns: boolean

True when the device is initialized correctly, False when the device failed to be initialized as the expected controller.

Switching IO

public InputStream getInputStream()
public OutputStream getOutputStream()
public BLESerialPort getSerialPort()
public short getFirmwareVersion()
public void switchIO(InputStream in, OutputStream out, BLESerialPort port, short firmwarev) throws IOException

When two BLE:Bit devices with different controllers are used, one cannot determine which devices has which controller only be reviewing the USB bridge SoC driver's name. Therefore, when a wrong port is selected, the method isInitializedCorrectly() can be used to detect that error. When this is the case, the above methods can be used to correct that anomaly. Then, the methods can be used as shown below:

    /* Identify the correct device (ce or pe ) and switch IO if that is deemed necessary */
    private static void switchIO(String[] found_ports, CEController ce, PEController pe) throws IOException {
        if (!ce.isInitializedCorrectly() && !pe.isInitializedCorrectly())
        {
            // Get SerialPort InputStream and OutputStream
            InputStream ce_in = ce.getInputStream();
            OutputStream ce_out = ce.getOutputStream();
            // Get Firmware version retrieved from BLE:Bit during initialization stage
            short ce_fw = ce.getFirmwareVersion();
            // get Serial Port
            BLESerialPort ce_port = ce.getSerialPort();
            // Exchange Ports
            String serial_ce = found_ports[0];
            found_ports[0] = found_ports[1];
            found_ports[1] = serial_ce;
            // Switch Input/Output streams, Serial Ports and Firmware Version
            ce.switchIO(pe.getInputStream(), pe.getOutputStream(), pe.getSerialPort(), pe.getFirmwareVersion());
            pe.switchIO(ce_in, ce_out, ce_port, ce_fw);

        }
        else if ((ce.isInitializedCorrectly() ^ pe.isInitializedCorrectly()))
        {
            System.exit(1);
        }
    }

Sending Connection Parameters

Note: Must be used before invoking the method finishSetup()

public void sendConnectionParameters(CEConnectionParameters ceparameters) throws IOException

Parameters:

  • ceparameters - An object of class CEConnectionParameters that holds the connection parameters

Returns: void

Set Device Bluetooth Device Address

Note: Must be used before invoking the method finishSetup()

public void sendBluetoothDeviceAddress(String address, ConnectionTypesCommon.BITAddressType address_type) throws IOException 

Parameters:

  • address - The hexadecimal format address, semi-colon separated ie. aa:bb:cc:aa:bb:cc
  • address_type - The type of address specified as a ConnectionTypesCommon.BITAddressType

Returns: void

Disable Repairing after bonding

Note: Must be used before invoking the method finishSetup()

public void deviceDisableRepairingAfterBonding() throws IOException

When there is an LTK key for the target device, do not attempt to repair with the device.

Parameters: None

Returns: void

Delete all Long Term Keys

Note: Must be used before invoking the method finishSetup()

public void eraseBonds() throws IOException

Parameters: None

Returns: void

Delete Long Term Key per device

Note: You may delete peer's keys only when you are disconnected and no advertising/scan is in place - otherwise the call will fail

public boolean deletePeerBond(short peer_id)

When the device has successfully paired with a target, then target is associated with a peer-id.

Parameters:

  • peer_id - The peer-id of the target

Returns: boolean

Returns true when the keys has been erased or false when the call has failed to complete.

Request bonding when a connection is achieved

Note: Must be used before invoking the method finishSetup()

public void bondOnConnect(boolean force_repairing) throws IOException 

As soon a target is connected, initiate pairing.

Parameters:

  • force_repairing - Force bond repairing when the keys are missing

Returns: void

Get ready for action - Finish Setup

When the device has been configured properly, then the finishSetup() must be invoked in order to force the device to change into a state which can connect to a target, scan etc.

public void finishSetup() throws IOException 

Parameters: None

Returns: void

Check if the communication is encrypted

public boolean isBonded()

Parameters: None

Returns: boolean

Returns true only if the device has established a secure communication with the target.

Configure Pairing Method

Note: Must be used before invoking the method finishSetup()

public void configurePairing(ConnectionTypesCommon.PairingMethods p_method, String static_pin) throws IOException

Parameters:

  • p_method - Pairing method, a type of ConnectionTypesCommon.PairingMethods
  • pin (optional) - A static PIN

Returns: void

Conn. request in progress

public boolean isConnectRequestInProgress()

Parameters: None

Returns: boolean

Returns true when a connection request has been sent but the connection has not been established/failed yet.

Cancel connection request

public boolean cancelConnectRequest() throws IOException 

Parameters: None

Returns: boolean

Returns true if the connection request has been canceled

Start Scan

public boolean startScan() 

Parameters: None

Returns: boolean

Returns true if the scan has been initiated successfully or false when the scan has failed

Stop Scan

The stop scan request prompts the device to stop scanning. The call is asynchronous. When the BLE:Bit has stopped scanning an event is sent asynchronously. Ref: CEScanCallback

public void stopScan() 

Parameters: None

Returns: void

isDeviceConnected

public boolean isDeviceConnected()

Parameters: None

Returns: boolean

Returns true if there is a connection has been established with a target or false when there is no connection established

Get the address of the connected device

public String getConnectedDeviceAddress()

Parameters: None

Returns: String

Returns the hexadecimal-format of the address of the peer device

Get peer device's address type

public ConnectionTypesCommon.AddressType getConnectedDeviceAddressType()

Parameters: None

Returns: ConnectionTypesCommon.AddressType

Returns the type of the address which is of type ConnectionTypesCommon.AddressType

Get disconnected reason

public int getDisconnectionReason()

Parameters: None

Returns: int

Returns the reason as a numerical form, which defines the disconnection reason. The encoded reasons are taken from the actual LE-frame, and are defined by the Bluetooth Sig Spec. and can be found below:

  • Authentication Failure - 0x05
  • Remote User Terminated Connection - 0x13
  • Connection Terminated by Local Host - 0x16
  • Remote device terminated connection due to low resources - 0x14
  • Remote device terminated connection due to Power Off - 0x15
  • Unsupported Remote Feature - 0x15
  • Pairing with Unit Key Not Supported error code - 0x29
  • Unacceptable Connection Parameters - 0x3B

Disconnect

public void disconnect(int reason)

Parameters:

  • reason - Disconnect from the target by specifying a reason

The encoded reasons are defined by the Bluetooth Sig Spec. and can be found below:

  • Authentication Failure - 0x05
  • Remote User Terminated Connection - 0x13
  • Connection Terminated by Local Host - 0x16
  • Remote device terminated connection due to low resources - 0x14
  • Remote device terminated connection due to Power Off - 0x15
  • Unsupported Remote Feature - 0x15
  • Pairing with Unit Key Not Supported error code - 0x29
  • Unacceptable Connection Parameters - 0x3B

Returns: void

Initiate Service Discovery

public boolean startDiscovery(boolean block)

Parameters:

  • block - The argument determines if the method shall work as asynchronous or synchronous. If block is set as true, the method shall work as a synchronous method and will block until the discovery has been finished (or failed)

Returns: boolean

Returns true if the discovery was successful or false when the discovery has failed. Please note that the value will always be true in case the block parameter is set as false.

Get discovered services

public List<BLEService> getDiscoveredServices()

Parameters: None

Returns: List<BLEService>

Returns a list with BLEService objects. The list contains the services discovered during the service discovery procedure. The services are placed into the list only when a discovery has been finished.

Get discovery process

This method is useful only when the discovery has been initiated asynchronously.

public boolean isDiscoveryInProgress()

Parameters: None

Returns: boolean

Returns true if the device is in the discovery mode, false when the device is not in discovery mode

Get discovery status

This method is useful only when the discovery has been initiated asynchronously.

public boolean getDiscoverySuccess()

Parameters: None

Returns: boolean

Returns the discovery status. When the discovery process succeeded the method shall return true.

Clear Cached Services

When a discovery process for a particular target has already done once, the discovery process is not going to start again until the cache is found to be empty. The returned services will always be the same until the cache is found to be empty.

public void clearCachedServices(String client_address)

Parameters:

  • client_address - The hexadecimal format of the target address

Returns: void

Writing data to characteristics

There are three methods that can be used to write data to a characteristic as shown below:

public boolean writeData(byte []data, int offset, int len, short handle) throws IOException
public boolean writeData(byte []data, int offset, int len, short handle, int tm_ms) throws IOException
public void writeDataCMD(byte []data, int offset, int len, short handle) throws IOException

To get the characteristic's handle, use the methods getValueHandle() or getCCCDHandle() on an object of the class BLECharacteristic.

Reading data from characteristics

There are two methods that can be used to read data from a characteristic, as shown below:

public int readData(byte[] data, int offset, int len, short handle) throws IOException

Parameters:

  • data - Buffer to store data
  • offset - Offset from the start of given array
  • len - Maximum available buffer
  • handle - The handle of characteristic

Returns: int

Returns the length of available data

public int readData(byte[] data, int offset, int len, short handle, int tm_ms) throws IOException

Parameters:

  • data - Buffer to store data
  • offset - Offset from the start of given array
  • len - Maximum available buffer
  • handle - The handle of characteristic
  • tm_ms - Timeout in milliseconds

Returns: int

Returns the length of available data

Receive Notifications

For the peripheral to be able to notify or indicate a message to a central, the notifications/indications must be enabled as shown below:

public boolean enableNotifications(short cccd_handle)
public boolean enableIndications(short cccd_handle)

The following methods are used to disable the notifications/indications:

public boolean disableNotifications(short cccd_handle)
public boolean disableIndications(short cccd_handle)

The return value indicates whenever the feature has been enabled or not. Returning true, means the feature is enabled.

Bond Now

public boolean bondNow(boolean force_repairing)

Parameters:

  • force_repairing - Force the device to repair

Returns: boolean

Returns true of the device has bonded successfully.

Terminate the session with BLE:Bit

The following method force the BLE:Bit to perform a soft-reset.

public void terminate()

Get characteristic by handle

When the characteristics have been discovered successfully, by the invocation of the method startDiscovery(), then one may retrieve the characteristic object by calling the following methods using the characteristic's handle and the address of the peer device:

public BLECharacteristic getCharacteristicByHandle(short handle, String client_address)
public BLECharacteristic getCharacteristicByCCCDHandle(short handle, String client_address)

Available Static Methods

Reset

public static boolean reset(String device_port)

Parameters:

  • String device_port - The COM/tty/ACM/USB port of the device

Returns: boolean

Returns true if the device has been reset successfully, or false when the reset has failed