I cannot share my complete source code because it is for a new product that is about to be released, but I will be glad to assist you. I am not using the TI SensorTag but I have designed a custom board that uses the TI CC2640 chip. This is similar to the TI CC 2650 used on the SensorTag.
Basically, there are several steps to connect and get data from the BLE device. A summary follows:
Note: Your code should be placed in the Starter file. This example assumes that the BLE manager is named Manager.
- Call Manager.Scan(Null)
- The event Manager_DeviceFound() is raised for each device found. This event contains the string name of the device, its serial number, advertising data and RSSI. You can determine if this is your device if the name string matches SensorTag (I believe that it is the default SensorTag string name) or the Id matches the SensorTag's serial number. If you are writing an app that can use multiple SensorTags, you will need to store the Id of each tag in a file on the phone for later comparison. If the event is raised with the Id that you want to connect to, call Manager.Connect2(Id, False). Connect2() allows a faster connection versus Connect()
- Once the connection has occurred, the event Manager_Connected() is raised with a list as the services available. Call Manager.ReadData(service) with the service UUID that you want to read.
- The event Manager_DataAvailable() is raised with the service Id string and the characteristics as a map. You can loop through each characteristic in the map to read its data. Alternately, I use Characteristics.ContainsKey(CharacteristicUUID) with a series of IF statements to look at only certain characteristics that I am interested in.
- Use Characteristics.Get(characteristicUUID) to get the the raw bytes from the characteristic. You will then have to convert the bytes into a format more usable such as an int, float, etc. Use ByteConverter to do this.
That is basically it. There are some other things to consider:
- Use Manager.Disconnect to disconnect from the target.
- Use Manager.SetNotify if a characteristic uses notifications. Note that you MAY NOT BE ABLE TO issue multiple SetNotify() calls for multiple characteristics one after another and expect them to be processed by Android. I have found that you need a delay of about 200-300 ms between each call for Android to process them. Use CallSubPlus to do this.
- Use Manager.WriteData to update a characteristic. Note that the event Manager_WriteComplete gets raised after each write is completed. Again, you may not be able to write multiple characteristics at the same time. If needed, use a queue that gets de-queued for each new characteristic update in Manager_WriteComplete.
Hopefully, this helps. Let me know if I can be of more assistance.