Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to send key - Error: failed to find a BLE device #91

Closed
trygve opened this issue Jul 15, 2024 · 41 comments
Closed

Unable to send key - Error: failed to find a BLE device #91

trygve opened this issue Jul 15, 2024 · 41 comments
Labels
help wanted Extra attention is needed

Comments

@trygve
Copy link

trygve commented Jul 15, 2024

[23:25:51] NOTICE: Attempt 5/5 to delivery the public key to vin ************* [23:25:51] ERROR: teslaCtrlSendKey; Error: failed to find a BLE device: can't init hci: no devices available: (hci0: can't down device: no such device) [23:25:51] ERROR: Could not send the key; Is the car awake and sufficiently close to the bluetooth adapter?

I can see that the cars presence is detected in the addon, so that means it should be in rage?
The car is approximately 5 meters away from my HA server which has a bluetooth antenna (Intel NUC).

How can I go about troubleshooting this?

@baylanger
Copy link
Collaborator

The can't init hci: no devices available error sounds like the Bluetooth adapter isn't accessible by the add-on container.

What hardware do you use (board & BT adapter)?

You could also try to configure the bluetooth_LE_tracker or iBeacon integration and see if those allow you to pick your BT adapter.

@trygve
Copy link
Author

trygve commented Jul 15, 2024

Hi @baylanger, thanks for your reply.

I have an Intel NUC NUC10I3FNH2, which runs proxmox -> HA.
I believe this is the specs: https://www.intel.com/content/dam/support/us/en/documents/intel-nuc/NUC10i357FN_TechProdSpec.pdf

This is the first time I have tried to use Bluetooth in my setup, so Im not sure what works and not.
I tried to enable the iBeacon adapter and my TMY seems to appear there.
The Tesla Local Commands Logs also says that presence is detected of the car.

Does that suggest the Bluetooth adapter is accessible, or is there a fundamental difference in receive vs send?

@baylanger
Copy link
Collaborator

It's interested to see Intel has a page dedicated for Bluetooth issues. I doubt you fall into that category.

It still puzzle me to see that hci0 adapter. The error Error: failed to find a BLE device: can't init hci: no devices available: (hci0: can't down device: no such device) likely comes from tesla-command but I can't confirm.

Can you turn on debugging mode, it's accessible via the "optional settings". Perhaps we'll get a little more info.

Do you have Advance SSH installed? If not we might need it to go log into the container like this:

docker  exec -ti addon_local_tesla_local_commands bash

Before doing that, lets take a look at debug level.

@trygve
Copy link
Author

trygve commented Jul 16, 2024

[02:22:00] NOTICE: Listening for Home Assistant Start (in background)
[02:22:00] INFO: Entering main loop...
[02:22:00] NOTICE: Lauching background listen_to_mqtt_loop...
[02:22:00] INFO: Launch BLE scanning for car presence every 120 seconds
[02:22:00] NOTICE: Entering Listen to MQTT loop...
[02:22:00] DEBUG: Launching bluetoothctl to check for BLE presence
[02:22:00] INFO: Launching listen_to_mqtt
[02:22:00] INFO: Listening to MQTT
[02:22:11] DEBUG: [NEW] Device ************** **************
[CHG] Device ************** RSSI: 0xffffffad (-83)
[02:22:11] INFO: VIN ************** BLE MAC & LN (|) presence detected
[02:22:11] INFO: VIN ************** (|) TTL expired, set presence ON
[02:22:11] DEBUG: mqtt topic tesla_ble//binary_sensor/presence succesfully updated to ON
[02:22:11] DEBUG: VIN ************** (
|) update presence expire time to 1721089571
[02:22:15] INFO: Received MQTT message; topic:tesla_ble/
/config msg:deploy-key vin:************** cmd:config
[02:22:15] DEBUG: deploy-key; calling deployKeyMain()
[02:22:15] DEBUG: deployKeyMain; calling teslaCtrlSendKey()
[02:22:15] INFO: Trying to deploy the public key to vin:**************
[02:22:15] NOTICE: Attempt 1/5 to delivery the public key to vin **************
[02:22:15] ERROR: teslaCtrlSendKey; Error: failed to find a BLE device: can't init hci: no devices available: (hci0: can't down device: no such device)
[02:22:15] ERROR: Could not send the key; Is the car awake and sufficiently close to the bluetooth adapter?
[02:22:15] NOTICE: teslaCtrlSendKey; Retrying in 5 seconds
[02:22:20] NOTICE: Attempt 2/5 to delivery the public key to vin **************
[02:22:20] ERROR: teslaCtrlSendKey; Error: failed to find a BLE device: can't init hci: no devices available: (hci0: can't down device: no such device)
[02:22:20] ERROR: Could not send the key; Is the car awake and sufficiently close to the bluetooth adapter?
[02:22:20] NOTICE: teslaCtrlSendKey; Retrying in 5 seconds
[02:22:25] NOTICE: Attempt 3/5 to delivery the public key to vin **************
[02:22:25] ERROR: teslaCtrlSendKey; Error: failed to find a BLE device: can't init hci: no devices available: (hci0: can't down device: no such device)
[02:22:25] ERROR: Could not send the key; Is the car awake and sufficiently close to the bluetooth adapter?
[02:22:25] NOTICE: teslaCtrlSendKey; Retrying in 5 seconds
[02:22:30] NOTICE: Attempt 4/5 to delivery the public key to vin **************
[02:22:30] ERROR: teslaCtrlSendKey; Error: failed to find a BLE device: can't init hci: no devices available: (hci0: can't down device: no such device)
[02:22:30] ERROR: Could not send the key; Is the car awake and sufficiently close to the bluetooth adapter?
[02:22:30] NOTICE: teslaCtrlSendKey; Retrying in 5 seconds
[02:22:35] NOTICE: Attempt 5/5 to delivery the public key to vin **************
[02:22:35] ERROR: teslaCtrlSendKey; Error: failed to find a BLE device: can't init hci: no devices available: (hci0: can't down device: no such device)
[02:22:35] ERROR: Could not send the key; Is the car awake and sufficiently close to the bluetooth adapter?
[02:22:35] DEBUG: deployKeyMain; key was not delivered

So I guess not much help here?

Yes, I have SSH installed, so I can ssh to the instance. What do you need me to do?

@baylanger
Copy link
Collaborator

baylanger commented Jul 16, 2024

True not much in those logs. Just to make sure, for ssh I refer to the Advance SSH add-on to ssh to HAOS using, by default, username hassio.

Inside the container run the following;

  • type bluetoothctl and once inside that application, run command list and then show - This should tell us if the adapter is hci0 or not. Then you can type exit

  • Lets see what's going on with tesla-control ... run this command:

vin=REPLACE_WITH_YOUR_VIN
/usr/bin/tesla-control -debug -vin $vin -ble add-key-request /share/tesla_ble_mqtt/${vin}_public.pem owner cloud_key

@baylanger
Copy link
Collaborator

baylanger commented Jul 16, 2024

Could you have too many BLE devices configured in your car?

The vehicle has a BLE connection limit of 3 devices (from what I've seen on my M3LR). If you try to connect another device, it will not be able to, and will just give an error on the device trying to connect.
Ref: https://teslabtapi.lexnastin.com/docs/tips#connection-limit

Your vehicle uses Bluetooth and BLE (Bluetooth Low Energy) to seamlessly connect your smartphone to Model 3.
Ref: https://www.tesla.com/ownersmanual/model3/en_us/GUID-3D90EA76-8DE3-4808-B7E4-1979EF299F3A.html

@raphmur
Copy link
Collaborator

raphmur commented Jul 16, 2024

Do you restart the system from time to time?

@trygve Additionnal info: in another thread, somebody had similar issue... Just running bluetoothctl scan on in a terminal inside Home Assistant made the thing work. Maybe worth a try:
You can use the "Terminal & SSH" addon, add the package bluez in the options:
image

And then in the terminal run the above command: bluetoothctl scan on

I wonder... How did you install Homeassistant on the NUC? HA OS? Container? Supervised? Core? This will have an impact on the available devices in Home Assistant, especially the "Container" mode

@trygve The option on more than 3 devices might be relevant to look at. First hand Tesla purchase? No other tool (like TeslaKee) or similar gadget that connects to the car?

@raphmur raphmur added the help wanted Extra attention is needed label Jul 16, 2024
@Gates1234
Copy link

Gates1234 commented Jul 17, 2024

moved to #93

@baylanger baylanger changed the title Unable to send key Unable to send key - Error: failed to find a BLE device Jul 17, 2024
@raphmur
Copy link
Collaborator

raphmur commented Jul 17, 2024

@Gates1234 issue moved here: #93 as it is different

@baylanger
Copy link
Collaborator

baylanger commented Jul 17, 2024

Good news, I was able to reproduce the original issue posted by @trygve

  • Recap of the error; in order to communicate with the car, tesla-control, an official app available from Tesla, tries to open the Bluetooth adapter using the device name hci0.

Snippet from the error:

hci0: can't down device: no such device

  • Running bluetoothclt mgmt.info in Home Assistant terminal or over SSH:
# bluetoothctl mgmt.info
Index list with 1 item
hci1:	Primary controller
	addr 04:42:1A:XX:XX:XX version 10 manufacturer 93 class 0x6c0000
{snip}
  • Somehow the adapter is listed ashci1 but in the past, it was on hci0 - this is quite odd.

bluetoothctl by default will pick the first available controller. It also allows via an argument to pick a specific adapter.

Currently tesla-control doesn't allow to specify an adapter via cli nor does it try to find an available adapter if hci0 doesn't exist.

  • Two possible ways to fix the issue:
  1. There's probably a way to pin the adapter to using a udev rule file. Those are located in the directory /lib/udev/rules.d but if you look at the default ones in HAOS, there's no good example. The directory location differs between Linux distributions. Some are located in /etc/udev/rules.d - If anyone here has time to figure this out, go ahead otherwise will try to find a solution.
  2. There's already an issue open with tesla-control. If it doesn't get fixed, the source code is available.

[EDIT] a reboot of my NAS brought back the device to hci0 !

@trygve
Copy link
Author

trygve commented Jul 17, 2024

@baylanger
You nailed it!
This is my exact issue.

~ # bluetoothctl mgmt.info
Index list with 1 item
hci1: Primary controller
addr XXXXXXX version 11 manufacturer 2 class 0x6c0000
supported settings: powered connectable fast-connectable discoverable bondable link-security ssp br/edr le advertising secure-conn debug-keys privacy configuration static-addr phy-configuration wide-band-speech
current settings: powered ssp br/edr le secure-conn wide-band-speech
name homeassistant
short name
hci1: Configuration options
supported options: public-address
missing options:
~ #
~ #

After Proxmox and HA reboot

~ # bluetoothctl mgmt.info
Index list with 1 item
hci0: Primary controller
addr XXXXXXXX version 11 manufacturer 2 class 0x6c0000
supported settings: powered connectable fast-connectable discoverable bondable link-security ssp br/edr le advertising secure-conn debug-keys privacy configuration static-addr phy-configuration wide-band-speech
current settings: powered ssp br/edr le secure-conn wide-band-speech
name homeassistant
short name
hci0: Configuration options
supported options: public-address
missing options:
~ #

Btw, I had to reboot twice, so no guarantee that it will connect to hci0.

@baylanger Do you have a link to the tesla-control issue? Do you think it would be beneficial to comment there with a link to this issue? The more ppl with this problem, the higher the chance for a fix :)

@baylanger
Copy link
Collaborator

baylanger commented Jul 17, 2024

Here's the Tesla issue

There's already a PR in draft to improve BLE. I could be wrong but I think this is an initiative from an outsider, if so we don't know if it will ever get merged.

I personally tend to avoid writing something like "Me too I have this problem" as it creates noise, unless I have something to bring. I have found multiple people complaining on the fact the adapter resets and jumps from hci0 to hci1 and vice-versa. For the kernel to reset the adapter, fine but it's very likely there's a racing condition between the thread that detects a new device and the one resetting it. That would explain the jump, the thread detecting is adding the device before the thread that did the reset finishes the work. Feel free to put comments if not, there's a subscribe button on each of the page (Issue & PR).

In the meantime, I'm not a Go developer but I did start to try adding the missing functionality to tesla-control. My colleague and I will try to pursuit this avenue 🤞

@trygve
Copy link
Author

trygve commented Jul 17, 2024

Sounds reasonable.

My setup is however back to hci1. Seems like whenever I issue the "deploy key" command, this triggers the bug.
I immediately get these errors in HA log

2024-07-17 22:57:11.846 ERROR (MainThread) [habluetooth.scanner] hci0 (**************): Error stopping scanner: [org.freedesktop.DBus.Error.UnknownObject] Method "StopDiscovery" with signature "" on interface "org.bluez.Adapter1" doesn't exist

2024-07-17 22:57:16.865 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not determine the power state of the Bluetooth adapter hci0 [**************] due to timeout after 5 seconds
2024-07-17 22:57:16.869 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not cycle the Bluetooth adapter hci0 [**************]: [Errno 16] Resource busy
2024-07-17 22:57:16.869 WARNING (MainThread) [bluetooth_auto_recovery.recover] Bluetooth management socket connection lost: [Errno 22] Invalid argument
2024-07-17 22:57:21.870 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not reset the power state of the Bluetooth adapter hci0 [**************] due to timeout after 5 seconds
2024-07-17 22:57:23.893 WARNING (MainThread) [bluetooth_auto_recovery.recover] Closing Bluetooth adapter hci0 [**************] failed: [Errno 9] Bad file descriptor
2024-07-17 22:57:25.396 ERROR (MainThread) [habluetooth.scanner] hci0 (**************): Failed to restart Bluetooth scanner: hci0 (**************): Failed to start Bluetooth: adapter 'hci0' not found; Try power cycling the Bluetooth hardware.
Traceback (most recent call last):
  File "src/habluetooth/scanner.py", line 310, in habluetooth.scanner.HaScanner._async_start_attempt
  File "src/habluetooth/scanner.py", line 310, in habluetooth.scanner.HaScanner._async_start_attempt
  File "src/habluetooth/scanner.py", line 313, in habluetooth.scanner.HaScanner._async_start_attempt
  File "/usr/local/lib/python3.12/site-packages/bleak/__init__.py", line 203, in start
    await self._backend.start()
  File "/usr/local/lib/python3.12/site-packages/bleak/backends/bluezdbus/scanner.py", line 178, in start
    self._stop = await manager.passive_scan(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/bleak/backends/bluezdbus/manager.py", line 513, in passive_scan
    self._check_adapter(adapter_path)
  File "/usr/local/lib/python3.12/site-packages/bleak/backends/bluezdbus/manager.py", line 209, in _check_adapter
    raise BleakError(f"adapter '{adapter_path.split('/')[-1]}' not found")
bleak.exc.BleakError: adapter 'hci0' not found

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "src/habluetooth/scanner.py", line 509, in habluetooth.scanner.HaScanner._async_restart_scanner
  File "src/habluetooth/scanner.py", line 267, in _async_start
  File "src/habluetooth/scanner.py", line 354, in _async_start_attempt
habluetooth.scanner.ScannerStartError: hci0 (**************): Failed to start Bluetooth: adapter 'hci0' not found; Try power cycling the Bluetooth hardware.
2024-07-17 22:57:46.848 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not determine the power state of the Bluetooth adapter hci0 [**************] due to timeout after 5 seconds
2024-07-17 22:57:46.849 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not cycle the Bluetooth adapter hci0 [**************]: [Errno 16] Resource busy
2024-07-17 22:57:46.850 WARNING (MainThread) [bluetooth_auto_recovery.recover] Bluetooth management socket connection lost: [Errno 22] Invalid argument
2024-07-17 22:57:51.851 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not reset the power state of the Bluetooth adapter hci0 [**************] due to timeout after 5 seconds
2024-07-17 22:57:53.880 WARNING (MainThread) [bluetooth_auto_recovery.recover] Closing Bluetooth adapter hci0 [**************] failed: [Errno 9] Bad file descriptor
2024-07-17 22:57:55.454 ERROR (MainThread) [homeassistant] Error doing job: Fatal error: protocol.data_received() call failed. (None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/asyncio/selector_events.py", line 1017, in _read_ready__data_received
    self._protocol.data_received(data)
  File "/usr/local/lib/python3.12/site-packages/bluetooth_auto_recovery/recover.py", line 147, in data_received
    and (response := btmgmt_protocol.reader(data))
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/btsocket/btmgmt_protocol.py", line 1055, in reader
    cmd_params = event_frame.decode(evt_params)
                 ^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'decode'
2024-07-17 22:57:55.461 WARNING (MainThread) [bluetooth_auto_recovery.recover] Bluetooth management socket connection lost: 'NoneType' object has no attribute 'decode'
2024-07-17 22:58:00.453 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not reset the power state of the Bluetooth adapter hci0 [**************] due to timeout after 5 seconds
2024-07-17 22:58:00.956 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not cycle the Bluetooth adapter hci0 [**************]: [Errno 114] Operation already in progress
2024-07-17 22:58:00.956 ERROR (MainThread) [bluetooth_auto_recovery.recover] Could not reset the power state of the Bluetooth adapter hci0 [**************]
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/bluetooth_auto_recovery/recover.py", line 618, in _execute_reset
    return await _execute_power_on(adapter, name, power_state_before_reset)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/bluetooth_auto_recovery/recover.py", line 638, in _execute_power_on
    await adapter.set_powered(True)
  File "/usr/local/lib/python3.12/site-packages/bluetooth_auto_recovery/recover.py", line 295, in set_powered
    response = await self.protocol.send(
               ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/bluetooth_auto_recovery/recover.py", line 160, in send
    assert self.transport is not None  # nosec
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError
2024-07-17 22:58:02.980 WARNING (MainThread) [bluetooth_auto_recovery.recover] Closing Bluetooth adapter hci0 [**************] failed: [Errno 9] Bad file descriptor
2024-07-17 22:58:02.982 WARNING (MainThread) [bluetooth_auto_recovery.recover] Adapter with mac address ************** has moved to hci1
2024-07-17 22:58:04.484 ERROR (MainThread) [habluetooth.scanner] hci0 (**************): Failed to restart Bluetooth scanner: hci0 (**************): Failed to start Bluetooth: adapter 'hci0' not found; Try power cycling the Bluetooth hardware.
Traceback (most recent call last):
  File "src/habluetooth/scanner.py", line 310, in habluetooth.scanner.HaScanner._async_start_attempt
  File "src/habluetooth/scanner.py", line 310, in habluetooth.scanner.HaScanner._async_start_attempt
  File "src/habluetooth/scanner.py", line 313, in habluetooth.scanner.HaScanner._async_start_attempt
  File "/usr/local/lib/python3.12/site-packages/bleak/__init__.py", line 203, in start
    await self._backend.start()
  File "/usr/local/lib/python3.12/site-packages/bleak/backends/bluezdbus/scanner.py", line 178, in start
    self._stop = await manager.passive_scan(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/bleak/backends/bluezdbus/manager.py", line 513, in passive_scan
    self._check_adapter(adapter_path)
  File "/usr/local/lib/python3.12/site-packages/bleak/backends/bluezdbus/manager.py", line 209, in _check_adapter
    raise BleakError(f"adapter '{adapter_path.split('/')[-1]}' not found")
bleak.exc.BleakError: adapter 'hci0' not found

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "src/habluetooth/scanner.py", line 509, in habluetooth.scanner.HaScanner._async_restart_scanner
  File "src/habluetooth/scanner.py", line 267, in _async_start
  File "src/habluetooth/scanner.py", line 354, in _async_start_attempt
habluetooth.scanner.ScannerStartError: hci0 (**************): Failed to start Bluetooth: adapter 'hci0' not found; Try power cycling the Bluetooth hardware.
2024-07-17 22:58:11.847 WARNING (MainThread) [bluetooth_auto_recovery.recover] Adapter with mac address ************** has moved to hci1
2024-07-17 22:58:14.457 WARNING (MainThread) [bluetooth_auto_recovery.recover] Adapter with mac address ************** has moved to hci1

As a sidenote, it is enough to reboot HA from shell with "ha host reboot" to reset back to hci0. I dont have to reboot the VM hostsystem.
Not sure if this is helpful :)

@baylanger
Copy link
Collaborator

2024-07-17 22:57:16.865 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not determine the power state of the Bluetooth adapter hci0 [**************] due to timeout after 5 seconds
2024-07-17 22:57:16.869 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not cycle the Bluetooth adapter hci0 [**************]: [Errno 16] Resource busy
2024-07-17 22:57:16.869 WARNING (MainThread) [bluetooth_auto_recovery.recover] Bluetooth management socket connection lost: [Errno 22] Invalid argument
2024-07-17 22:57:21.870 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not reset the power state of the Bluetooth adapter hci0 [**************] due to timeout after 5 seconds

It looks like you have either iBeacon and/or bluetooth_le_tracker configured, is this true? It's hard to tell by the error, it shows "HaScanner" and there's no such integration by that name. It's possible HAScanner is a lower level service that iBeacon & le_tracker uses to access the BT adapter and thus, can manage to handle concurrent request to the adapter. If you do have eBeacon/le_tracker enable, perhaps you can disable and see if it works better. If it does, the solution might be to have a dedicated BT adapter for tesla-control and 1 for the HA BT tracking.

As a sidenote, it is enough to reboot HA from shell with "ha host reboot" to reset back to hci0. I dont have to reboot the VM hostsystem. Not sure if this is helpful :)

That's what I do as well. Something that might be faster; remove the BT adapter in the VM config and assign it back. What I tried before was to physically remove the BT adapter and plug it back but then it needs to be reassign it to the VM.

@Gates1234
Copy link

@trygve after a few hours of the integration running my BT drops off hci0 to hci1. I believe I have a similar wifi/BT chip to you and am running HASS on Proxmox (Lenovo M710q). Mine is 8087:0a2b.

Blacklisting btusb, bluetooth, btintel followed by "update-initramfs -u" on the host seems to extend the duration before it drops off hci0 to hci1, and I believe this is because the controller looks like it's disconnecting power momentarily sometimes while issuing commands and if it hits a power cycle at the wrong time enough times it will error out. I've ordered an external BT adaptor to try that out as there's countless threads spanning years discussing the intel BT+wifi chips being problematic on linux and HA. I am also experimenting with extending the duration between actions/commands issued from 5 seconds to 9 seconds and slowing down the frequency I send commands to the car over BLE as a interim solution.

My BT controller seems to be stable until I start issuing commands to the car, then it starts doing this:
image
image

Instead of looking like this when it's not issuing commands to the car:
image

Note that earlier in the day I had the host a lot closer to the car (RSSI ~-60) and these issues were present.

@raphmur
Copy link
Collaborator

raphmur commented Jul 19, 2024

Very interesting feedback, thanks. We are investigating this issue... But the device constantly switching is difficult to track and looking for the latest available device might not solve the issue by itself.

Few elements around though:

I had very similar issues with my RPi 4b with device turning off or becoming inaccessible. Two things helped:

  • Properly cooling the Wifi/BT chip. My previous case was good at passive cooling for CPU/RAM but not specifically on the BT chip. I traced it down to this sequence: car is a bit far > bluetooth increases power + commands fail due to distance > endless retries > chip overheats >chip disconnects
  • Update to 0.1.0 (but you done it) which is less brute force in the overall mqtt listening loop
    @trygve how close is your system to the car?

Home assistant community is recommending "high performance" BT chips:

  • Cambridge Silicon Radio CSR8510A10
  • Broadcom BCM20702A0/1
  • Cypress CYW43455 (Raspberry Pi3 or Pi4)
    @Gates1234 Did you order a chip of these specs? You can also use a USB extension cord to avoid interferences.

Reading again through issue 27, I realize these are all the errors we are seeing now. Short story: tesla_ble_mqtt v0.1.0 or above and efficient BT chip cooling...

@Gates1234
Copy link

Gates1234 commented Jul 19, 2024

I picked up a CSR based one (ASUS BT400) but it won't be here for a couple days.

I can adjust the bios on the computer to a more aggressive cooling mode, I'll give that a go - we're currently in a heat wave and ambient temps in the garage are ~23-27C.

Overnight while this was not issuing any commands it seems to have ran completely fine, and then as the sun began rising it started to have errors pop up:
image

Server started at 00:24 and ran without errors on hci0 until 05:39, where errors started popping up, at 06:28 it bumped to hcl1.
Sunrise, when the automation begins, is 5:36AM today.

2024-07-19 06:28:02.528 ERROR (MainThread) [habluetooth.scanner] hci0 (00:00:00:00:00:00): Error stopping scanner: [org.freedesktop.DBus.Error.UnknownObject] Method "StopDiscovery" with signature "" on interface "org.bluez.Adapter1" doesn't exist
2024-07-19 06:28:03.798 ERROR (MainThread) [homeassistant] Error doing job: Fatal error: protocol.data_received() call failed. (None)
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/asyncio/selector_events.py", line 1017, in _read_ready__data_received
    self._protocol.data_received(data)
  File "/usr/local/lib/python3.12/site-packages/bluetooth_auto_recovery/recover.py", line 147, in data_received
    and (response := btmgmt_protocol.reader(data))
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/btsocket/btmgmt_protocol.py", line 1055, in reader
    cmd_params = event_frame.decode(evt_params)
                 ^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'decode'
2024-07-19 06:28:03.799 WARNING (MainThread) [bluetooth_auto_recovery.recover] Bluetooth management socket connection lost: 'NoneType' object has no attribute 'decode'
2024-07-19 06:28:08.797 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not reset the power state of the Bluetooth adapter hci0 [00:00:00:00:00:00] due to timeout after 5 seconds
2024-07-19 06:28:08.798 WARNING (MainThread) [bluetooth_auto_recovery.recover] Could not cycle the Bluetooth adapter hci0 [00:00:00:00:00:00]: [Errno 16] Resource busy
2024-07-19 06:28:08.799 ERROR (MainThread) [bluetooth_auto_recovery.recover] Could not reset the power state of the Bluetooth adapter hci0 [00:00:00:00:00:00]
Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/bluetooth_auto_recovery/recover.py", line 618, in _execute_reset
    return await _execute_power_on(adapter, name, power_state_before_reset)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/bluetooth_auto_recovery/recover.py", line 638, in _execute_power_on
    await adapter.set_powered(True)
  File "/usr/local/lib/python3.12/site-packages/bluetooth_auto_recovery/recover.py", line 295, in set_powered
    response = await self.protocol.send(
               ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/bluetooth_auto_recovery/recover.py", line 160, in send
    assert self.transport is not None  # nosec
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError
2024-07-19 06:28:10.789 WARNING (MainThread) [bluetooth_auto_recovery.recover] Closing Bluetooth adapter hci0 [00:00:00:00:00:00] failed: [Errno 9] Bad file descriptor
2024-07-19 06:28:10.790 WARNING (MainThread) [bluetooth_auto_recovery.recover] Adapter with mac address 00:00:00:00:00:00 has moved to hci1
2024-07-19 06:28:12.293 ERROR (MainThread) [habluetooth.scanner] hci0 (00:00:00:00:00:00): Failed to restart Bluetooth scanner: hci0 (00:00:00:00:00:00): Failed to start Bluetooth: adapter 'hci0' not found; Try power cycling the Bluetooth hardware.

Here's the entire HA log.

2024-07-19 002400.681 WARNING (Sync.txt

Edit: After disabling wifi in the host (via rfkill block 0) and opening the computer case to let the BT/wifi module breathe a bit better this has been running flawlessly for about 7-8hours.

@PedroKTFC

This comment was marked as off-topic.

@baylanger
Copy link
Collaborator

@PedroKTFC Please continue conversation in #97

@SebastianGode
Copy link

Very interesting feedback, thanks. We are investigating this issue... But the device constantly switching is difficult to track and looking for the latest available device might not solve the issue by itself.

After rebooting the device is back to hci0 and it works flawlessly again, so nothing regarding to overheating (in my case).
Whatever is causing the rename in the system, just looking for the latest device might help in most cases. I'd suggest trying that.

@aalllop
Copy link

aalllop commented Aug 4, 2024

I have installed the integration with a Realtek RTL8761BU adapter. I could agregate the key to the car and it seems that all works correctly for a while. But suddenly it stops working and says "teslaCtrlSendCommand; Error: failed to find a BLE device: can't init hci: no devices available: (hci0: can't down device: no such device". The device is working on hci0 . Rebooting sometimes works and others not.

@iainbullock
Copy link
Collaborator

It looks like the device name for your BLE adapter is changing (probably from hci0 to hci1). Many people (including myself until I changed hardware) have experienced this issue. It seems to happen sometimes randomly or more likely when multiple commands are being sent in fairly quick succession. Whilst presence detection seems to continue working, it is not possible to send further commands when this happens. I found I needed to reboot to fix it which is not a satisfactory solution.

I was originally using a RPi1b with a third party USB BLE adapter. In the end I changed device to a RPi3b+ and the problem has gone away. Others have reported success with RPi4. I am running the docker version of this project, though I believe this problem occurs whichever version you are using

@aalllop
Copy link

aalllop commented Aug 7, 2024

I have installed the integration with a Realtek RTL8761BU adapter. I could agregate the key to the car and it seems that all works correctly for a while. But suddenly it stops working and says "teslaCtrlSendCommand; Error: failed to find a BLE device: can't init hci: no devices available: (hci0: can't down device: no such device". The device is working on hci0 . Rebooting sometimes works and others not.

I have changed the BT adapter. The new one is more simple and it is too on the HA tested devices list :
SABRENT USB Bluetooth 4.0 (BT-UB40)

Now the problems have disappeared. It seems that HA has problems with the drivers of Realtek RTL8761BU. So if you have problems like this change de BT USB adapter. I have buyed it on Amazon.

@iainbullock
Copy link
Collaborator

iainbullock commented Aug 8, 2024

I think it's a more general Linux driver issue rather than HA. I will check what BLE adapter driver was being used in my case when it didn't work well. Maybe it's a RTL8761BU

What kernel driver does the new device use?

@Genesisfm
Copy link

I have the same problem that the Bluetooth USB device is changing from HCI0 to HCI1 and i see the following errors in my HA log:
image
I think the device will change it's adres when there occures an error?

@iainbullock
Copy link
Collaborator

We don't know why this happens but it does for some bluetooth adapters. Only solution we know is to use a different bluetooth adatpter.

@aalllop please provide the URL for the 'HA tested devices list' that you used to find an adapter that worked for you

@Genesisfm
Copy link

@aalllop please provide the URL for the 'HA tested devices list' that you used to find an adapter that worked for you

Thx i already ordered an compatibel bt device yesterday 😑 i was to fast with giving a reaction on this topic. In 3 days i know the result 💪

@Genesisfm
Copy link

We don't know why this happens but it does for some bluetooth adapters. Only solution we know is to use a different bluetooth adatpter.

@aalllop please provide the URL for the 'HA tested devices list' that you used to find an adapter that worked for you
I tryed a new BLE adapter : Sabrent 4.0 and it works fine right now ! Thank you for your support!

@aalllop
Copy link

aalllop commented Aug 19, 2024

We don't know why this happens but it does for some bluetooth adapters. Only solution we know is to use a different bluetooth adatpter.

@aalllop please provide the URL for the 'HA tested devices list' that you used to find an adapter that worked for you

The list of Bluetooth adapters is on the HA webpage:
https://www.home-assistant.io/integrations/bluetooth/

@raphmur
Copy link
Collaborator

raphmur commented Aug 25, 2024

@Genesisfm any good news? :)

@aalllop
Copy link

aalllop commented Aug 27, 2024

I have the same problem that the Bluetooth USB device is changing from HCI0 to HCI1 and i see the following errors in my HA log: image I think the device will change it's adres when there occures an error?

I have tested this integration and I have discovered that this messages ocurred when there is problems to transmit BLE messages to the car. I have the BT dongle 5 meters away from the car but there is a wall between car and BT dongle. If I put some object like a box between the BT dongle and the car, that messages were showed on the HA console and the commands doesn't arrives to the car. So if there is problems with the BT signal you will have those messages on your system.

I have experienced another big problem... If the integration is not able to send messages to the car due to a BT problem, HA stops with a hardware error and you have to restart all .

So be carefull to have good signal between car and BT dongle to avoid problems.

@Genesisfm
Copy link

@Genesisfm any good news? :)

Yes it works with a new BT dongle, im using the Sabrent 4.0

@aalllop
Copy link

aalllop commented Aug 27, 2024

I still having this errors when I am charging the car
Screenshot_20240827_222856_Microsoft Remote Desktop

@iainbullock
Copy link
Collaborator

@aalllop I thought you had fixed it but it seems not unfortunately.

I did notice from your original image that you are running HA inside a Oracle Virtualbox virtual machine - is that right?

image

I'm not aware that this causes a problem, but it might be another factor affecting control of the bluetooth device which we know is fussy about hardware

@aalllop
Copy link

aalllop commented Aug 28, 2024

@aalllop I thought you had fixed it but it seems not unfortunately.

I did notice from your original image that you are running HA inside a Oracle Virtualbox virtual machine - is that right?

image

I'm not aware that this causes a problem, but it might be another factor affecting control of the bluetooth device which we know is fussy about hardware

You are right... I'm using Oracle Virtual Box. The integration works with my BT device but sometimes is working well and sometime it fails . If there is too much fails then HA broke and I have to reset all HA.

I think I will try to use another usb bt dongle. Is not possible to use a BT proxy with this integration? I have tried Shelly 1 Plus who has BT proxy integrated but this integration says that no BT device is installed.

@iainbullock
Copy link
Collaborator

I am using a RPi3b+ which runs the docker version of this project (and nothing else). Home Assistant runs on another device. Works without issues. There are people who are using RPi4 successfully with this add-on version.

https://github.com/tesla-local-control/tesla_ble_mqtt_docker

@Genesisfm
Copy link

@aalllop I thought you had fixed it but it seems not unfortunately.
I did notice from your original image that you are running HA inside a Oracle Virtualbox virtual machine - is that right?
image
I'm not aware that this causes a problem, but it might be another factor affecting control of the bluetooth device which we know is fussy about hardware

You are right... I'm using Oracle Virtual Box. The integration works with my BT device but sometimes is working well and sometime it fails . If there is too much fails then HA broke and I have to reset all HA.

I think I will try to use another usb bt dongle. Is not possible to use a BT proxy with this integration? I have tried Shelly 1 Plus who has BT proxy integrated but this integration says that no BT device is installed.

I'm using proxmox with any "hang" issues, maybe you have a problem with a "hardware" setting in the Oracle Virtual box ?

@Gates1234
Copy link

Gates1234 commented Sep 9, 2024

So, over the past few weeks, I've tried 4 different BT devices with varying durations between failure (when it falls off hci0). Timespan ran from anywhere between seconds and 12 hours, none of the adaptos really stood out as better than the others (the BRCM one is the worst).
image

I've gone ahead and transferred my HA to HAOS on bare metal as Generic x86-64 (computer is a Lenovo M710q) rather than as a VM through proxmox (linux). I do not have much run time to say for certain this has resolved all issues for me, but the current adaptor I am using right now was struggling to work for longer than a few minutes on the VM/Proxmox setup and has been stable for the past few hours. When the car is awake, it seems to be issuing commands on first try consistently with about a 4 second delay between input and command receive confirmation from the car. When the car is asleep, the command never succeeds.
image

Something to consider would be issuing a "wake command" after 4-5 failed attempts and then retry the requested command a final time (or make something like this an opt in configuration option). I am ignorant to how hard it would be to implement something like this, just a suggestion or observation.

I will follow up in a few days after I have more runtime w/ HAOS on bare metal.

Thanks for all your work on this integration and add-on!

@iainbullock
Copy link
Collaborator

Thanks for sharing your experience, it sounds like it is now working for you.

Regarding having the code send a wake command if the required command fails; I have had several requests for this on the https://github.com/tesla-local-control/tesla_ble_mqtt_docker project. I agree it would be useful as it avoids having to add code in HA automations (several times in my case). I'd probably send a wake after the first failure of this type, as it will have the required effect more quickly and not work the BLE more than necessary. Also make it selectable in the config as some users might not want it.

@baylanger @raphmur what do you think - shall we look at implementing this for v0.2.2?

@raphmur
Copy link
Collaborator

raphmur commented Sep 9, 2024

@iainbullock could be nice yes.

@iainbullock
Copy link
Collaborator

OK I think we can close this issue. Let's have the conversation about how best to implement in the projects section

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

9 participants