Debian Codegraph @

src/systeminfo/mac/qbatteryinfo_mac.mm

raw
1 /****************************************************************************
2 **
3 ** Copyright (C) 2018 The Qt Company Ltd and/or its subsidiary(-ies).
4 ** Copyright (C) 2018 BlackBerry Limited. All rights reserved.
5 ** Contact: http://www.qt-project.org/legal
6 **
7 ** This file is part of the QtSystems module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** Commercial License Usage
11 ** Licensees holding valid commercial Qt licenses may use this file in
12 ** accordance with the commercial license agreement provided with the
13 ** Software or, alternatively, in accordance with the terms contained in
14 ** a written agreement between you and The Qt Company. For licensing terms
15 ** and conditions see https://www.qt.io/terms-conditions. For further
16 ** information use the contact form at https://www.qt.io/contact-us.
17 **
18 ** GNU Lesser General Public License Usage
19 ** Alternatively, this file may be used under the terms of the GNU Lesser
20 ** General Public License version 3 as published by the Free Software
21 ** Foundation and appearing in the file LICENSE.LGPL3 included in the
22 ** packaging of this file. Please review the following information to
23 ** ensure the GNU Lesser General Public License version 3 requirements
24 ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25 **
26 ** GNU General Public License Usage
27 ** Alternatively, this file may be used under the terms of the GNU
28 ** General Public License version 2.0 or (at your option) the GNU General
29 ** Public license version 3 or any later version approved by the KDE Free
30 ** Qt Foundation. The licenses are as published by the Free Software
31 ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32 ** included in the packaging of this file. Please review the following
33 ** information to ensure the GNU General Public License requirements will
34 ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35 ** https://www.gnu.org/licenses/gpl-3.0.html.
36 **
37 ** $QT_END_LICENSE$
38 **
39 ****************************************************************************/
40
41 #include "qbatteryinfo_mac_p.h"
42
43 #include <QtCore/qmetaobject.h>
44 #include <QtCore/qnumeric.h>
45 #include <QDebug>
46
47 #include <Foundation/NSAutoreleasePool.h>
48 #include <CoreFoundation/CoreFoundation.h>
49 #include <IOKit/ps/IOPowerSources.h>
50 #include <IOKit/ps/IOPSKeys.h>
51 #include <Foundation/NSDictionary.h>
52 #include <Foundation/NSString.h>
53 #include <Foundation/NSKeyValueCoding.h>
54 #include <IOKit/IOKitLib.h>
55
56 QT_BEGIN_NAMESPACE
57
58 void powerInfoChanged(void* context)
59 {
60 QBatteryInfoPrivate *sys = reinterpret_cast<QBatteryInfoPrivate *>(context);
61 if (sys) {
62 sys->currentChargingState();
63 }
64 }
65
66 void batteryInfoChanged(void* context)
67 {
68 QBatteryInfoPrivate *bat = reinterpret_cast<QBatteryInfoPrivate *>(context);
69 if (bat) {
70 bat->getBatteryInfo();
71 }
72 }
73
74 QBatteryInfoPrivate::QBatteryInfoPrivate(QBatteryInfo *parent)
75 : QObject(parent)
76 , q_ptr(parent)
77 , currentBatLevel(0)
78 , currentVoltage(-1)
79 , dischargeRate(0)
80 , capacity(-1)
81 , timeToFull(-1)
82 , remainingEnergy(-1)
83 , numberOfBatteries(0)
84 , index(0)
85 {
86 initialize();
87 }
88
89 QBatteryInfoPrivate::QBatteryInfoPrivate(int batteryIndex, QBatteryInfo *parent)
90 : QObject(parent)
91 , q_ptr(parent)
92 , currentBatLevel(0)
93 , currentVoltage(-1)
94 , dischargeRate(0)
95 , capacity(-1)
96 , timeToFull(-1)
97 , remainingEnergy(-1)
98 , numberOfBatteries(0)
99 , index(batteryIndex)
100 {
101 initialize();
102 }
103
104 void QBatteryInfoPrivate::initialize()
105 {
106 getBatteryInfo();
107 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
108
109 CFRunLoopSourceRef runLoopSource = (CFRunLoopSourceRef)IOPSNotificationCreateRunLoopSource(batteryInfoChanged, this);
110 if (runLoopSource) {
111 CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
112 CFRelease(runLoopSource);
113 }
114 [autoreleasepool release];
115 currentChargingState();
116 getBatteryInfo();
117 }
118
119 QBatteryInfoPrivate::~QBatteryInfoPrivate()
120 {
121 }
122
123 int QBatteryInfoPrivate::batteryCount()
124 {
125 return numberOfBatteries;
126 }
127
128 int QBatteryInfoPrivate::batteryIndex() const
129 {
130 return index;
131 }
132
133 bool QBatteryInfoPrivate::isValid()
134 {
135 return (index >= 0) && (numberOfBatteries > index);
136 }
137
138 void QBatteryInfoPrivate::setBatteryIndex(int batteryIndex)
139 {
140 if (index != batteryIndex) {
141 bool validBefore = isValid();
142 int oldIndex = index;
143 index = batteryIndex;
144 bool validNow = isValid();
145 if (validBefore != validNow)
146 Q_EMIT validChanged(validNow);
147
148 if (validNow) {
149 if (validBefore) {
150 // valid now, valid before so we have to check individual values
151
152 // ignore chargerType - it won't change based on battery index
153 //emit chargerTypeChanged(newChargerType);
154
155 QBatteryInfo::ChargingState newChargingState = chargingState();
156 if (newChargingState != chargingState(oldIndex))
157 emit chargingStateChanged(newChargingState);
158
159 int newValue = level();
160 if (newValue != level(oldIndex))
161 emit levelChanged(newValue);
162
163 newValue = currentFlow();
164 if (newValue != currentFlow(oldIndex))
165 emit currentFlowChanged(newValue);
166
167 newValue = cycleCount();
168 if (newValue != cycleCount(oldIndex))
169 emit cycleCountChanged(newValue);
170
171 newValue = remainingCapacity();
172 if (newValue != remainingCapacity(oldIndex))
173 emit remainingCapacityChanged(newValue);
174
175 newValue = remainingChargingTime();
176 if (newValue != remainingChargingTime(oldIndex))
177 emit remainingChargingTimeChanged(newValue);
178
179 newValue = voltage();
180 if (newValue != voltage(oldIndex))
181 emit voltageChanged(newValue);
182
183 QBatteryInfo::LevelStatus newLevelStatus = levelStatus();
184 if (newLevelStatus != levelStatus(oldIndex))
185 emit levelStatusChanged(newLevelStatus);
186
187 QBatteryInfo::Health newHealth = health();
188 if (newHealth != health(oldIndex))
189 emit healthChanged(newHealth);
190
191 float newTemperature = temperature();
192 if (!qFuzzyCompare(newTemperature, temperature(oldIndex)))
193 emit temperatureChanged(newTemperature);
194 } else {
195 // it wasn't valid before so everything is changed
196
197 // ignore chargerType - it won't change based on battery index
198 //emit chargerTypeChanged(newChargerType);
199
200 emit chargingStateChanged(chargingState());
201 emit levelChanged(level());
202 emit currentFlowChanged(currentFlow());
203 emit cycleCountChanged(cycleCount());
204 emit remainingCapacityChanged(remainingCapacity());
205 emit remainingChargingTimeChanged(remainingChargingTime());
206 emit voltageChanged(voltage());
207 emit levelStatusChanged(levelStatus());
208 emit healthChanged(health());
209 emit temperatureChanged(temperature());
210 }
211 }
212
213 Q_EMIT batteryIndexChanged(index);
214 }
215 }
216
217 int QBatteryInfoPrivate::level(int battery)
218 {
219 int maxCapacity = maximumCapacity(battery);
220 int remCapacity = remainingCapacity(battery);
221
222 if (maxCapacity == 0)
223 return -1;
224
225 return remCapacity * 100 / maxCapacity;
226 }
227
228 int QBatteryInfoPrivate::level()
229 {
230 return level(index);
231 }
232
233 int QBatteryInfoPrivate::currentFlow(int battery)
234 {
235 if (battery < 0)
236 battery = 0;
237 return currentFlows.value(battery);
238 }
239
240 int QBatteryInfoPrivate::currentFlow()
241 {
242 return currentFlow(index);
243 }
244
245 int QBatteryInfoPrivate::cycleCount(int battery)
246 {
247 Q_UNUSED(battery)
248
249 return -1;
250 }
251
252 int QBatteryInfoPrivate::cycleCount()
253 {
254 return cycleCount(index);
255 }
256
257 int QBatteryInfoPrivate::maximumCapacity(int battery)
258 {
259 if (battery < 0)
260 battery = 0;
261 return maximumCapacities.value(battery);
262 }
263
264 int QBatteryInfoPrivate::maximumCapacity()
265 {
266 return maximumCapacity(index);
267 }
268
269 int QBatteryInfoPrivate::remainingCapacity(int battery)
270 {
271 if (battery < 0)
272 battery = 0;
273 return remainingCapacities.value(battery);
274 }
275
276 int QBatteryInfoPrivate::remainingCapacity()
277 {
278 return remainingCapacity(index);
279 }
280
281 int QBatteryInfoPrivate::remainingChargingTime(int battery)
282 {
283 if (battery < 0)
284 battery = 0;
285 return remainingChargingTimes.value(battery);
286 }
287
288 int QBatteryInfoPrivate::remainingChargingTime()
289 {
290 return remainingChargingTime(index);
291 }
292
293 int QBatteryInfoPrivate::voltage(int battery)
294 {
295 if (battery < 0)
296 battery = 0;
297 return voltages.value(battery);
298 }
299
300 int QBatteryInfoPrivate::voltage()
301 {
302 return voltage(index);
303 }
304
305 QBatteryInfo::ChargerType QBatteryInfoPrivate::chargerType()
306 {
307 return curChargeType;
308 }
309
310 QBatteryInfo::ChargingState QBatteryInfoPrivate::chargingState(int battery)
311 {
312 if (battery < 0)
313 battery = 0;
314 return chargingStates.value(battery);
315 }
316
317 QBatteryInfo::ChargingState QBatteryInfoPrivate::chargingState()
318 {
319 return chargingState(index);
320 }
321
322 QBatteryInfo::LevelStatus QBatteryInfoPrivate::levelStatus(int battery)
323 {
324 if (battery < 0)
325 battery = 0;
326 return levelStatuss.value(battery);
327 }
328
329 QBatteryInfo::LevelStatus QBatteryInfoPrivate::levelStatus()
330 {
331 return levelStatus(index);
332 }
333
334 QBatteryInfo::Health QBatteryInfoPrivate::health(int battery)
335 {
336 Q_UNUSED(battery)
337
338 return QBatteryInfo::HealthUnknown;
339 }
340
341 QBatteryInfo::Health QBatteryInfoPrivate::health()
342 {
343 return health(index);
344 }
345
346 float QBatteryInfoPrivate::temperature(int battery)
347 {
348 Q_UNUSED(battery)
349
350 return qQNaN();
351 }
352
353 float QBatteryInfoPrivate::temperature()
354 {
355 return temperature(index);
356 }
357
358 void QBatteryInfoPrivate::connectNotify(const QMetaMethod &signal)
359 {
360 // static const QMetaMethod batteryCountChangedSignal = QMetaMethod::fromSignal(&QBatteryInfoPrivate::batteryCountChanged);
361 static const QMetaMethod chargingStateChangedSignal = QMetaMethod::fromSignal(&QBatteryInfoPrivate::chargingStateChanged);
362 static const QMetaMethod currentFlowChangedSignal = QMetaMethod::fromSignal(&QBatteryInfoPrivate::currentFlowChanged);
363 static const QMetaMethod levelStatusChangedSignal = QMetaMethod::fromSignal(&QBatteryInfoPrivate::levelStatusChanged);
364 // static const QMetaMethod chargerTypeChangedSignal = QMetaMethod::fromSignal(&QBatteryInfoPrivate::chargerTypeChanged);
365 // static const QMetaMethod remainingCapacityChangedSignal = QMetaMethod::fromSignal(&QBatteryInfoPrivate::remainingCapacityChanged);
366 // static const QMetaMethod remainingChargingTimeChangedSignal = QMetaMethod::fromSignal(&QBatteryInfoPrivate::remainingChargingTimeChanged);
367 // static const QMetaMethod voltageChangedSignal = QMetaMethod::fromSignal(&QBatteryInfoPrivate::voltageChanged);
368
369 if (signal == chargingStateChangedSignal
370 || signal == currentFlowChangedSignal
371 || signal == levelStatusChangedSignal) {
372
373 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
374
375 CFRunLoopSourceRef runLoopSource = (CFRunLoopSourceRef)IOPSNotificationCreateRunLoopSource(powerInfoChanged, this);
376 if (runLoopSource) {
377 CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
378 }
379 [autoreleasepool release];
380 CFRelease(runLoopSource);
381 }
382 }
383
384 void QBatteryInfoPrivate::disconnectNotify(const QMetaMethod &signal)
385 {
386 Q_UNUSED(signal)
387 }
388
389 QBatteryInfo::ChargingState QBatteryInfoPrivate::currentChargingState()
390 {
391 NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
392 QBatteryInfo::ChargingState state = QBatteryInfo::UnknownChargingState;
393 QBatteryInfo::ChargerType cType = QBatteryInfo::UnknownCharger;
394
395 CFDictionaryRef powerSourceDict = NULL;
396 CFStringRef powerStateString;
397
398 CFTypeRef powerSourcesInfo = IOPSCopyPowerSourcesInfo();
399 CFArrayRef powerSourcesList = IOPSCopyPowerSourcesList(powerSourcesInfo);
400 int batteries = CFArrayGetCount(powerSourcesList);
401
402 if (batteries != numberOfBatteries) {
403 bool validBefore = isValid();
404 numberOfBatteries = batteries;
405 bool validNow = isValid();
406 if (validBefore != validNow)
407 Q_EMIT validChanged(validNow);
408
409 Q_EMIT batteryCountChanged(numberOfBatteries);
410 }
411
412 int i;
413 for (i = 0; i < numberOfBatteries; i++) {
414 powerSourceDict = IOPSGetPowerSourceDescription(powerSourcesInfo, CFArrayGetValueAtIndex(powerSourcesList, i));
415 if (!powerSourceDict) {
416 state = QBatteryInfo::UnknownChargingState;
417 cType = QBatteryInfo::UnknownCharger;
418 qDebug() << "unknown state";
419 break;
420 }
421
422 powerStateString = (CFStringRef)CFDictionaryGetValue(powerSourceDict, CFSTR(kIOPSPowerSourceStateKey));
423 if (CFStringCompare(powerStateString,CFSTR(kIOPSBatteryPowerValue),0)==kCFCompareEqualTo) {
424 //has battery
425 state = QBatteryInfo::Discharging;
426 cType = QBatteryInfo::UnknownCharger;
427 } else {
428
429 NSDictionary *powerSourceInfo = nil;
430 powerSourceInfo = [NSDictionary dictionaryWithDictionary:(NSDictionary*)powerSourceDict];
431 bool charging = (bool)[[powerSourceInfo valueForKey:[NSString stringWithUTF8String:kIOPSIsChargingKey]] boolValue];
432 if (charging ) {
433 state = QBatteryInfo::Charging;
434 cType = QBatteryInfo::WallCharger;
435 } else {
436 cType = QBatteryInfo::UnknownCharger;
437 state = QBatteryInfo::IdleChargingState;
438 }
439 }
440
441 if (cType != curChargeType) {
442 curChargeType = cType;
443 Q_EMIT chargerTypeChanged(curChargeType);
444 }
445
446 if ( chargingStates.value(i) != state) {
447 chargingStates[i] = state;
448 if (i == index)
449 Q_EMIT chargingStateChanged(state);
450 }
451 }
452 CFRelease(powerSourcesInfo);
453 CFRelease(powerSourcesList);
454
455 [autoreleasepool release];
456 return state;
457 }
458
459 void QBatteryInfoPrivate::getBatteryInfo()
460 {
461 int cEnergy = 0;
462 int cVoltage = 0;
463 int cTime = 0;
464 int rEnergy = 0;
465
466 CFTypeRef info;
467 CFArrayRef list;
468 CFDictionaryRef battery;
469
470 info = IOPSCopyPowerSourcesInfo();
471 if (info == NULL) {
472 qDebug() << "IOPSCopyPowerSourcesInfo error";
473 return;
474 }
475 list = IOPSCopyPowerSourcesList(info);
476 if (list == NULL) {
477 CFRelease(info);
478 qDebug() << "IOPSCopyPowerSourcesList error";
479 return;
480 }
481
482 CFMutableDictionaryRef matching = NULL;
483 CFMutableDictionaryRef batDoctionary = NULL;
484 io_registry_entry_t entry = 0;
485 matching = IOServiceMatching("IOPMPowerSource");
486 entry = IOServiceGetMatchingService(kIOMasterPortDefault,matching);
487 IORegistryEntryCreateCFProperties(entry, &batDoctionary,NULL,0);
488
489 int batteries = CFArrayGetCount(list);
490 for (int i = 0; i < batteries; i++) {
491
492 battery = IOPSGetPowerSourceDescription(info, CFArrayGetValueAtIndex(list, i));
493
494 int curCapacityPercent = 0;
495 int maxCapacity = 0;
496
497 const void *psValue;
498 psValue = CFDictionaryGetValue(battery, CFSTR(kIOPSCurrentCapacityKey));
499 CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacityPercent);
500
501 psValue = CFDictionaryGetValue(battery, CFSTR(kIOPSMaxCapacityKey));
502 CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);
503
504 QBatteryInfo::LevelStatus stat = QBatteryInfo::LevelUnknown;
505
506 if (curCapacityPercent < 2) {
507 stat = QBatteryInfo::LevelEmpty;
508 } else if (curCapacityPercent < 11) {
509 stat = QBatteryInfo::LevelLow;
510 } else if (curCapacityPercent > 10 && curCapacityPercent < 100) {
511 stat = QBatteryInfo::LevelOk;
512 } else if (curCapacityPercent == 100) {
513 stat = QBatteryInfo::LevelFull;
514 }
515 if (levelStatuss.value(i) != stat) {
516 levelStatuss[i] = stat;
517 if (i == index)
518 Q_EMIT levelStatusChanged(stat);
519 }
520
521 cVoltage = [[(NSDictionary*)batDoctionary objectForKey:@kIOPSVoltageKey] intValue];
522
523 if (cVoltage != voltages.value(i) && cVoltage != 0) {
524 voltages[i] = cVoltage;
525 if (i == index)
526 Q_EMIT(voltageChanged( cVoltage));
527 }
528
529 cEnergy = [[(NSDictionary*)batDoctionary objectForKey:@kIOPSCurrentKey] doubleValue];
530
531 if (cEnergy != currentFlows.value(i) && cEnergy != 0) {
532 currentFlows[i] = cEnergy;
533 if (i == index)
534 Q_EMIT currentFlowChanged(cEnergy);
535 }
536
537 cTime = [[(NSDictionary*)batDoctionary objectForKey:@kIOPSTimeToFullChargeKey] intValue];
538
539 if (cTime != remainingChargingTimes.value(i)) {
540 remainingChargingTimes[i] = cTime * 60;
541 if (i == index)
542 Q_EMIT remainingChargingTimeChanged(remainingChargingTimes[i]);
543 }
544
545 rEnergy = [[(NSDictionary*)batDoctionary objectForKey:@"CurrentCapacity"] intValue];
546
547 if (rEnergy != remainingCapacities.value(i) && rEnergy != 0) {
548 remainingCapacities[i] = rEnergy;
549 if (i == index)
550 Q_EMIT remainingCapacityChanged(remainingCapacities[i]);
551 }
552 int max = rEnergy / ((qreal)(curCapacityPercent) / 100);
553 maximumCapacities[i] = max;
554 }
555
556 if (batteries == 0) {
557 maximumCapacities[0] = -1;
558 remainingCapacities[0] = -1;
559 remainingChargingTimes[0] = -1;
560 voltages[0] = -1;
561 chargingStates[0] = QBatteryInfo::UnknownChargingState;
562 levelStatuss[0] = QBatteryInfo::LevelUnknown;
563 }
564 if (batDoctionary != NULL)
565 CFRelease(batDoctionary);
566 CFRelease(info);
567 CFRelease(list);
568 }
569
570 QT_END_NAMESPACE