Dave Dave - 4 months ago 19
Swift Question

SocketScan Getting the Battery Level in Swift

Whatever I seem to try I cannot currently get back the Battery level from the iOS/SocketScan API. I am using version 10.3.36, here is my code so far:

func onDeviceArrival(result: SKTRESULT, device deviceInfo: DeviceInfo!) {
print("onDeviceArrival:\(deviceInfo.getName())")
scanApiHelper.postGetBattery(deviceInfo, target: self, response: #selector(onGetBatteryInfo))

}

func onGetBatteryInfo(scanObj: ISktScanObject) {

let result:SKTRESULT = scanObj.Msg().Result()
print("GetBatteryInfo status:\(result)")

if (result == ESKT_NOERROR) {
let batterylevel = scanObj.Property().getUlong()
print("Battery is:\(batterylevel)")
} else {
print("Error GetBatteryInfo status:\(result)")
}


However, the values I get back are:

GetBatteryInfo status:0

Battery is:1677741312


If my code is correct then how do I make the Battery result I get back a meaningful result, like a percentage?
If I'm way off then how do I get back info like the battery level, firmware version etc?


Thanks

David

Answer

EDIT: SKTBATTERY_GETCURLEVEL isn't supported in Swift. However, the docs explain that the battery level response includes the min, current and max levels encoded in the first, second and third bytes, respectively.

The following is equivalent to using SKTBATTERY_GETCURLEVEL

Swift

func onGetBatteryInfo(scanObj: ISktScanObject) {

    let result:SKTRESULT = scanObj.Msg().Result()

    if(SKTSUCCESS(result)){

        let batteryInfo = scanObj.Property().getUlong();

        let batteryMin = ((batteryInfo >> 4) & 0xff);
        let batteryCurrent = ((batteryInfo >> 8) & 0xff);
        let batteryMax = ((batteryInfo >> 12) & 0xff);

        let batteryPercentage = batteryCurrent / (batteryMax - batteryMin);
        print("Battery is:\(batteryPercentage)")

        self.setBatteryLevel = batteryPercentage
        self.tableView.reloadData

    } else {

        print("Error GetBatteryInfo status:\(result)")
    }
}

Objective-C

-(void) onGetBatteryInfo:(ISktScanObject*)scanObj {

SKTRESULT result=[[scanObj Msg]Result];
if(SKTSUCCESS(result)){

    long batteryLevel = SKTBATTERY_GETCURLEVEL([[scanObj Property] getUlong]);
    NSLog(@"BatteryInfo %ld", batteryLevel);

    [self setBatteryLevel:batteryLevel];
    [self.tableView reloadData];

} else {

    NSLog(@"Error GetBatteryInfo status: %ld",result);
}
}
Comments