How to get the Battery Charge Level specifically in mWh (not percentage) for Mac (Cocoa or C)

主宰稳场 提交于 2019-12-23 17:12:07

问题


The title pretty much explains it all. I'm creating a mac app and I need the battery charge level specifically in mWh (not percentage). Would like to do it in C or Objective C preferably.

Thanks!


回答1:


Sorry, but I don't think the hardware has a way to report that. It's going to change over time as the battery gets on in its life cycle, and all you could know at the outset is the nominal capacity of the battery when it was installed.




回答2:


So here is a bit of code that directly answers my question which is getting the Battery Charge Level in mWh. It's not perfect, but it does the job.

 + (NSString* ) chargeInMWH 
  { 



CFMutableDictionaryRef matching , properties = NULL;
io_registry_entry_t entry = 0;
matching = IOServiceMatching( "IOPMPowerSource" );
entry = IOServiceGetMatchingService( kIOMasterPortDefault , matching );
IORegistryEntryCreateCFProperties( entry , &properties , NULL , 0 );



NSNumber * voltage = [[NSNumber alloc] initWithFloat:1.0];
NSNumber * currentCapacity= [[NSNumber alloc] initWithFloat:1.0];

voltage =  [properties objectForKey:@"Voltage"];    
currentCapacity =  [properties objectForKey:@"CurrentCapacity"];


int floatValue = [voltage intValue];
int floatValue2 = [currentCapacity intValue];
int answer = floatValue * floatValue2;

NSString *theCompleteAnswer = [[NSString alloc] initWithFormat:@"%i",answer];


CFRelease( properties );
IOObjectRelease( entry );


return theCompleteAnswer;

    }



回答3:


This probably doesn't help you, but I do know that the ioreg command line program can dump out all kinds of wonderful stats about your computer's battery, including design capacity, current capacity, and current charge level in mAh. (ioreg -l gives you really verbose output with all of this) If you can figure out what API that program uses, you could do the same.

Or you could just call the program from your app and capture the output.



来源:https://stackoverflow.com/questions/3290395/how-to-get-the-battery-charge-level-specifically-in-mwh-not-percentage-for-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!