| 1 | ''' |
| 2 | Module of MacOS API for plyer.battery. |
| 3 | ''' |
| 4 | |
| 5 | from os import environ |
| 6 | from subprocess import Popen, PIPE |
| 7 | from plyer.facades import Battery |
| 8 | from plyer.utils import whereis_exe |
| 9 | |
| 10 | |
| 11 | class OSXBattery(Battery): |
| 12 | ''' |
| 13 | Implementation of MacOS battery API. |
| 14 | ''' |
| 15 | |
| 16 | def _get_state(self): |
| 17 | old_lang = environ.get('LANG', '') |
| 18 | environ['LANG'] = 'C' |
| 19 | |
| 20 | status = {"isCharging": None, "percentage": None} |
| 21 | |
| 22 | ioreg_process = Popen( |
| 23 | ["ioreg", "-rc", "AppleSmartBattery"], |
| 24 | stdout=PIPE |
| 25 | ) |
| 26 | output = ioreg_process.communicate()[0] |
| 27 | |
| 28 | environ['LANG'] = old_lang |
| 29 | |
| 30 | if not output: |
| 31 | return status |
| 32 | |
| 33 | is_charging = max_capacity = current_capacity = None |
| 34 | for line in output.decode('utf-8').splitlines(): |
| 35 | if 'IsCharging' in line: |
| 36 | is_charging = line.rpartition('=')[-1].strip() |
| 37 | if 'MaxCapacity' in line: |
| 38 | max_capacity = float(line.rpartition('=')[-1].strip()) |
| 39 | if 'CurrentCapacity' in line: |
| 40 | current_capacity = float(line.rpartition('=')[-1].strip()) |
| 41 | |
| 42 | if is_charging: |
| 43 | status['isCharging'] = is_charging == "Yes" |
| 44 | |
| 45 | if current_capacity and max_capacity: |
| 46 | status['percentage'] = 100.0 * current_capacity / max_capacity |
| 47 | |
| 48 | return status |
| 49 | |
| 50 | |
| 51 | def instance(): |
| 52 | ''' |
| 53 | Instance for facade proxy. |
| 54 | ''' |
| 55 | import sys |
| 56 | if whereis_exe('ioreg'): |
| 57 | return OSXBattery() |
| 58 | sys.stderr.write("ioreg not found.") |
| 59 | return Battery() |