0

I am creating an app that is intended for QC/engineering tests to emulate an embedded system that has a battery. I am trying to make it so that my team and myself can change the battery level to an arbitrary value for testing with a UISlider or UITextField. But I keep finding that no matter what I do, the value of the Battery Level Characteristic always seems to be the iPhone's battery level!

In my first attempts, I set up a PeripheralManager object and populated it with the default Battery Service + Battery Level Characteristic:

// ------INIT BATTERY SERVICE--------
batteryServiceCBUID = CBUUID(string:SRV_Battery )
let batteryService = CBMutableService(type: batteryServiceCBUID, primary: false)

batteryLevelCharacterstic = CBMutableCharacteristic(type: CBUUID(string: CHK_BatteryLevel), properties: [ .read, .notify  ], value: nil, permissions: [.readable, .writeable])

if let battChar = batteryLevelCharacterstic{
    let batterylevelDescriptor = CBMutableDescriptor(type: CBUUID(string: DSK_BatteryLevel), value: value)
    
    battChar.descriptors = [batterylevelDescriptor]
    batteryService.characteristics = [ battChar]
}

Then I went ahead and just modify the characteristic just like I do with other custom characteristics:

func setBatteryLevel(value:UInt8){
    var passedValue = value
    let sampleBattLevel = Data(bytes: &passedValue, count: MemoryLayout<UInt8>.size)
    if let battChar = batteryLevelCharacterstic{
        let success = peripheralManager.updateValue(sampleBattLevel, for: battChar, onSubscribedCentrals: nil)
        if(!success){
            print(success)
        }
    }
}

I had read elsewhere on SO that it is possible that the peripheral is not ready to send data when updateValue is called so I made it setBatteryLevel also gets called in the delegate function:

func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) {
    print("peripheralManager toUpdateSubscribers: \(String(describing: peripheral.description))")
    setBatteryLevel(value: 45)
}

I can see in debug that "success" is true however I still do not observe a change in the value of the characteristic from my Central Device.

I've followed the same process in custom characteristics and had success. Is it possible that the Battery Level Characteristic is supplied by the OS and there's nothing I can do about it? Or am I doing something wrong in my code?

Arasuvel
  • 2,971
  • 1
  • 25
  • 40
jimBeaux27
  • 117
  • 7
  • 1
    "Is it possible that the Battery Level Characteristic is supplied by the OS and there's nothing I can do about it?". Yes. iOS supplies that characteristic value. Remember that the phone is a single BLE peripheral. CBPeripheral is an abstraction that allows apps to contribute characteristics and services to that peripheral. – Paulw11 Jul 28 '22 at 19:49
  • Thanks for the reply Paul. So it seems it is not possible to override the value. Thanks. – jimBeaux27 Jul 28 '22 at 20:42

0 Answers0