Python 安卓手机电池管理

# -*- coding: utf-8 -*-
# -------------------------------
# @时间:2024/6/26 20:06
# @文件:battery.py

import subprocess


def get_devices():
    """获取设备sn列表"""
    sn_list = []
    try:
        output = subprocess.check_output(['adb', 'devices'])
    except subprocess.CalledProcessError as e:
        print("Error:", e.output)
        return None
    for line in output.decode('utf-8').splitlines():
        if line.endswith("device"):
            sn = line.split()[0]
            sn_list.append(sn)
    return sn_list


def get_battery_info(sn):
    """获取电池百分比,充电状态"""
    try:
        output = subprocess.check_output(['adb', '-s', sn, 'shell', 'dumpsys', 'battery'])
    except subprocess.CalledProcessError as e:
        print("Error:", e.output)
        return None
    level, charge_status = None, None
    for line in output.decode('utf-8').splitlines():
        if "level" in line:
            level = line.split()[1]
        if "status" in line:
            charge_status = line.split()[1]
    return int(level), int(charge_status)


def set_battery_charge(sn, level, charge_status):
    """设置手机电池状态"""
    if level:
        if level <= 50 and charge_status == 0:
            status = 2
        elif level >= 90 and charge_status == 2:
            status = 0
    else:
        return None
    try:
        print(f'{sn} battery level is {level}')
        cmd = ['adb', '-s', sn, 'shell', 'dumpsys', 'battery', 'set', 'status', f'{status}']
        print(cmd)
        output = subprocess.check_output(cmd)
    except subprocess.CalledProcessError as e:
        print("Error:", e.output)


def battery_manager():
    sn_list = get_devices()
    if len(sn_list) > 0:
        for sn in sn_list:
            level, charge_status = get_battery_info(sn)
            if level and charge_status:
                set_battery_charge(sn, level, charge_status)
            else:
                print(f"{sn} get battery info fail!")
    else:
        print(f"未获取到设备列表")


if __name__ == '__main__':
    battery_manager()

``

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值