Closed fishenebelny closed 4 years ago
И вспомнил. Что пришлось как-то править модуль tion-python. Кажется pair.py. В этом скрипте использовался класс s3, а его почему-то не было в python. Пришлось где-то переименовать с s3 на tion. И заработало.
@fishenebelny, что касается текущей ситуации (зависание при отправке команды, что похоже на #2 ):
logger:
default: warning
logs:
custom_components.tion.climate: debug
s3: debug
tion: debug
tion.s3: debug
pair сейчас посмотрю.
Pair поправил. Спасибо!
Я пока удалил компонент полнлстью (даже Bluepy и удалил paired device через bluetoothctl), так как зависания были, а сейчас пропали. Пока такие ощущения. Готов его установить и проверить все с нуля.
Я правильнл понимаю, что должна быть железка с BT(Raspberry pi 4 4Gb в моем случае) и Tion 3S (2 шт. в моем случае). В такой конфигурации все долюно работать без видимых проблем? Тип ОС (Raspbian или Hassio) не имеет значение? Я под hassio пробовал ставить, но там почему-то Bluepy не ставился никак....
И простая установка модуля HA-Tion через HACS? При жтом tion-python, Bluepy ручкаии ставить не предполагается? Верно?
@fishenebelny, доброго дня.
Спасибо за предложение помочь с проверкой установки. Было бы не плохо. Я посмотрел как другие компоненты используют bluepy: они указывают версию. Сделал также (обновление будет в v1.2.3, в ближайшие часы сделаю). Может быть это решит проблемы. Но не факт, поскольку все компоненты включенные в HA используют wheels с предсобранным bluepy (https://github.com/home-assistant/core/issues/24441). Если после задания версии проблемы при установке bluepy сохранятся -- дайте, пожалуйста, занть. Форсирую свои планы в этом направлении.
И простая установка модуля HA-Tion через HACS? При жтом tion-python, Bluepy ручкаии ставить не предполагается? Верно?
Верно. Идея перехода к установке через HACS и настройке через GUI именно в этом: чтобы пользователь ничего дополнительно не делал.
Про зависания: если будет возможность выложите debug логи в #2 (и давайте с этим вопросом туда перебираться, чтобы вся информация была в одном месте). Ситуация для меня непонятная: у самого (Raspberry 3, HA через venv, HASC+GUI, а до этого configuration.yaml + manual installation) все работает и никаких зависаний нет. Единственное подозрение такое: 2 инстанса одновременно начинают опрашивать свои бризеры и дерутся за BT. Так ли это покажет лог.
Проверил установку (Pi4 + venv + HA-Tion 1.2.5) - работает. Спаривается. Но не с первого раза, несмотря на то, что устройство добавилось и сказало что все прекрасно. Однако, ничего не работает. Захожу в bluetootchctl:
Проверил как телефон с точки установки малины подключается. Телефон подключился. Даже подключился к более дальнему тиону. Включил логи как описано выше. Выключил малину. Перенес малину в прямую видимость на расстоянии 5 метров. Включил. Объект climate,.tion_2 недоступен.
В логах пишет ошибку что-то там про сенсор было. Ниже логи.
По всей видимости не хочет подключаться.
Проверил Hassio. Модуль обновил со старой версии, предварительно удали старую неудачную запись. Устройство добавилось. Было написано что все в порядке!
Но hassio повис намертво. Даже по питанию перезагрузка пока не помогла. Вот уже 5 минут он в сети, пинги идут, но веб морды так и нет.
Попробую проверить Bluetooth модуль с колонками.
Проверил работу Bluetooth. С телефоном моим через Bluetoothctl спарился. С колонками, с которыми раньше спаривался, а потом удалил выдает ошибку. Но с Тиjном спаривается. bluetoothctl -> paired devices и Тион тут есть.
Даже корпус снял, чтоб убедиться, что он не мешает никак. Какой-то запрос проходит, а потом все... тишина. Connectec yes/no/yes/no.
@fishenebelny, спасибо за проделанную работу и логи. bluetoothctl для tion не показатель. У него свой механизм pairing'a и однозначно ответить что pair прошел правильно можно только по факту "все работает".
После заливки модуля на PyPi он называется tion_btle (извините, документация не успевает за разработкой):
logger:
default: warning
logs:
custom_components.tion: debug
tion_btle.tion: debug
tion_btle.s3: debug
(readme обновил) Выглядеть логи будут примерно так:
2020-08-24 10:18:09 DEBUG (MainThread) [tion_btle.tion] Doing _connect. Attempt 1/3
2020-08-24 10:18:11 DEBUG (MainThread) [tion_btle.tion] Enabling notification
2020-08-24 10:18:11 DEBUG (MainThread) [tion_btle.tion] Notify handler is 11
2020-08-24 10:18:11 DEBUG (MainThread) [tion_btle.tion] Will write b'\x01\x00' to 12 handle
2020-08-24 10:18:11 DEBUG (MainThread) [tion_btle.tion] Result is {'rsp': ['wr']}
2020-08-24 10:18:11 DEBUG (MainThread) [tion_btle.tion] Doing _try_write. Attempt 1/3
2020-08-24 10:18:11 DEBUG (MainThread) [tion_btle.tion] Writing 3d0100000000000000000000000000000000005a to 6e400002-b5a3-f393-e0a9-e50e24dcca9e
2020-08-24 10:18:11 DEBUG (MainThread) [tion_btle.tion] Got data in 11 response b310241403001514148f000c0a004b0a0033005a
После того как в логах выставлен правильный уровень отладки нужно:
Иногда бывает такое, что после pair бризер в течении 5-10 минут вообще отказывается принимать соедиения. Так что, возможно, придется подождать перед последними шагами чуть дольше.
По текущим логам я вижу что: BT на малине работает нормально, вероятно не проходит нормальное сопряжение и/или во время работы через HA к бризеру подключается пульт или телефон.
Подключение-отключение к бризеру, которое видно через bluetoothctl, -- нормально. BTLE протокол тут устроен так, что не позволяет двум клиентам работать с одним устройством. Поэтому, чтобы сохранить возможность управления бризером через телефон и пульт, компонент подключается к бризеру только если нужно обновить данные или передать команду.
В v1.3.0, среди прочего, обновил механизм добавления бризера: теперь на этапе конфигурации будет сообщаться о проблемах с сопряжением/подключением и если такие проблемы есть бризер в конфигурацию не добавится.
Первая попытка
Could not pair! Error occurs while pairing routine! Check logs for details.
Вторая попытка через минуту - процесс настройки закончился успешно. Тион управляется. Но в логах сервера все равно какие-то сообщения. Второй не могу сейчас пробовать, завтра попробую.
Tion instance updated at None 1:08:20 – Tion breezer (WARNING) - первое сообщение получено 1:03:57 и повторялось 8 раз Need to set mode to heat 1:07:37 – Tion breezer (WARNING) Init of sensor input temperature for 66d6f182c5e144baa7fd2de9be7788e5 1:03:58 – Tion breezer (WARNING) - первое сообщение получено 1:03:58 и повторялось 2 раз No previously saved temperature, setting to 22 1:03:58 – Tion breezer (WARNING)
Относительно управления с других устройств. В настройках Tion Remote есть галочка "Передача управления". Я так понимаю, если она включена, то можно и с пульта подключиться и с малины. И проблем быть не должно.
В v1.3.0, среди прочего, обновил механизм добавления бризера: теперь на этапе конфигурации будет сообщаться о проблемах с сопряжением/подключением и если такие проблемы есть бризер в конфигурацию не добавится.
В первой попытке как раз ничего не добавилось.
Первая попытка подключить второй Тион. Неудачная. Тион был включен. Появились следующие сообщения:
Tion instance updated at 2020-08-25 07:10:59.163314+00:00
10:15:39 – Tion breezer (WARNING) - первое сообщение получено 1:49:58 и повторялось 507 раз
Cannot pair and get data. Result is {}, error: ('_connect', 'Could not connect to c4:64:95:c3:5e:79')
10:15:39 – Tion breezer (ERROR)
Got exception while _connect: Failed to connect to peripheral d5:91:dd:fc:1a:60, addr type: random
10:15:39 – /srv/homeassistant/lib/python3.7/site-packages/tion_btle/tion.py (WARNING) - первое сообщение получено 1:58:00 и повторялось 28 раз
Got Failed to connect to peripheral d5:91:dd:fc:1a:60, addr type: random exception
10:15:37 – /srv/homeassistant/lib/python3.7/site-packages/tion_btle/tion.py (WARNING) - первое сообщение получено 1:57:58 и повторялось 28 раз
Вторая попытка. Выключил Тион, дождался отключения пульта. Не подключилось. При этом никаких ошибок не было показано. Просто бесконечно крутится кружочек в момент спаривания и все.
Попытка 3.
Появилось сообщение интеграции. Could not pair! Error occurs while pairing routine! Check logs for details.
Четвертая тоже не дала спариться. Заканчиаю попытки, жду обратной связи.
@fishenebelny, спасибо за логи. Сейчас буду разбираться.
Относительно управления с других устройств. В настройках Tion Remote есть галочка "Передача управления". Я так понимаю, если она включена, то можно и с пульта подключиться и с малины. И проблем быть не должно.
Нет, это не так. "Передача управления" в настройках приложения означает что приложение подключается к бризеру только для передачи команд и обновления статуса и не держит соединение открытым постоянно. Можете самостоятельно провести эксперимент: подключиться к бризеру пультом, постоянно что-то с пульта делать (менять температуру +/-1 градус) и в этот же момент попробовать подключиться приложением. Приложение скажет что не может подключиться к бризеру или пульт потеряет соединение.
подключиться к бризеру пультом, постоянно что-то с пульта делать (менять температуру +/-1 градус) и в этот же момент попробовать подключиться приложением. Приложение скажет что не может подключиться к бризеру или пульт потеряет соединение.
Оьращал внимание на такое. Когда с одного телефона настройки меняли, другой уже не подключался. Я подумал, что эта галочка как раз и решает эту проблемв. Попробую проверить.
@fishenebelny, в ваших логах я вижу ошибки подключения: малина не может подключиться к бризеру. Точно ли в этот момент с бризером никто не общается (из пульта вынута батарейка, на телефоне отключен BT итд и с момента отключения прошло хотя бы минут 5: для нормальной работы 5 минут не нужно, но сейчас я вижу что что-то идет не так на стадии подключения и хорошо бы убедиться что все подключения сброшены).
Далее по попыткам:
Я вижу два бризера. К которым одновременно, в 10:15:39 пытается подключиться малина. Само по себе это не смертельно, но неприятно и я попытаюсь разнести параллельные запросы в будущем. До этого в 08:13:32 малина, на фоне не занятого BT, не смогла подключиться к бризеру c4:64:95:c3:5e:79. Она пыталась это сделать 1.5 минуты. Тут от вас нужно подтверждение что все происходит в "стерильной" обстановке и с бризером никто не общается в этот момент. Запрос на обновление второго бризера пришел в 07:13:59 (тут я думаю есть проблемы с временными зонами и на самом деле это 08:13:59), терпеливо подождал пока все обновится и корректно отработал. Итого: проблем в работе модуля и компонента я не вижу.
К бризеру подключение прошло со второго раза (видимо чуть поторопились после отключения пульта). Pair прошел корректно (дальше pair для c4:64:95:c3:5e:79 делать не нужно). Завалился модуль на чтении из notify топика на стадии включения уведомлений. С этим буду разбираться.
Тут все ожидаемо (я с таким уже сталкивался) после device disconnected после pair бризер не рвет соединение сразу. Людям помогает подождать минут 5-10, после этого все начинает "само" работать нормально.
С шестой попытки Pairing прошел. Перед этим перезагрузил Home Assistant.
Значит нужно выставить задержку между завершением pair и проверкой что все нормально в компоненте, потому что стадия pair (на уровне устройств) у вас нормально завершилась во вторых логах.
Теперь при попытке включить проветриватели они очень долго думали. Минуты 2-3 прошло и потом они внезапно включились. Кажется теперь проблема с зависаними будет.
```
2020-08-25 12:00:00 WARNING (MainThread) [custom_components.tion] Tion instance updated at 2020-08-25 11:00:00.911783+00:00
2020-08-25 12:00:00 DEBUG (MainThread) [custom_components.tion] Update fired force = False. Keep connection is False
2020-08-25 12:00:00 DEBUG (MainThread) [custom_components.tion] Now is 2020-08-25 11:00:00.911783+00:00
2020-08-25 12:00:00 DEBUG (MainThread) [tion_btle.tion] Doing _connect. Attempt 1/3
2020-08-25 12:00:01 DEBUG (MainThread) [tion_btle.tion] Enabling notification
2020-08-25 12:00:01 DEBUG (MainThread) [tion_btle.tion] Notify handler is 11
2020-08-25 12:00:01 DEBUG (MainThread) [tion_btle.tion] Will write b'\x01\x00' to 12 handle
2020-08-25 12:00:01 DEBUG (MainThread) [tion_btle.tion] Result is {'rsp': ['wr']}
2020-08-25 12:00:02 DEBUG (MainThread) [tion_btle.tion] Doing _try_write. Attempt 1/3
2020-08-25 12:00:02 DEBUG (MainThread) [tion_btle.tion] Writing 3d0100000000000000000000000000000000005a to 6e400002-b5a3-f393-e0a9-e50e24dcca9e
2020-08-25 12:00:02 DEBUG (MainThread) [tion_btle.tion] Got data in 11 response b310260a01001717164b010d1f00001d0033005a
2020-08-25 12:00:27 WARNING (MainThread) [custom_components.tion] Tion instance updated at 2020-08-25 11:00:27.941153+00:00
2020-08-25 12:00:27 DEBUG (MainThread) [custom_components.tion] Update fired force = False. Keep connection is False
2020-08-25 12:00:27 DEBUG (MainThread) [custom_components.tion] Now is 2020-08-25 11:00:27.941153+00:00
2020-08-25 12:00:27 DEBUG (MainThread) [tion_btle.tion] Doing _connect. Attempt 1/3
2020-08-25 12:00:31 DEBUG (MainThread) [tion_btle.tion] Enabling notification
2020-08-25 12:00:31 DEBUG (MainThread) [tion_btle.tion] Notify handler is 11
2020-08-25 12:00:31 DEBUG (MainThread) [tion_btle.tion] Will write b'\x01\x00' to 12 handle
2020-08-25 12:00:32 DEBUG (MainThread) [tion_btle.tion] Result is {'rsp': ['wr']}
2020-08-25 12:00:33 DEBUG (MainThread) [tion_btle.tion] Doing _try_write. Attempt 1/3
2020-08-25 12:00:33 DEBUG (MainThread) [tion_btle.tion] Writing 3d0100000000000000000000000000000000005a to 6e400002-b5a3-f393-e0a9-e50e24dcca9e
2020-08-25 12:00:33 DEBUG (MainThread) [tion_btle.tion] Got data in 11 response b310210a0100171716ab000d270000bd0033005a
2020-08-25 12:00:55 WARNING (MainThread) [custom_components.tion.climate] Need to set mode to heat
2020-08-25 12:00:55 INFO (MainThread) [custom_components.tion.climate] Need to set: heater='on', status='on'
2020-08-25 12:00:55 INFO (MainThread) [custom_components.tion] Need to set: heater='on', status='on'
2020-08-25 12:00:55 DEBUG (MainThread) [tion_btle.tion] Doing _connect. Attempt 1/3
2020-08-25 12:00:57 DEBUG (MainThread) [tion_btle.tion] Doing _connect. Attempt 1/3
2020-08-25 12:00:57 DEBUG (MainThread) [tion_btle.tion] Enabling notification
2020-08-25 12:00:57 DEBUG (MainThread) [tion_btle.tion] Notify handler is 11
2020-08-25 12:00:57 DEBUG (MainThread) [tion_btle.tion] Will write b'\x01\x00' to 12 handle
2020-08-25 12:00:57 DEBUG (MainThread) [tion_btle.tion] Result is {'rsp': ['wr']}
2020-08-25 12:00:59 DEBUG (MainThread) [tion_btle.tion] Doing _try_write. Attempt 1/3
2020-08-25 12:00:59 DEBUG (MainThread) [tion_btle.tion] Writing 3d0100000000000000000000000000000000005a to 6e400002-b5a3-f393-e0a9-e50e24dcca9e
2020-08-25 12:00:59 DEBUG (MainThread) [tion_btle.tion] Got data in 11 response b310210a0100161616ab000d270000bd0033005a
2020-08-25 12:00:59 DEBUG (MainThread) [tion_btle.tion] Doing _try_write. Attempt 1/3
2020-08-25 12:01:00 WARNING (MainThread) [tion_btle.tion] Got Device disconnected exception
2020-08-25 12:01:02 WARNING (MainThread) [tion_btle.tion] Got exception while _try_write: Device disconnected
2020-08-25 12:01:02 DEBUG (MainThread) [tion_btle.tion] Doing _try_write. Attempt 2/3
2020-08-25 12:01:03 DEBUG (MainThread) [tion_btle.tion] Writing 3d02010a0203000000000000000000000000005a to 6e400002-b5a3-f393-e0a9-e50e24dcca9e
2020-08-25 12:01:03 WARNING (MainThread) [custom_components.tion] Tion instance updated at None
2020-08-25 12:01:03 DEBUG (MainThread) [custom_components.tion] Update fired force = True. Keep connection is False
2020-08-25 12:01:03 DEBUG (MainThread) [tion_btle.tion] Doing _connect. Attempt 1/3
2020-08-25 12:01:04 WARNING (MainThread) [tion_btle.tion] Got Device disconnected exception
2020-08-25 12:01:06 WARNING (MainThread) [tion_btle.tion] Got exception while _connect: Device disconnected
2020-08-25 12:01:06 DEBUG (MainThread) [tion_btle.tion] Doing _connect. Attempt 2/3
2020-08-25 12:01:08 WARNING (MainThread) [tion_btle.tion] Got Device disconnected exception
2020-08-25 12:01:10 WARNING (MainThread) [tion_btle.tion] Got exception while _connect: Device disconnected
2020-08-25 12:01:10 DEBUG (MainThread) [tion_btle.tion] Doing _connect. Attempt 3/3
2020-08-25 12:01:12 DEBUG (MainThread) [tion_btle.tion] Enabling notification
2020-08-25 12:01:12 DEBUG (MainThread) [tion_btle.tion] Notify handler is 11
2020-08-25 12:01:12 DEBUG (MainThread) [tion_btle.tion] Will write b'\x01\x00' to 12 handle
2020-08-25 12:01:13 DEBUG (MainThread) [tion_btle.tion] Result is {'rsp': ['wr']}
2020-08-25 12:01:14 CRITICAL (MainThread) [custom_components.tion] Got exception Device disconnected
2020-08-25 12:01:14 CRITICAL (MainThread) [custom_components.tion] Will delay next check
2020-08-25 12:01:14 WARNING (MainThread) [custom_components.tion] Tion instance updated at 2020-08-25 11:01:00.912516+00:00
2020-08-25 12:01:14 DEBUG (MainThread) [custom_components.tion] Update fired force = False. Keep connection is False
2020-08-25 12:01:14 DEBUG (MainThread) [custom_components.tion] Now is 2020-08-25 11:01:00.912516+00:00
2020-08-25 12:01:14 DEBUG (MainThread) [tion_btle.tion] Doing _connect. Attempt 1/3
2020-08-25 12:01:15 DEBUG (MainThread) [tion_btle.tion] Enabling notification
2020-08-25 12:01:15 DEBUG (MainThread) [tion_btle.tion] Notify handler is 11
2020-08-25 12:01:15 DEBUG (MainThread) [tion_btle.tion] Will write b'\x01\x00' to 12 handle
2020-08-25 12:01:15 DEBUG (MainThread) [tion_btle.tion] Result is {'rsp': ['wr']}
2020-08-25 12:01:16 DEBUG (MainThread) [tion_btle.tion] Doing _try_write. Attempt 1/3
2020-08-25 12:01:16 DEBUG (MainThread) [tion_btle.tion] Writing 3d0100000000000000000000000000000000005a to 6e400002-b5a3-f393-e0a9-e50e24dcca9e
2020-08-25 12:01:16 DEBUG (MainThread) [tion_btle.tion] Got data in 11 response b310260a01001717164b010d2000001d0033005a
2020-08-25 12:01:16 ERROR (MainThread) [homeassistant.core] Error executing service:
Зависания есть. История не подгружается. Или подгружается через какое-то время, чего раньше не было.
ОК. Я понял/вижу: нужны очереди и поменьше await, поскольку на это время блокируется работа HA. Ровно ситуация в #2
Пока придется пользоваться одним бризером через HA (с одним проблем быть не должно).
Что-то еще (кроме дополнительной паузы во время сопряжения), в рамках этого issue нужно прояснить/сделать, на ваш взгляд?
Спасибо за оперативный ответ!
Что-то еще (кроме дополнительной паузы во время сопряжения), в рамках этого issue нужно прояснить/сделать, на ваш взгляд?
В рамках установки? На данный момент вроде отлично работает. Может быть не имеет смысла только мак адрес вводить. Вче таки Тион видется средствами Блютуз и это можно автомат зировать по аналошии как обычный пульт сопрягается. Добавить комментарий - что за пауза 60 секунд? Интервал опроса устройства? Ну и какую то информацию в случае ошибки. Мол повторите еще раз откдючив все пульты, телефоны, которые могут управлять устройством.
Scan и автоматическое добавление устройств -- это хорошо и правильно, но, пока, сложно и не очень обязательные рюшечки, на которые нужно потратить достаточно много времени. Можно под это завести отдельный issue (чтобы идея не потерялась), но у меня, в ближайшее время, до этого руки не дойдут.
Про keep alive в настройках понял, добавлю. Информацию при ошибке тоже перепишу обновлю. Спасибо.
Не могли бы вы описать реквизиты установи модуля и какой-то порядок действий чуть более детально? Я пробовал установить модуль на hassio (готовая флешка Home assistant). Но при попытке связать устройства получал ошибку. У меня сейчас все работает на Raspberry OS + venv установка Home assistant. Но, откровенно, я это смог "каким-то" образом установить. Пришлось вручную ставить Bluepy, tion-python. Потом вручную при помощи pair.py связывать Тионы. И сейчас все работает нестабильно. Перезагружаю систему, отправляю команду на Тион - все ок. Через 5 минут эту же команду, на этот же Тион уже не отправить. Все висит. И выглядит так, что висит из-за этой команды все.