Состояние Bluetooth и батареи
Показывает подключённые устройства, их адреса и оставшийся заряд из system_profiler
Что делает скрипт
Скрипт разбирает JSON system_profiler SPBluetoothDataType и находит контроллер, подключённые и сохранённые устройства. Для наушников и клавиатур выводятся доступные поля заряда. Это только чтение, Bluetooth не включается и не выключается.
Быстрый старт
python3 bluetooth_status.py
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python3 bluetooth_status.pypython3 bluetooth_status.py --json bluetooth.json
Что понадобится
brew install python
bluetooth_status.py
#!/usr/bin/env python3
"""Состояние Bluetooth-контроллера и устройств macOS."""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from pathlib import Path
BATTERY_KEYS = (
"device_batteryLevel",
"device_batteryLevelLeft",
"device_batteryLevelRight",
"device_batteryLevelCase",
"device_batteryLevelMain",
)
def load_profiler() -> list[dict]:
result = subprocess.run(
["system_profiler", "SPBluetoothDataType", "-json"],
capture_output=True,
text=True,
check=False,
)
if result.returncode != 0:
print(f"system_profiler завершился с ошибкой: {result.stderr.strip()}", file=sys.stderr)
return []
try:
data = json.loads(result.stdout)
except json.JSONDecodeError as error:
print(f"Не удалось разобрать JSON: {error}", file=sys.stderr)
return []
entries = data.get("SPBluetoothDataType", [])
return entries if isinstance(entries, list) else [entries]
def section_devices(entry: dict, section: str):
items = entry.get(section, [])
if isinstance(items, dict):
items = [items]
if not isinstance(items, list):
return
for item in items:
if not isinstance(item, dict):
continue
for name, info in item.items():
if isinstance(info, dict):
yield name, info
def controller_info(entry: dict) -> dict:
props = entry.get("controller_properties", {})
if not isinstance(props, dict):
return {}
return {
"address": props.get("controller_address", ""),
"state": props.get("controller_state", ""),
"power": props.get("controller_powerState", ""),
"firmware": props.get("controller_firmwareVersion", ""),
}
def main() -> int:
parser = argparse.ArgumentParser(description="Показать состояние Bluetooth")
parser.add_argument("--json", type=Path)
args = parser.parse_args()
entries = load_profiler()
if not entries:
print("Данные Bluetooth недоступны. Проверьте, включён ли адаптер.")
return 1
report = {"controller": {}, "devices": []}
for entry in entries:
if not isinstance(entry, dict):
continue
if not report["controller"]:
report["controller"] = controller_info(entry)
for section, connected in (("device_connected", True), ("device_not_connected", False)):
for name, info in section_devices(entry, section):
battery = {key: info[key] for key in BATTERY_KEYS if key in info}
report["devices"].append(
{
"name": name,
"connected": connected,
"address": info.get("device_address", ""),
"type": info.get("device_minorType", ""),
"battery": battery,
}
)
if args.json:
args.json.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
controller = report["controller"]
print("Контроллер Bluetooth:")
print(f" адрес: {controller.get('address') or 'неизвестно'}")
print(f" состояние: {controller.get('state') or 'неизвестно'}")
print(f" питание: {controller.get('power') or 'неизвестно'}")
print(f" прошивка: {controller.get('firmware') or 'неизвестно'}")
if not report["devices"]:
print("\nУстройства не найдены.")
return 0
print(f"\nУстройств: {len(report['devices'])}.")
for device in report["devices"]:
status = "подключено" if device["connected"] else "не подключено"
print(f"\n{device['name']} ({status})")
if device["address"]:
print(f" адрес: {device['address']}")
if device["type"]:
print(f" тип: {device['type']}")
if device["battery"]:
parts = ", ".join(f"{key.replace('device_batteryLevel', '') or 'заряд'}: {value}" for key, value in device["battery"].items())
print(f" батарея: {parts}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.