/**
* @see org.javabluetooth.stack.BluetoothStack#connectL2CAPChannel(org.javabluetooth.stack.l2cap.L2CAPChannel,
* javax.bluetooth.RemoteDevice, short)
*/
public void connectL2CAPChannel(L2CAPChannel channel, RemoteDevice remoteDevice, short psm) throws HCIException {
if (!isConnected) throw new HCIException("BluetoothTCPClient is not connected.");
short channelHandle = -1;
for (int i = 0; i < channels.length; i++) {
if (channels[i] == null) {
channels[i] = channel;
channel.l2capSender = this;
channel.remoteAddress = remoteDevice.bdAddrLong;
channelHandle = (short)i;
break;
}
}
if (channelHandle == -1) throw new HCIException("Connect L2CAPChannel failed. No Open Channel Slots.");
byte[] createL2CAPChannelRequest = {
L2CAP_CREATE_CONNECTION_REQUEST, 0x0e, 0x00, //fixed length 14
(byte)((channelHandle) & 0xff), (byte)((channelHandle >> 8) & 0xff), (byte)((psm) & 0xff), (byte)((psm >> 8) & 0xff),
(byte)((remoteDevice.bdAddrLong) & 0xff), (byte)((remoteDevice.bdAddrLong >> 8) & 0xff),
(byte)((remoteDevice.bdAddrLong >> 16) & 0xff), (byte)((remoteDevice.bdAddrLong >> 24) & 0xff),
(byte)((remoteDevice.bdAddrLong >> 32) & 0xff), (byte)((remoteDevice.bdAddrLong >> 40) & 0xff),
remoteDevice.pageScanRepMode, remoteDevice.pageScanMode, (byte)((remoteDevice.clockOffset) & 0xff),
(byte)((remoteDevice.clockOffset >> 8) & 0xff)
};
try {
Debug.println(6, "BluetoothTCPClient: Sending L2CAP Create Connection Request:", createL2CAPChannelRequest);
socketOut.write(createL2CAPChannelRequest);
socketOut.flush();
}
catch (IOException e) {
cleanExit();
throw new HCIException("IOException: " + e);
}
int timeout = 0;
while (channel.channelState == L2CAPChannel.CLOSED) {
try {
Thread.sleep(1000);
timeout++;
}
catch (InterruptedException e) { }
if (timeout == 100) throw new HCIException("Connect L2CAPChannel timed out.");
}
if (channel.channelState == L2CAPChannel.FAILED) throw new HCIException("Connect L2CAPChannel failed.");
}