pablojimenezmateo / GodotAndroidBluetoothPlugin

Android Studio project for GodotAndroidBluetooth
35 stars 5 forks source link

Get manufacturer data and duplicate devices #5

Closed IanBUK closed 1 year ago

IanBUK commented 1 year ago

This PR adds two things: 1) A flag that can be set with setReportDuplicates(bool report) and tested with getReportDuplicates() that allows the consumer to determine whether devices are reported each time they are detected, or just the first time. This currently defaults to true, so duplicates will be reported.

2) The object sent in _on_device_found, from the function public void sendNewDevice(ScanResult newDevice) has an additional member manufacturerData that contains newDevice.getScanRecord().getBytes(). This allows the consumer to read the BLE advert sent from the device.

The two changes combined allow me to send data from the device, in the manufacturerData part of the BLE advert, so that I can receive continually updated data from it without connecting.

For example, the following snippet retrieves the manufacturer ID and battery level from the advert, given the appropriate indexes. BLE places the manufacturer ID in a particular place, and here the battery percentage of the sensor is placed in the 20th byte. The result is added to the devices_list shown in the main sample for this repo at GodotAndroidBluetoothDemo

var INDEX_MANUFACTURER_ID_LOW = 0;   
var INDEX_MANUFACTURER_ID_HIGH = 1; 
var INDEX_BATTERY = 20;
func inflateRHBSensorAdvert(new_device):
    var offset = 10
    var advert = new_device.manufacturerData

    var manufacturerIdBytes = advert.subarray(offset + INDEX_MANUFACTURER_ID_LOW, offset + INDEX_MANUFACTURER_ID_HIGH)
    var manufacturerIdHex = manufacturerIdBytes.hex_encode()
    var manufacturerIdLow = manufacturerIdHex[0]+manufacturerIdHex[1]
    var manufacturerIdHigh = manufacturerIdHex[2]+manufacturerIdHex[3]

    var battery =   advert[offset + INDEX_BATTERY]

    devices_list.add_item(new_device.name + " " + manufacturerIdHigh + manufacturerIdLow + " " + str(battery) + "% ")

The readme.md file has been updated to show these changes.