Connect by Service Name

There are cases where the service identifies itself not by a unique Service Class Id but by a particular Service Name. In these cases one should query the service records on the remote device, find which contains the expected Service Name, and use the RFCOMM channel (port) number from the record in the BluetoothEndPoint passed to Connect. For example:

Dim expectedSvcName As String = "FooBar"
Dim addrS As String = "001122334455"
Dim commonClass As Guid = BluetoothService.SerialPort ' e.g
Dim addr As BluetoothAddress = BluetoothAddress.Parse(addrS)
Dim bdi As New BluetoothDeviceInfo(addr)
Dim rcdList() As ServiceRecord = bdi.GetServiceRecords(commonClass)
Dim curSvcName As String
Dim portInteger As Integer = -1
For Each record As ServiceRecord In rcdList
  portInteger = ServiceRecordHelper.GetRfcommChannelNumber(record)
    curSvcName = record.GetPrimaryMultiLanguageStringAttributeById( _
  Catch ex As KeyNotFoundException ' No ServiceName attribute
    Continue For
  End Try
  Debug.Assert(curSvcName IsNot Nothing, "null ServiceName!?")
  If expectedSvcName.Equals(curSvcName, StringComparison.InvariantCulture) Then
    If portInteger = -1 Then
      Throw New InvalidOperationException("Selected Service is not RFCOMM")
    End If
    Exit For ' Success!
  End If
If portInteger = -1 Then
  Throw New InvalidOperationException("No Service found with the ServiceName")
End If
Dim port As Byte = CByte(portInteger) ' convert to byte now we know that it's valid
Dim rep As New BluetoothEndPoint(addr, BluetoothService.Empty, port)
Dim cli As New BluetoothClient()
... ...

Last edited Jan 26, 2012 at 8:32 PM by alanjmcf, version 3


No comments yet.