fix: v1.4.3 добавил защиту для случая если процесс bluetooth аварийно завершился, приложение считает его connected и не может подключиться

This commit is contained in:
2026-09-27 17:13:42 +03:00
parent 41a4d6cd1b
commit 2846fb0fbb
2 changed files with 82 additions and 4 deletions
+2 -2
View File
@@ -1,8 +1,8 @@
[version]
major = 1
minor = 4
patch = 2
patch = 3
[build]
date = "2026-09-27"
time = "09:21:09"
time = "17:12:58"
+80 -2
View File
@@ -1,4 +1,7 @@
import asyncio
import logging
import shutil
import sys
from typing import Any
from bleak import BleakScanner
from tion_btle import TionS4
@@ -7,6 +10,7 @@ from .models import TionState
from app.my_dataclasses import *
logger = logging.getLogger(__name__)
class TionController:
"""
@@ -88,12 +92,23 @@ class TionController:
# от предыдущего соединения.
await self._reset_device()
# Получаем свежий BLEDevice.
# Сначала обычный поиск.
ble_device = await BleakScanner.find_device_by_address(
self._mac,
timeout=5.0,
)
if ble_device is None:
# Возможно, предыдущий процесс умер через SIGKILL,
# а ОС всё ещё удерживает старое BLE-соединение.
await self._recover_stale_system_connection()
# После recovery пробуем найти Tion ещё раз.
ble_device = await BleakScanner.find_device_by_address(
self._mac,
timeout=5.0,
)
if ble_device is None:
raise ConnectionError(
f"Tion {self._mac} not found"
@@ -282,4 +297,67 @@ class TionController:
return self
async def __aexit__(self, exc_type, exc_value, traceback) -> None:
await self.disconnect()
await self.disconnect()
async def _recover_stale_system_connection(self) -> None:
"""
Попытаться освободить зависшее BLE-соединение,
оставшееся после аварийного завершения предыдущего процесса.
На Linux BlueZ может продолжать показывать Connected=yes,
хотя процесс-владелец уже умер. В таком состоянии Tion может
не advertising'иться, поэтому BleakScanner его не находит.
На других ОС ничего не делаем: основной код остаётся
платформенно-независимым.
"""
if not sys.platform.startswith("linux"):
return
bluetoothctl = shutil.which("bluetoothctl")
if bluetoothctl is None:
logger.warning(
"Tion stale-connection recovery skipped: "
"bluetoothctl not found"
)
return
logger.warning(
"Tion %s not found by scan; "
"trying to clear stale BlueZ connection",
self._mac,
)
process = await asyncio.create_subprocess_exec(
bluetoothctl,
"disconnect",
self._mac,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(),
timeout=5.0,
)
except asyncio.TimeoutError:
process.kill()
await process.communicate()
logger.warning(
"Timed out while clearing stale Tion BLE connection"
)
return
logger.warning(
"Tion BlueZ recovery finished: rc=%s stdout=%s stderr=%s",
process.returncode,
stdout.decode(errors="replace").strip(),
stderr.decode(errors="replace").strip(),
)
# Даём BlueZ и самому Tion время освободить старое соединение
# и снова начать advertising.
await asyncio.sleep(1.0)