forked from gsly/OS-X-ACPI-Battery-Driver
-
Notifications
You must be signed in to change notification settings - Fork 57
/
AppleSmartBattery.cpp
1913 lines (1631 loc) · 66.3 KB
/
AppleSmartBattery.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2005 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/* Modification History
*
* Unknown date: Original mods credit to glsy/insanelymac.com
*
* 2012-08-31, RehabMan/tonymacx86.com.
* - Integrate zprood's hack to gather cycle count as extra field in _BIF.
* - Also fix bug where if boot with no batteries installed, incorrect
* "Power Soure: Battery" was displayed in Mac menu bar.
* - Also a few other changes to get battery status to show in System Report
*
* 2012-09-02, RehabMan/tonymacx86.com
* - Fix bug where code assumes that "not charging" means 100% charged.
* - Minor code cleanup (const issues)
* - Added code to set warning/critical levels
*
* 2012-09-10, RehabMan/tonymacx86.com
* - Added ability to get battery temperature thorugh _BIF method
*
* 2012-09-19, RehabMan/tonymacx86.com
* - Calculate for watts correctly in case ACPI is reporting watts instead
* of amps.
*
* 2012-09-21, RehabMan/tonymacx86.com
* - In preparation to merge probook and master branches, validate
* _BIX, and _BBIX methods before attempting to use them.
*
*/
#include <IOKit/IOTimerEventSource.h>
#include <IOKit/IOWorkLoop.h>
#include <IOKit/IOTimerEventSource.h>
#include <IOKit/pwr_mgt/RootDomain.h>
//#include <IOKit/pwr_mgt/IOPMPrivate.h> //rehabman: I don't have this header in latest xcode
#include <libkern/c++/OSObject.h>
#include "AppleSmartBatteryManager.h"
#include "AppleSmartBattery.h"
// Retry attempts on command failure
enum {
kRetryAttempts = 5,
kInitialPollCountdown = 5,
kIncompleteReadRetryMax = 10
};
enum
{
kSecondsUntilValidOnWake = 30,
kPostChargeWaitSeconds = 120,
kPostDischargeWaitSeconds = 120
};
enum
{
kDefaultPollInterval = 0,
kQuickPollInterval = 1
};
#define kErrorRetryAttemptsExceeded "Read Retry Attempts Exceeded"
#define kErrorOverallTimeoutExpired "Overall Read Timeout Expired"
#define kErrorZeroCapacity "Capacity Read Zero"
#define kErrorPermanentFailure "Permanent Battery Failure"
#define kErrorNonRecoverableStatus "Non-recoverable status failure"
// Polling intervals
// The battery kext switches between polling frequencies depending on
// battery load
static uint32_t milliSecPollingTable[2] =
{
30000, // 0 == Regular 30 second polling
1000 // 1 == Quick 1 second polling
};
// Keys we use to publish battery state in our IOPMPowerSource::properties array
static const OSSymbol *_MaxErrSym = OSSymbol::withCString(kIOPMPSMaxErrKey);
static const OSSymbol *_DeviceNameSym = OSSymbol::withCString(kIOPMDeviceNameKey);
static const OSSymbol *_FullyChargedSym = OSSymbol::withCString(kIOPMFullyChargedKey);
static const OSSymbol *_AvgTimeToEmptySym = OSSymbol::withCString("AvgTimeToEmpty");
static const OSSymbol *_AvgTimeToFullSym = OSSymbol::withCString("AvgTimeToFull");
static const OSSymbol *_InstantTimeToEmptySym = OSSymbol::withCString("InstantTimeToEmpty");
static const OSSymbol *_InstantTimeToFullSym = OSSymbol::withCString("InstantTimeToFull");
static const OSSymbol *_InstantAmperageSym = OSSymbol::withCString("InstantAmperage");
static const OSSymbol *_ManufactureDateSym = OSSymbol::withCString(kIOPMPSManufactureDateKey);
static const OSSymbol *_DesignCapacitySym = OSSymbol::withCString(kIOPMPSDesignCapacityKey);
static const OSSymbol *_QuickPollSym = OSSymbol::withCString("Quick Poll");
static const OSSymbol *_TemperatureSym = OSSymbol::withCString(kIOPMPSBatteryTemperatureKey);
static const OSSymbol *_CellVoltageSym = OSSymbol::withCString("CellVoltage");
static const OSSymbol *_ManufacturerDataSym = OSSymbol::withCString("ManufacturerData");
static const OSSymbol *_PFStatusSym = OSSymbol::withCString("PermanentFailureStatus");
static const OSSymbol *_TypeSym = OSSymbol::withCString("BatteryType");
static const OSSymbol *_ChargeStatusSym = OSSymbol::withCString(kIOPMPSBatteryChargeStatusKey);
static const OSSymbol *_RunTimeToEmptySym = OSSymbol::withCString("RunTimeToEmpty");
static const OSSymbol *_RelativeStateOfChargeSym = OSSymbol::withCString("RelativeStateOfCharge");
static const OSSymbol *_AbsoluteStateOfChargeSym = OSSymbol::withCString("AbsoluteStateOfCharge");
static const OSSymbol *_RemainingCapacitySym = OSSymbol::withCString("RemainingCapacity");
static const OSSymbol *_AverageCurrentSym = OSSymbol::withCString("AverageCurrent");
static const OSSymbol *_CurrentSym = OSSymbol::withCString("Current");
/* _FirmwareSerialNumberSym represents the manufacturer's 16-bit serial number in
numeric format.
*/
static const OSSymbol *_FirmwareSerialNumberSym = OSSymbol::withCString("FirmwareSerialNumber");
/* _SoftwareSerialSym == AppleSoftwareSerial
represents the Apple-generated user readable serial number that will appear
in the OS and is accessible to users.
*/
static const OSSymbol *_BatterySerialNumberSym = OSSymbol::withCString("BatterySerialNumber");
static const OSSymbol *_DateOfManufacture = OSSymbol::withCString("Date of Manufacture");
static const OSSymbol * unknownObjectKey = OSSymbol::withCString("Unknown");
OSDefineMetaClassAndStructors(AppleSmartBattery, IOPMPowerSource)
/******************************************************************************
* AppleSmartBattery::ACPIBattery
*
******************************************************************************/
AppleSmartBattery * AppleSmartBattery::smartBattery(void)
{
AppleSmartBattery * me;
me = new AppleSmartBattery;
if (me && !me->init())
{
me->release();
return NULL;
}
return me;
}
/******************************************************************************
* AppleSmartBattery::init
*
******************************************************************************/
bool AppleSmartBattery::init(void)
{
if (!super::init()) {
return false;
}
fProvider = NULL;
fWorkLoop = NULL;
fPollTimer = NULL;
fTracker = NULL;
fCellVoltages = NULL;
return true;
}
/******************************************************************************
* AppleSmartBattery::free
*
******************************************************************************/
void AppleSmartBattery::free(void)
{
fPollTimer->cancelTimeout();
fWorkLoop->disableAllEventSources();
clearBatteryState(true);
super::free();
}
/******************************************************************************
* AppleSmartBattery::start
*
******************************************************************************/
bool AppleSmartBattery::loadConfiguration()
{
// build configuration dictionary
OSDictionary* config = OSDynamicCast(OSDictionary, fProvider->getProperty(kConfigurationInfoKey));
if (!config)
return false;
// allow overrides from RMCF ACPI method
OSDictionary* merged = NULL;
OSDictionary* custom = fProvider->getConfigurationOverride("RMCF");
if (custom)
{
DebugOnly(fProvider->setProperty("Configuration.Override", custom));
merged = OSDictionary::withDictionary(config);
if (merged && merged->merge(custom))
{
DebugOnly(fProvider->setProperty("Configuration.Merged", merged));
config = merged;
}
custom->release();
}
if (OSNumber* debugPollingSetting = OSDynamicCast(OSNumber, config->getObject(kBatteryPollingDebugKey)))
{
/* We set our polling interval to the "BatteryPollingPeriodOverride" property's value,
in seconds.
Polling Period of 0 causes us to poll endlessly in a loop for testing.
*/
fPollingInterval = debugPollingSetting->unsigned32BitValue();
fPollingOverridden = true;
}
else
{
fPollingInterval = kDefaultPollInterval;
fPollingOverridden = false;
}
// Check if we should use extended information in _BIX (ACPI 4.0) or older _BIF
fUseBatteryExtendedInformation = false;
if (OSBoolean* useExtendedInformation = OSDynamicCast(OSBoolean, config->getObject(kUseBatteryExtendedInfoKey)))
{
fUseBatteryExtendedInformation = useExtendedInformation->isTrue();
if (fUseBatteryExtendedInformation && kIOReturnSuccess != fProvider->validateBatteryBIX())
fUseBatteryExtendedInformation = false;
}
if (fUseBatteryExtendedInformation)
AlwaysLog("Using ACPI extended battery information method _BIX\n");
else
AlwaysLog("Using ACPI regular battery information method _BIF\n");
// Check if we should use extra information in BBIX
fUseBatteryExtraInformation = false;
if (OSBoolean* useExtraInformation = OSDynamicCast(OSBoolean, config->getObject(kUseBatteryExtraInfoKey)))
{
fUseBatteryExtraInformation = useExtraInformation->isTrue();
if (fUseBatteryExtraInformation && kIOReturnSuccess != fProvider->validateBatteryBBIX())
fUseBatteryExtraInformation = false;
}
if (fUseBatteryExtraInformation)
AlwaysLog("Using ACPI extra battery information method BBIX\n");
OSBoolean* flag;
// Check whether to use fDesignVoltage in _BST or fCurrentVoltage
flag = OSDynamicCast(OSBoolean, config->getObject(kUseDesignVoltageForDesignCapacity));
fUseDesignVoltageForDesignCapacity = flag && flag->isTrue() ? true : false;
flag = OSDynamicCast(OSBoolean, config->getObject(kUseDesignVoltageForMaxCapacity));
fUseDesignVoltageForMaxCapacity = flag && flag->isTrue() ? true : false;
flag = OSDynamicCast(OSBoolean, config->getObject(kUseDesignVoltageForCurrentCapacity));
fUseDesignVoltageForCurrentCapacity = flag && flag->isTrue() ? true : false;
// Check whether to correct to be certain CurrentCapacity<=MaxCapacity<=DesignCapacity
flag = OSDynamicCast(OSBoolean, config->getObject(kCorrectCorruptCapacities));
fCorrectCorruptCapacities = flag && flag->isTrue() ? true : false;
// Check whether to correct for 16-bit signed current capacity from _BST
flag = OSDynamicCast(OSBoolean, config->getObject(kCorrect16bitSignedCurrentRate));
fCorrect16bitSignedCurrentRate = flag && flag->isTrue() ? true : false;
// Get divisor to be used when estimating CycleCount
fEstimateCycleCountDivisor = 6;
if (OSNumber* estimateCycleCountDivisor = OSDynamicCast(OSNumber, config->getObject(kEstimateCycleCountDivisorInfoKey)))
fEstimateCycleCountDivisor = estimateCycleCountDivisor->unsigned32BitValue();
// Get cap for reported amperage
fCurrentDischargeRateMax = 0;
if (OSNumber* currentDischargeRateMax = OSDynamicCast(OSNumber, config->getObject(kCurrentDischargeRateMaxInfoKey)))
fCurrentDischargeRateMax = currentDischargeRateMax->unsigned32BitValue();
fFirstPollDelay = 7500;
if (OSNumber* firstPollDelay = OSDynamicCast(OSNumber, config->getObject(kFirstPollDelay)))
fFirstPollDelay = firstPollDelay->unsigned32BitValue();
// Configuration done, release allocated merged configuration
OSSafeRelease(merged);
return true;
}
bool AppleSmartBattery::start(IOService *provider)
{
fProvider = OSDynamicCast(AppleSmartBatteryManager, provider);
if (!fProvider || !super::start(provider)) {
return false;
}
// load the configuration from Info.plist and ACPI overrides
if (!loadConfiguration())
return false;
// allocate memory for fCellVoltages
fCellVoltages = OSArray::withCapacity(NUM_CELLS);
if (!fCellVoltages)
return false;
for (int i = 0; i < NUM_CELLS; i++)
{
OSNumber* num = OSNumber::withNumber(0ULL, NUM_BITS);
if (!num)
return false;
fCellVoltages->setObject(num);
}
// Initialize other state...
fBatteryPresent = false;
fACConnected = false;
fACChargeCapable = false;
// Make sure that we read battery state at least 5 times at 30 second intervals
// after system boot.
fInitialPollCountdown = kInitialPollCountdown;
fWorkLoop = getWorkLoop();
fPollTimer = IOTimerEventSource::timerEventSource( this,
OSMemberFunctionCast( IOTimerEventSource::Action,
this, &AppleSmartBattery::pollingTimeOut) );
if( !fWorkLoop || !fPollTimer
|| (kIOReturnSuccess != fWorkLoop->addEventSource(fPollTimer)))
{
return false;
}
// get tracker for status of other batteries
fTracker = OSDynamicCast(BatteryTracker, waitForMatchingService(serviceMatching(kBatteryTrackerService)));
this->setName("AppleSmartBattery");
// Publish the intended period in seconds that our "time remaining"
// estimate is wildly inaccurate after wake from sleep.
setProperty( kIOPMPSInvalidWakeSecondsKey, kSecondsUntilValidOnWake, NUM_BITS);
// Publish the necessary time period (in seconds) that a battery
// calibrating tool must wait to allow the battery to settle after
// charge and after discharge.
setProperty( kIOPMPSPostChargeWaitSecondsKey, kPostChargeWaitSeconds, NUM_BITS);
setProperty( kIOPMPSPostDishargeWaitSecondsKey, kPostDischargeWaitSeconds, NUM_BITS);
// zero out battery state with argument (do_set == true)
fStartupFastPoll = 10;
fPollingInterval = kQuickPollInterval;
clearBatteryState(false);
// Kick off the 30 second timer and do an initial poll
//pollBatteryState( kNewBatteryPath );
fPollTimer->setTimeoutMS(fFirstPollDelay);
return true;
}
/******************************************************************************
* AppleSmartBattery::stop
*
******************************************************************************/
void AppleSmartBattery::stop(IOService *provider)
{
OSSafeReleaseNULL(fTracker);
OSSafeReleaseNULL(fCellVoltages);
super::stop(provider);
}
/******************************************************************************
* AppleSmartBattery::logReadError
*
******************************************************************************/
void AppleSmartBattery::logReadError(
const char *error_type,
uint16_t additional_error,
void *t)
{
if(!error_type) return;
setProperty((const char *)"LatestErrorType", error_type);
AlwaysLog("Error: %s (%d)\n", error_type, additional_error);
return;
}
/******************************************************************************
* AppleSmartBattery::setPollingInterval
*
******************************************************************************/
void AppleSmartBattery::setPollingInterval(
int milliSeconds)
{
DebugLog("setPollingInterval: New interval = %d ms\n", milliSeconds);
if (!fPollingOverridden) {
milliSecPollingTable[kDefaultPollInterval] = milliSeconds;
fPollingInterval = kDefaultPollInterval;
}
}
/******************************************************************************
* AppleSmartBattery::pollBatteryState
*
* Asynchronously kicks off the register poll.
******************************************************************************/
bool AppleSmartBattery::pollBatteryState(int path)
{
DebugLog("pollBatteryState: path = %d\n", path);
// This must be called under workloop synchronization
fProvider->getBatterySTA();
if (fBatteryPresent)
{
if (fUseBatteryExtendedInformation)
fProvider->getBatteryBIX();
else
fProvider->getBatteryBIF();
if (fUseBatteryExtraInformation)
fProvider->getBatteryBBIX();
fProvider->getBatteryBST();
}
else
{
//rehabman: added to correct power source Battery if boot w/ no batteries
DebugLog("!fBatteryPresent\n");
fACConnected = true;
setExternalConnected(fACConnected);
setFullyCharged(false);
clearBatteryState(true);
}
fPollTimer->cancelTimeout();
if (!fPollingOverridden)
{
// at startup, polling is quick for slow to respond ACPI implementations
if (fStartupFastPoll)
{
DebugLog("fStartupFastPoll=%d\n", fStartupFastPoll);
--fStartupFastPoll;
if (!fStartupFastPoll)
fPollingInterval = kDefaultPollInterval;
}
DebugLog("fRealAC=%d, fACConnected=%d\n", fRealAC, fACConnected);
if (-1 == fRealAC || fRealAC == fACConnected)
{
// Restart timer with standard polling interval
fPollTimer->setTimeoutMS(milliSecPollingTable[fPollingInterval]);
}
else
{
// Restart timer with quick polling interval
fPollTimer->setTimeoutMS(milliSecPollingTable[kQuickPollInterval]);
}
}
else
{
// restart timer with debug value
fPollTimer->setTimeoutMS(1000 * fPollingInterval);
}
return true;
}
void AppleSmartBattery::handleBatteryInserted()
{
DebugLog("handleBatteryInserted called\n");
// This must be called under workloop synchronization
pollBatteryState(kNewBatteryPath);
}
void AppleSmartBattery::handleBatteryRemoved()
{
DebugLog("handleBatteryRemoved called\n");
// This must be called under workloop synchronization
pollBatteryState(kNewBatteryPath);
}
/*****************************************************************************
* AppleSmartBatteryManager::notifyConnectedState
* Cause a fresh battery poll in workloop to check AC status
******************************************************************************/
void AppleSmartBattery::notifyConnectedState(bool connected)
{
fRealAC = connected;
if (fBatteryPresent)
{
// on AC status change, poll right away (will set quick timer if AC is out-of-sync)
pollBatteryState(kExistingBatteryPath);
}
}
/******************************************************************************
* AppleSmartBattery::handleSystemSleepWake
*
* Caller must hold the gate.
******************************************************************************/
IOReturn AppleSmartBattery::handleSystemSleepWake(IOService* powerService, bool isSystemSleep)
{
DebugLog("handleSystemSleepWake: isSystemSleep = %d\n", isSystemSleep);
if (isSystemSleep) // System Sleep
{
// nothing
}
else // System Wake
{
pollBatteryState(kNewBatteryPath);
}
return kIOPMAckImplied;
}
/******************************************************************************
* pollingTimeOut
*
* Regular 30 second poll expiration handler.
******************************************************************************/
void AppleSmartBattery::pollingTimeOut()
{
DebugLog("pollingTimeOut called\n");
if (fInitialPollCountdown > 0)
{
// At boot time we make sure to re-read everything kInitialPoltoCountdown times
pollBatteryState(kNewBatteryPath);
--fInitialPollCountdown;
}
else
{
pollBatteryState(kExistingBatteryPath);
}
}
/******************************************************************************
* incompleteReadTimeOut
*
* The complete battery read has not completed in the allowed timeframe.
* We assume this is for several reasons:
* - The EC has dropped an SMBus packet (probably recoverable)
* - The EC has stalled an SMBus request; IOSMBusController is hung (probably not recoverable)
*
* Start the battery read over from scratch.
*****************************************************************************/
void AppleSmartBattery::incompleteReadTimeOut(void)
{
DebugLog("incompleteReadTimeOut called\n");
logReadError(kErrorOverallTimeoutExpired, 0, NULL);
pollBatteryState(kExistingBatteryPath);
}
/******************************************************************************
* AppleSmartBattery::clearBatteryState
*
******************************************************************************/
void AppleSmartBattery::clearBatteryState(bool do_update)
{
DebugLog("clearBatteryState: do_update = %s\n", do_update == true ? "true" : "false");
// Only clear out battery state; don't clear manager state like AC Power.
// We just zero out the int and bool values, but remove the OSType values.
fBatteryPresent = false;
fACConnected = false;
fACChargeCapable = false;
setBatteryInstalled(false);
setIsCharging(false);
setCurrentCapacity(0);
setMaxCapacity(0);
setTimeRemaining(0);
setAmperage(0);
setVoltage(0);
setCycleCount(0);
setMaxErr(0);
//REVIEW: should we be manipulating protected member 'properties' like this?
//REVIEW: maybe should be doing through setPSProperty (with NULL)?
properties->removeObject(manufacturerKey);
removeProperty(manufacturerKey);
properties->removeObject(serialKey);
removeProperty(serialKey);
properties->removeObject(batteryInfoKey);
removeProperty(batteryInfoKey);
properties->removeObject(errorConditionKey);
removeProperty(errorConditionKey);
// setBatteryBIF/setBatteryBIX
properties->removeObject(_DesignCapacitySym);
removeProperty(_DesignCapacitySym);
properties->removeObject(_DeviceNameSym);
removeProperty(_DeviceNameSym);
properties->removeObject(_TypeSym);
removeProperty(_TypeSym);
properties->removeObject(_MaxErrSym);
removeProperty(_MaxErrSym);
properties->removeObject(_ManufactureDateSym);
removeProperty(_ManufactureDateSym);
properties->removeObject(_FirmwareSerialNumberSym);
removeProperty(_FirmwareSerialNumberSym);
properties->removeObject(_ManufacturerDataSym);
removeProperty(_ManufacturerDataSym);
properties->removeObject(_PFStatusSym);
removeProperty(_PFStatusSym);
properties->removeObject(_AbsoluteStateOfChargeSym);
removeProperty(_AbsoluteStateOfChargeSym);
properties->removeObject(_DateOfManufacture);
removeProperty(_DateOfManufacture);
properties->removeObject(_RelativeStateOfChargeSym);
removeProperty(_RelativeStateOfChargeSym);
properties->removeObject(_RemainingCapacitySym);
removeProperty(_RemainingCapacitySym);
properties->removeObject(_RunTimeToEmptySym);
removeProperty(_RunTimeToEmptySym);
// setBatteryBST
properties->removeObject(_AvgTimeToEmptySym);
removeProperty(_AvgTimeToEmptySym);
properties->removeObject(_AvgTimeToFullSym);
removeProperty(_AvgTimeToFullSym);
properties->removeObject(_InstantTimeToEmptySym);
removeProperty(_InstantTimeToEmptySym);
properties->removeObject(_InstantTimeToFullSym);
removeProperty(_InstantTimeToFullSym);
properties->removeObject(_InstantAmperageSym);
removeProperty(_InstantAmperageSym);
properties->removeObject(_QuickPollSym);
removeProperty(_QuickPollSym);
properties->removeObject(_CellVoltageSym);
removeProperty(_CellVoltageSym);
properties->removeObject(_TemperatureSym);
removeProperty(_TemperatureSym);
properties->removeObject(_BatterySerialNumberSym);
removeProperty(_BatterySerialNumberSym);
rebuildLegacyIOBatteryInfo(do_update);
fRealAC = -1; // real AC status is unknown...
if(do_update) {
updateStatus();
}
}
/******************************************************************************
* Package battery data in "legacy battery info" format, readable by
* any applications using the not-so-friendly IOPMCopyBatteryInfo()
******************************************************************************/
#if 0
static void setLegacyObject(OSDictionary* dest, const char* destKey, OSDictionary* src, const char* srcKey)
{
OSNumber* srcNum = OSDynamicCast(OSNumber, src->getObject(srcKey));
if (srcNum)
{
OSNumber* destNum = OSNumber::withNumber(srcNum->unsigned32BitValue(), 32);
if (destNum)
{
dest->setObject(destKey, destNum);
destNum->release();
}
}
}
#endif
void AppleSmartBattery::rebuildLegacyIOBatteryInfo(bool do_update)
{
DebugLog("rebuildLegacyIOBatteryInfo called\n");
if (do_update)
{
uint32_t flags = 0;
if (externalConnected()) flags |= kIOPMACInstalled;
if (batteryInstalled()) flags |= kIOPMBatteryInstalled;
if (isCharging()) flags |= kIOPMBatteryCharging;
OSDictionary* legacyDict = OSDictionary::withCapacity(5);
OSNumber* flags_num = OSNumber::withNumber((unsigned long long)flags, NUM_BITS);
if (!legacyDict || !flags_num)
{
OSSafeRelease(legacyDict);
OSSafeRelease(flags_num);
return;
}
legacyDict->setObject(kIOBatteryFlagsKey, flags_num);
flags_num->release();
#if 0
setLegacyObject(legacyDict, kIOBatteryCurrentChargeKey, properties, kIOPMPSCurrentCapacityKey);
setLegacyObject(legacyDict, kIOBatteryCapacityKey, properties, kIOPMPSMaxCapacityKey);
setLegacyObject(legacyDict, kIOBatteryVoltageKey, properties, kIOPMPSVoltageKey);
setLegacyObject(legacyDict, kIOBatteryAmperageKey, properties, kIOPMPSAmperageKey);
setLegacyObject(legacyDict, kIOBatteryCycleCountKey, properties, kIOPMPSCycleCountKey);
#else
legacyDict->setObject(kIOBatteryCurrentChargeKey, properties->getObject(kIOPMPSCurrentCapacityKey));
legacyDict->setObject(kIOBatteryCapacityKey, properties->getObject(kIOPMPSMaxCapacityKey));
legacyDict->setObject(kIOBatteryVoltageKey, properties->getObject(kIOPMPSVoltageKey));
legacyDict->setObject(kIOBatteryAmperageKey, properties->getObject(kIOPMPSAmperageKey));
legacyDict->setObject(kIOBatteryCycleCountKey, properties->getObject(kIOPMPSCycleCountKey));
#endif
setLegacyIOBatteryInfo(legacyDict);
legacyDict->release();
}
else
{
//REVIEW: should we be manipulating protected member 'properties' like this?
//REVIEW: maybe should be doing through setPSProperty (with NULL)?
properties->removeObject(kIOPMPSCurrentCapacityKey);
properties->removeObject(kIOPMPSMaxCapacityKey);
properties->removeObject(kIOPMPSVoltageKey);
properties->removeObject(kIOPMPSAmperageKey);
properties->removeObject(kIOPMPSCycleCountKey);
}
}
/******************************************************************************
* Fabricate a serial number from our battery controller model and serial
* number.
******************************************************************************/
static bool isBlankString(const char* sz)
{
// empty or all spaces is blank
if (sz) {
while (*sz) {
if (*sz != ' ')
return false;
sz++;
}
}
return true;
}
#define kMaxGeneratedSerialSize (64)
void AppleSmartBattery::setBatterySerialNumber(const OSSymbol* deviceName, const OSSymbol* serialNumber)
{
DebugLog("setBatterySerialNumber called\n");
const char *device_cstring_ptr;
if (deviceName)
device_cstring_ptr = deviceName->getCStringNoCopy();
else
device_cstring_ptr = "Unknown";
const char *serial_cstring_ptr;
if (serialNumber)
serial_cstring_ptr = serialNumber->getCStringNoCopy();
else
serial_cstring_ptr = "Unknown";
char serialBuf[kMaxGeneratedSerialSize];
bzero(serialBuf, kMaxGeneratedSerialSize);
snprintf(serialBuf, kMaxGeneratedSerialSize, "%s-%s", device_cstring_ptr, serial_cstring_ptr);
const OSSymbol *printableSerial = OSSymbol::withCString(serialBuf);
if (printableSerial) {
setPSProperty(_BatterySerialNumberSym, const_cast<OSSymbol*>(printableSerial));
printableSerial->release();
}
}
void AppleSmartBattery::setSerialString(OSSymbol* serialNumber)
{
if (!serialNumber || isBlankString(serialNumber->getCStringNoCopy()))
serialNumber = (OSSymbol*)unknownObjectKey;
setSerial(serialNumber);
}
/******************************************************************************
* Given a packed date from SBS, decode into a human readable date and return
* an OSSymbol
******************************************************************************/
#define kMaxDateSize 12
const OSSymbol * AppleSmartBattery::unpackDate(UInt32 packedDate)
{
DebugLog("unpackDate: packedDate = 0x%x\n", (unsigned int) packedDate);
/* The date is packed in the following fashion: (year-1980) * 512 + month * 32 + day.
*
* Field Bits Used Format Allowable Values
* Day 0...4 5 bit binary value 1 - 31 (corresponds to date)
* Month 5...8 4 bit binary value 1 - 12 (corresponds to month number)
* Year 9...15 7 bit binary value 0 - 127 (corresponds to year biased by 1980
*/
UInt32 yearBits = packedDate >> 9;
UInt32 monthBits = (packedDate >> 5) & 0xF;
UInt32 dayBits = packedDate & 0x1F;
char dateBuf[kMaxDateSize];
bzero(dateBuf, kMaxDateSize);
// TODO: Determine date format from OS and format according to that, but for now use YYYY-MM-DD
snprintf(dateBuf, kMaxDateSize, "%4d-%02d-%02d%c", (unsigned int) yearBits + 1980, (unsigned int) monthBits, (unsigned int) dayBits, (char)0);
const OSSymbol *printableDate = OSSymbol::withCString(dateBuf);
return printableDate;
}
/******************************************************************************
* Power Source value accessors
* These supplement the built-in accessors in IOPMPowerSource.h, and should
* arguably be added back into the superclass IOPMPowerSource
******************************************************************************/
void AppleSmartBattery::setMaxErr(int error)
{
OSNumber *n = OSNumber::withNumber(error, NUM_BITS);
if (n) {
setPSProperty(_MaxErrSym, n);
n->release();
}
}
int AppleSmartBattery::maxErr(void)
{
OSNumber *n = OSDynamicCast(OSNumber, properties->getObject(_MaxErrSym));
return n ? n->unsigned32BitValue() : 0;
}
void AppleSmartBattery::setDeviceName(const OSSymbol *sym)
{
if (sym)
setPSProperty(_DeviceNameSym, const_cast<OSSymbol*>(sym));
}
OSSymbol * AppleSmartBattery::deviceName(void)
{
return OSDynamicCast(OSSymbol, properties->getObject(_DeviceNameSym));
}
void AppleSmartBattery::setFullyCharged(bool charged)
{
setPSProperty(_FullyChargedSym, charged ? kOSBooleanTrue : kOSBooleanFalse);
}
bool AppleSmartBattery::fullyCharged(void)
{
return (kOSBooleanTrue == properties->getObject(_FullyChargedSym));
}
void AppleSmartBattery::setInstantaneousTimeToEmpty(int seconds)
{
OSNumber *n = OSNumber::withNumber(seconds, NUM_BITS);
if (n) {
setPSProperty(_InstantTimeToEmptySym, n);
n->release();
}
}
void AppleSmartBattery::setInstantaneousTimeToFull(int seconds)
{
OSNumber *n = OSNumber::withNumber(seconds, NUM_BITS);
if (n) {
setPSProperty(_InstantTimeToFullSym, n);
n->release();
}
}
void AppleSmartBattery::setInstantAmperage(int mA)
{
OSNumber *n = OSNumber::withNumber(mA, NUM_BITS);
if (n) {
setPSProperty(_InstantAmperageSym, n);
n->release();
}
}
void AppleSmartBattery::setAverageTimeToEmpty(int seconds)
{
OSNumber *n = OSNumber::withNumber(seconds, NUM_BITS);
if (n) {
setPSProperty(_AvgTimeToEmptySym, n);
n->release();
}
}
int AppleSmartBattery::averageTimeToEmpty(void)
{
OSNumber *n = OSDynamicCast(OSNumber, properties->getObject(_AvgTimeToEmptySym));
return n ? n->unsigned32BitValue() : 0;
}
void AppleSmartBattery::setAverageTimeToFull(int seconds)
{
OSNumber *n = OSNumber::withNumber(seconds, NUM_BITS);
if (n) {
setPSProperty(_AvgTimeToFullSym, n);
n->release();
}
}
int AppleSmartBattery::averageTimeToFull(void)
{
OSNumber *n = OSDynamicCast(OSNumber, properties->getObject(_AvgTimeToFullSym));
return n ? n->unsigned32BitValue() : 0;
}
void AppleSmartBattery::setRunTimeToEmpty(int seconds)
{
OSNumber *n = OSNumber::withNumber(seconds, NUM_BITS);
if (n) {
setPSProperty(_RunTimeToEmptySym, n);
n->release();
}
}
int AppleSmartBattery::runTimeToEmpty(void)
{
OSNumber *n = OSDynamicCast(OSNumber, properties->getObject(_RunTimeToEmptySym));
return n ? n->unsigned32BitValue() : 0;
}
void AppleSmartBattery::setRelativeStateOfCharge(int percent)
{
OSNumber *n = OSNumber::withNumber(percent, NUM_BITS);
if (n) {
setPSProperty(_RelativeStateOfChargeSym, n);
n->release();
}
}
int AppleSmartBattery::relativeStateOfCharge(void)
{
OSNumber *n = OSDynamicCast(OSNumber, properties->getObject(_RelativeStateOfChargeSym));
return n ? n->unsigned32BitValue() : 0;
}
void AppleSmartBattery::setAbsoluteStateOfCharge(int percent)
{
OSNumber *n = OSNumber::withNumber(percent, NUM_BITS);
if (n) {
setPSProperty(_AbsoluteStateOfChargeSym, n);
n->release();
}
}
int AppleSmartBattery::absoluteStateOfCharge(void)
{
OSNumber *n = OSDynamicCast(OSNumber, properties->getObject(_AbsoluteStateOfChargeSym));
return n ? n->unsigned32BitValue() : 0;
}
void AppleSmartBattery::setRemainingCapacity(int mah)
{
OSNumber *n = OSNumber::withNumber(mah, NUM_BITS);
if (n) {
setPSProperty(_RemainingCapacitySym, n);
n->release();
}
}
int AppleSmartBattery::remainingCapacity(void)
{
OSNumber *n = OSDynamicCast(OSNumber, properties->getObject(_RemainingCapacitySym));
return n ? n->unsigned32BitValue() : 0;
}
void AppleSmartBattery::setAverageCurrent(int ma)
{
OSNumber *n = OSNumber::withNumber(ma, NUM_BITS);
if (n) {