Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 356
Dave Avatar asked Nov 23 '25 05:11

Dave


1 Answers

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);
}
}
like image 81
Edison Avatar answered Nov 24 '25 19:11

Edison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!