tesla-local-control / tesla_ble_mqtt_docker

Apache License 2.0
21 stars 8 forks source link

Create Add-on from tesla_ble_mqtt_docker #10

Closed BogdanDIA closed 2 months ago

BogdanDIA commented 2 months ago

It will be very useful to run tesla_ble_mqtt_docker as an addon so that it will work with the BLE from the physical machine HA runs on, e.g. from RPI.

In the first place it will help those who have the car closer to the physical machine so no other physical machine will be needed.

On the second place, the solution could work on long term together with a proper BLE proxy capable of sending/receiving (maybe an ESP based) so this will extend the range while keeping the private key on HA machine, hence having very good security.

iainbullock commented 2 months ago

If you are running HA in a docker it will already work if you run this container on the same host. I have that setup working for my dev testing.

I appreciate some will not want to run HA in a docker. It could my made to work as a HA addon for sure, though I might let someone else take on that challenge :)

raphmur commented 2 months ago

Hi there I planned to have a look at this in the next days :) To build it up as an extension... But when I tried, the tesla-control command could not use the bluetooth. I will deep dive a bit more...

iainbullock commented 2 months ago

When looking how to do it in a docker I found that you have to run the container in priviledged mode and for some inexplicable reason it has to use the host network. It also needs /run/dbus mapping from host to container.

I have little experience regarding HA add-ons however I believe they use docker 'under the hood', so probably the same issues arise

BogdanDIA commented 2 months ago

If you are running HA in a docker it will already work if you run this container on the same host. I have that setup working for my dev testing.

I appreciate some will not want to run HA in a docker. It could my made to work as a HA addon for sure, though I might let someone else take on that challenge :)

I know it will work on docker on the same host but I run a supervised HA since 2017, just changed rpi3 to rp4 some years ago and all hassle with the upgrades :)

BogdanDIA commented 2 months ago

TBH, it can be an integration as well instead of an add-on. There are several BLE integrations that work so API seems to have BLE.

iainbullock commented 2 months ago

It would be good if all these related projects could be made into a single integration where the choise of http proxy or BLE happens behind the scenes. Too big a task for me I'm afraid

raphmur commented 2 months ago

Yes indeed, but going step by step makes sense. Tesla has made major changes in their API that interferes a lot with how we use the connection with the car... So far I see:

Tesla Custom Integration

Tesla HTTP Proxy Add-on

Tesla BLE MQTT docker

Tesla Local Command Integration --> To be built

Then I believe we will need to have a common discussion with contributors of Tesla Custom Integration to implement the commands via BLE by fostering the best practices. Since we still cannot get sensor or entities states with BLE, we will still need the FleetAPI interface... zlymeda managed to "hack" the Tesla HTTP Proxy Add-on to include BLE calls before trying API calls, but it should be better integrated indeed.

One stupid example: you call trunk-open you need to know if it effectively opened... @iainbullock @BogdanDIA @MrBLJ from what you have seen, do you consider that an return code 0 means the command is effectively successful? That case we can assume that the command was successful and force update the entity state...

iainbullock commented 2 months ago

Agreed it is a very dynamic situation but good that people are responding to provide solutions. It is a shame BLE only seems to send commands. If it also read status we would know if for example the trunk actually opened.

BogdanDIA commented 2 months ago

Zero return can be considered the command has been received correctly. But the car SW uses the existing senors to check that the trunk is actually opened. We are missing that through BLE. Updating over FleetAPI every time will reach the rate limitation.

I am curious where tesla goes with BLE API. I think it is good idea to communicate directly with the car. The phone app sends commands too to the car through BLE when is does not have internet. So I think Tesla will want to expand on BLE unless they want more money :)

MrBLJ commented 2 months ago

Since we still cannot get sensor or entities states with BLE

I realized that on my watch, I'm using an app that doesn't need my phone, an internet connection or whatever to get the status of the car. It's stated in the FAQ :

What can Watchla do with Bluetooth? Over Bluetooth, Watchla can: • send commands to your vehicle • receive vehicle status updates

Some unless this is poorly written, they've found a way to get the car data via Bluetooth. Reading a bit more here and there, there are mentions of the possibility of receiving data from the vehicle via bluetooth (note that there's also mention of waking the car via BlueTooth).

I think we should dig further before anything else. Note that I'm in no way capable of understanding everything that's at stake here, so take all of this with a grain of salt.

iainbullock commented 2 months ago

Issuing tesla-control --help gives the following.

Question what do

get post product-info session-info

Maybe they return some data?

Sorry about formatting I'm on my phone!

Usage: tesla-control [OPTION...] COMMAND [ARG...]

Run tesla-control help COMMAND for more information. Valid COMMANDs are listed below.

Available OPTIONs: -ble Force BLE connection even if OAuth environment variables are defined -command-timeout duration Set timeout for commands sent to the vehicle. (default 5s) -connect-timeout duration Set timeout for establishing initial connection. (default 20s) -debug Enable verbose debugging messages -domain value Domains to connect to (can be repeated; omit for all) -key-file file A file containing private key. Defaults to $TESLA_KEY_FILE. -key-name name System keyring name for private key. Defaults to $TESLA_KEY_NAME. -keyring-debug Enable keyring debug logging -keyring-file-dir directory keyring directory for file-backed keyring types (default "~/.tesla_keys") -keyring-type type Keyring type (file|keyctl|pass). Defaults to $TESLA_KEYRING_TYPE. -session-cache file Load session info cache from file. Defaults to $TESLA_CACHE_FILE. -token-file File File containing OAuth token. Defaults to $TESLA_TOKEN_FILE. -token-name name System keyring name for OAuth token. Defaults to $TESLA_TOKEN_NAME. -vin string Vehicle Identification Number. Defaults to $TESLA_VIN.

Available COMMANDs: add-key Add PUBLIC_KEY to vehicle whitelist with ROLE and FORM_FACTOR add-key-request Request NFC-card approval for a enrolling PUBLIC_KEY with ROLE and FORM_FACTOR auto-seat-and-climate Turn on automatic seat heating and HVAC autosecure-modelx Close falcon-wing doors and lock vehicle. Model X only. charge-port-close Close charge port charge-port-open Open charge port charging-schedule Schedule charging to MINS minutes after midnight and enable daily scheduling charging-schedule-cancel Cancel scheduled charge start charging-set-amps Set charge current to AMPS charging-set-limit Set charge limit to PERCENT charging-start Start charging charging-stop Stop charging climate-off Turn off climate control climate-on Turn on climate control climate-set-temp Set temperature (Celsius) drive Remote start vehicle flash-lights Flash lights frunk-open Open vehicle frunk. Note that there's no frunk-close command! get GET an owner API http ENDPOINT. Hostname will be taken from -config. honk Honk horn list-keys List public keys enrolled on vehicle lock Lock vehicle media-set-volume Set volume media-toggle-playback Toggle between play/pause ping Ping vehicle post POST to ENDPOINT the contents of FILE. Hostname will be taken from -config. product-info Print JSON product info remove-key Remove PUBLIC_KEY from vehicle whitelist rename-key Change the human-readable metadata of PUBLIC_KEY to NAME, MODEL, KIND seat-heater Set seat heater at POSITION to LEVEL sentry-mode Set sentry mode to STATE ('on' or 'off') session-info Retrieve session info for PUBLIC_KEY from DOMAIN software-update-cancel Cancel a pending software update software-update-start Start software update after DELAY steering-wheel-heater Set steering wheel mode to STATE ('on' or 'off') tonneau-close Close Cybertruck tonneau. tonneau-open Open Cybertruck tonneau. tonneau-stop Stop moving Cybertruck tonneau. trunk-close Closes vehicle trunk. Only available on certain vehicle types. trunk-move Toggle trunk open/closed. Closing is only available on certain vehicle types. trunk-open Open vehicle trunk. Note that trunk-close only works on certain vehicle types. unlock Unlock vehicle wake Wake up vehicle windows-close Close all windows windows-vent Vent all windows I see there is now a wake comman

BogdanDIA commented 2 months ago

I looked few months back at get and post hoping they'll be for BLE. However, they are for FleetAPI over internet. tesla-control can communicate both over internet and ble accoding to the documentation.

I assume eventually teslajsonpy will be replaced with the FleetAPI library/tool (e.g. tesla-control or other software based on the FleetAPI provided now in golang) that unifies the BLE and http access to the car. Seems this kind of dual access is preferred by Tesla.

raphmur commented 2 months ago

@BogdanDIA I am not sure this is that easy. To my understanding, the API calls are the same as before. The Fleet API implements two ways asymmetric encryption when the old API was only one way encrypted (as I understand). teslajsonpy is a python wrapper to send API calls for each "command". The role of the proxy embedded in Tesla SDK is to enable this encryption, but the API calls remain the same. The Tesla HTTP Proxy Addon acts as a "man in the middle" between teslajsonpy and Tesla servers.

Now with the Tesla SDK, in fact, we would need to:

Essentially, that means rewriting the backend of Tesla Custom Integration to merge teslajsonpy with a new local Tesla which uses directly the tesla-control commands.

Quite some work to do...

raphmur commented 2 months ago

Today it is teslajsonpydoing all the hard work of the Tesla Custom Integration...

BogdanDIA commented 2 months ago

I know how all works as one year ago I chased and fixed a bug in Tesla integration/teslajsonpy, a bug that was making people going back several versions. Oh my, debugging the teslajsonpy was not easy as it is placed in homeassistant container that loses changes after each restart.

I did not say this is easy :) What I envision not immediately but on long term, part of teslajsonpy going to Tesla integration and other part of it going to tesla-control. BTW, tesla-control is just an example of implementation created by tesla to show the vehicle commands but it can be any other implementation done with the existing API. I actually don't consider being a good implementation this parameterized executable style communication that tesla-control is. A better approach would be a library that can be included in other projects needing to use it.

But as you said, it is a lot of work

raphmur commented 2 months ago

I just created an HA add-on which is 99% same code as Iain's code. It works until effectively sending a command: Error: failed to find a BLE device: can't init hci: can't create socket: address family not supported by protocol So, I am stuck on allowing access to local bluetooth device from the RPi... To be continued in the weekend...

iainbullock commented 2 months ago

@raphmur you might have already done this, but can you run bluetoothctl from the HA instance?

BogdanDIA commented 2 months ago

I checked on how add-ons and integrations are showing in HA in my supervised install. So each add-on has it's own container whereas all integrations are mostly python packages inside one single container. Going to look when have time on how a bluetooth integration is implemented. Can someone point to an bluetooth ad-on if there is one?

MrBLJ commented 2 months ago

Can someone point to an bluetooth ad-on if there is one?

looks like this is one

raphmur commented 2 months ago

Had same Idea but dis not find any relevant. Thanks for that! It looks like host_dbus: true migth be the thing

raphmur commented 2 months ago

And yes, I went through integration tutorial, but not adapted as it is python only. We could maybe create a python lib which wraps the vehicle-command client tools... Maybe...

iainbullock commented 2 months ago

Had same Idea but dis not find any relevant. Thanks for that!

It looks like host_dbus: true migth be the thing

I'm sure you need to map /run/dbus from host to container if that's what host_dbus: true is doing

raphmur commented 2 months ago

Alleluia! It works. I will upload today at kid's nap...

Short story: you need to pass quite some permissions to the container...

@iainbullock I will prepare a pull request to propose both availabilities (standalone or add-on) in your repo.

BogdanDIA commented 2 months ago

Wow, nice!

MrBLJ commented 2 months ago

Alleluia! It works. I will upload today at kid's nap...

Short story: you need to pass quite some permissions to the container...

@iainbullock I will prepare a pull request to propose both availabilities (standalone or add-on) in your repo.

This is a very good news ! Now that I think of it, don’t we have some kind of way to use an esp32 as a Bluetooth « relay » (might be poor wording here) to extend the range of Bluetooth from the device that runs HA ?

let’s say I have HA running on a NUC in my attic, can I used an esp32 in the basement to receive and relay commands to the server ?

raphmur commented 2 months ago

I see two options You can use a cheap second hand RPi as we do now, or an ESP32 with espHome bluetooth proxy. I have read quickly but did not try any implementation. I think this will be difficult because i don't see how the espHome integration could "mimick" a bluetooth hci interface...

MrBLJ commented 2 months ago

I see two options You can use a cheap second hand RPi as we do now, or an ESP32 with espHome bluetooth proxy. I have read quickly but did not try any implementation. I think this will be difficult because i don't see how the espHome integration could "mimick" a bluetooth hci interface...

I'll order an esp32 and see if I can get it running as a proxy.

BogdanDIA commented 2 months ago

I've been trying to understand the low level details of ble proxy and how it interacts with HA but so far I've got only high level details from my searches. Everybody tells basic things, if an integration exists in HA for a BT device, the BT proxy will emulate it so that the integration will find a BT device. At which level it emulates, it is unclear to me now.

The emulation can be done in many ways, this is just two of them:

  1. can be something like USBIP implementation which allows mimicking an USB controller on a machine based on existing controller on another machine. And this is done over IP. I used it and it works great for any kind of controller but it needs a kernel module to be installed and a user space app. So at this point I doubt something like USBIP is used. Can be a variation of it though.
  2. At the HA side the emulation is done at the dbus level where bluez communicates. That would be simpler and not require going in kernel space.

Tonight I'll search in my boxes to see if I can find an ESP32 compatible with BT proxy to play with it.

raphmur commented 2 months ago

Well, here it is: https://github.com/raphmur/tesla-local-control-addon

@iainbullock I created a separate repo with the structure for an HA addon. I copied the structure from https://github.com/llamafilm/tesla-http-proxy-addon. I suggest to wait for your return from vacation to merge both repos in one.

I took the latest code from release v1.0.14, so not including the BLE surveillance.

Main changes vs. tesla_ble_mqtt_docker are:

This is a quick & dirty job to make this work as an HA add-on. Note that the key parameters to pass the right to use the BLE controller are: host_network: true privileged: [NET_ADMIN] ... which gives the addon a fairly low security score.

Note2: NET_ADMIN is required otherwise I have to call sudo setcap 'cap_net_admin=eip' "$(which tesla-control)"

For me it works

image

MrBLJ commented 2 months ago

I suggest to wait for your return from vacation to merge both repos in one.

+1 to this, consolidating both repos would prevent users from getting lost.

Is there a way to move the key generated for the docker version to be used with the addon ?

iainbullock commented 2 months ago

Yes let's do it when I'm back. Thanks for your work on this

BogdanDIA commented 2 months ago

Continuing on the proxy, I installed the BT proxy on a ESP32. As I did not have one BT device that has a HA integration available, I used iBeacon integration. I did try using iBeacon integration few months back to detect the car presence but it was nvery slow in detection home/away so I gave up on it. Anyway, just for testing the BT proxy it was fine and I could see it picking the iBeacon signal from the car when ESP32 was closer. This can be seen only in the HA logs:

2024-06-16 08:41:23.273 DEBUG (MainThread) [aioesphomeapi.connection] esp32-bluetooth-proxy-368d90 @ 192.168.0.140: Got message of type BluetoothLERawAdvertisementsResponse: advertisements { address: 127847000284145 rssi: -60 data: "xxx-yyy-S1122334455667788C" <- this ID(not the real one here) starting with S and ending with C identifies a Tesla car }

Going further I was interested in understanding how BT work in HA so I did some digging in the HA sources. Short version is that a regular HA BT integration does not access directly the HCI but it uses another HA integration named Bluetooth which in turn use adapters for the various BT sources like the local HCIs or remote HCIs (through a BT proxy).

So a HA BT integration deals only with GATT server/client communication using bleak library. That makes it simple to write apparently but probably has a lot of unknown catches. Checked the exphome sources as well to understand the whole architecture. BTW, the Bluetooth integration does seamless switching between adapters for maintaining the communication with the device and that is a very nice feature.

As a conclusion, the BT proxy cannot be used directly with Tesla BLE unless an integration is written to adapt the HA BT API to Tesla BLE golang library. In my view, the Tesla golang BLE library should be replaced completely with a wrapper library for HA BT API.

I did not check if the same HA API is available for add-ons.

Will test the add-on @raphmur created tonight.

raphmur commented 2 months ago

Updated the addon with latest entities from this repo. Also managed to get the proximity sensor work directly on the HA host. I added quite some "how to", if you need id. To get the car MAC address, I use Android BLE Scanner

However the frequency of the BLE scanner should be set as a parameter, independently of the mqtt loop?

raphmur commented 2 months ago

I get this...

2024-06-16 15:26:09.736 ERROR (MainThread) [asyncio] Task exception was never retrieved
future: <Task finished name='Task-803891' coro=<Addon.watchdog_container() done, defined at /usr/src/supervisor/supervisor/addons/addon.py:1429> exception=AddonsJobError('Rate limit exceeded, more than 10 calls in 0:30:00')>
Traceback (most recent call last):
  File "/usr/src/supervisor/supervisor/addons/addon.py", line 1443, in watchdog_container
    await self._restart_after_problem(event.state)
  File "/usr/src/supervisor/supervisor/jobs/decorator.py", line 290, in wrapper
    raise on_condition(
supervisor.exceptions.AddonsJobError: Rate limit exceeded, more than 10 calls in 0:30:00

Anyway. I propose to manage this when we merge the repos

iainbullock commented 2 months ago

Thanks for all this. It might take me a while to catch up with you. Getting some disapproving looks from my partner LOL...

raphmur commented 2 months ago

it may be good to setup a call or chat or whatever better that writing in issues ;)

iainbullock commented 2 months ago

Yeah we could do a Teams call or similar, but it will have to be when I get back from holiday. Keep sending improvements in the meantime thanks

BogdanDIA commented 2 months ago

Updated the addon with latest entities from this repo. Also managed to get the proximity sensor work directly on the HA host. I added quite some "how to", if you need id. To get the car MAC address, I use Android BLE Scanner

However the frequency of the BLE scanner should be set as a parameter, independently of the mqtt loop?

You mean the BLE scanner from HA (bluetooth_le_tracker), the one that you configure directly in configuration.yaml? I have that but it won't help in using the Tesla BLE. Or you did some magic :) ?

The car's BLE MAC can be easily found with bluetoothctl or hcitool on any linux machine including the one running the HA (just ssh to the HA host and the commands are available). The help here is car's MAC is not randomized and once you get it it will be the same forever.

Will check tonight your repo and install the add-on.

raphmur commented 2 months ago

@BogdanDIA no i meant an Android app. The idea behind it toward the HA integration is to not have to send a command... I use this https://play.google.com/store/apps/details?id=com.macdom.ble.blescanner

By frequency i meant the call for "listen_to_ble" in the while loop

iainbullock commented 2 months ago

I think it can be partially calculated from the VIN and then scanned automatically via bluetoothctl. I will look at this when I get chance

On Sun, 16 Jun 2024 at 19:58, Raphael Murray @.***> wrote:

@BogdanDIA https://github.com/BogdanDIA no i meant an Android app. The idea behind it toward the HA integration is to not have to send a command... I use this https://play.google.com/store/apps/details?id=com.macdom.ble.blescanner

By frequency i meant the call for "listen_to_ble" in the while loop

— Reply to this email directly, view it on GitHub https://github.com/iainbullock/tesla_ble_mqtt_docker/issues/10#issuecomment-2171790588, or unsubscribe https://github.com/notifications/unsubscribe-auth/AODIAOOD2OIONJ4J2LH5TPLZHXG4FAVCNFSM6AAAAABJKI62ICVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCNZRG44TANJYHA . You are receiving this because you were mentioned.Message ID: @.***>

BogdanDIA commented 2 months ago

@BogdanDIA no i meant an Android app. The idea behind it toward the HA integration is to not have to send a command... I use this https://play.google.com/store/apps/details?id=com.macdom.ble.blescanner

By frequency i meant the call for "listen_to_ble" in the while loop

There is a bunch of apps to listen to BLE and resolve the services. On iPhone I am using nRF Connect.

However, better to do it automatically by scanning with bluetoothctl and grepping for car's BLE name. The BLE name will also get to HA through BLE proxy as I wrote in a post above.

Now, the BLE name is created from first(LSB) 6 bytes of the VIN and then taken through SHA1. Then added S in front and C on the back. I've used this script a year ago, pasting it here:

from cryptography.hazmat.primitives import hashes
vin = bytes("XP711223344556677", "UTF8")
digest = hashes.Hash(hashes.SHA1())
digest.update(vin)
vinSHA = digest.finalize().hex()
middleSection = vinSHA[0:16]
bleName = "S" + middleSection + "C"
print(bleName)

This will help the user to get the BLE MAC with a touch of a button.

And there is more to it. If in bluetoothctl you connect to a Tesla car using it's MAC (connect $MAC_ADDR), you will get the name of the car as it is shown on the tablet and the Tesla app. Funny, huh? Many consider this a security hole but anyhow it has been like that since day one. Though it does not work all the time from the first try.

iainbullock commented 2 months ago

However the frequency of the BLE scanner should be set as a parameter, independently of the mqtt loop?

I originally thought it best to have the BLE scan and the MQTT subsciption in a single thread / process so that there wouldn't be read and write to the bluetooth at the same same. This is the reason I used the -E -c options (so called durable client session) for mosquitto_sub (see https://mosquitto.org/man/mosquitto_sub-1.html ).

However for this is work the qos for messages send by HA needs to be >=1.

That's fine for the HA entities as the qos can be specified by auto-discovery. However it doesn't work for the 'Birth' message sent when HA restarts (which is needed to prevent the entities staying unavailable after a HA restart). This is because HA sends the Birth message as qos=0 which can't be changed.

So I'm thinking maybe the BLE scan and MQTT loop should be in separate processes after all. This makes it possible to set the frequency of the BLE scan to be independent of the MQTT loop. There will be times when the processes read and write at the same time, but probably infrequent.

What do you think?

raphmur commented 2 months ago

I just did a quick and dirty fix. In HA, your are kicked (or blamed) if you spam the BLE discovery more than 10 times in 30 min.

The loop runs with sleep 2. So I just added a counter that runs the BLE discovery every 90 loops = 180 sec = 3 min... So far it works...

I agree, it could be better to spam 2 independent processes, different periodicity, with probably a random time shift to prevent collisions. Anyways, if it collides, it will cycle again next loop...

BogdanDIA commented 2 months ago

Adding the script that I'm using for Car's MAC detection. It surely needs some improvement. Do change the BLE name with your car's one:

#!/bin/bash

echo Start MAC finding
BLE_LOCAL_NAME=S1122334455667788C

# print BLE Local Name for which we want the MAC
echo BLE_LOCAL_NAME: $BLE_LOCAL_NAME

# scan and store the list of found MACs, list is provided after timeout
bluetoothctl --timeout 30 scan on | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}' > scan-macs.txt

# print the list of MACs we found
echo Found MACS:
cat scan-macs.txt

# start scan again in another process so we can get the detailed info for each MAC
bluetoothctl --timeout 30 scan on > /dev/zero &

#xargs -0 -n 1 bluetoothctl info  < <(tr \\n \\0 <scan-macs.txt) | grep "Name: $BLE_LOCAL_NAME"

# cycle through all scanned MACs to find our MAC
cat scan-macs.txt |
while read mac; do
        INFO=$(bluetoothctl --timeout 1 info $mac)
        #echo INFO: "$INFO"
        INFONAME=$(echo "$INFO" | grep "Name: $BLE_LOCAL_NAME")
        #echo INFONAME: "$INFONAME"

        if [[ -n $INFONAME ]]; then
                echo Matched car\'s MAC:
                echo $mac > mac.txt
                INFORSSI=$(echo "$INFO" | grep "RSSI: ")
                echo "$mac"
                echo "$INFONAME"
                echo "$INFORSSI"
        fi
done

echo End MAC finding

The output should be like the following:

Start MAC finding BLE_LOCAL_NAME: S1122334455667788C Found MACS: D8:3A:DD:C2:67:D7 B4:60:77:5C:6E:6B 11:22:33:44:55:66 58:00:E3:E7:80:BA Matched car's MAC: 11:22:33:44:55:66 Name: S1122334455667788C RSSI: -81 End MAC finding

raphmur commented 2 months ago

Nice work.

You confirm that you can derive the SxxxxC from the VIN? If yes, I suggest to run this script at the docker container startup maybe... Or after the first successful MQTT message? Then this MAC is stored as a variable...

@iainbullock ?

iainbullock commented 2 months ago

Yes this is good. I was thinking of running this as a user intitiated phase of the container. Maybe a button press, like Generate / Deploy Key, then store the results somewhere persistent. The car has to be present so just doing everytime the container starts won't always work.

If BLE_LOCAL_NAME appears during scans more regularly than I originally thought maybe we don't need MAC and we just scan for BLE_LOCAL_NAME. I will catch up with the BLE conversations when I get back from holidays, as I need my car to be present to test

BogdanDIA commented 2 months ago

Nice work.

You confirm that you can derive the SxxxxC from the VIN? If yes, I suggest to run this script at the docker container startup maybe... Or after the first successful MQTT message? Then this MAC is stored as a variable...

@iainbullock ?

Yes, it works so the LNAME is not necessary to be input by the user, only the VIN.

BogdanDIA commented 2 months ago

Yes this is good. I was thinking of running this as a user intitiated phase of the container. Maybe a button press, like Generate / Deploy Key, then store the results somewhere persistent. The car has to be present so just doing everytime the container starts won't always work.

If BLE_LOCAL_NAME appears during scans more regularly than I originally thought maybe we don't need MAC and we just scan for BLE_LOCAL_NAME. I will catch up with the BLE conversations when I get back from holidays, as I need my car to be present to test

For me it should be fine to have a mqtt button to obtain the MAC. Just tell the user to do this when the car is close. As for RSSI, it should be sent every time when the CAR presence is checked.

BogdanDIA commented 2 months ago

As I'm going off for few days, I paste here the latest RSSI detection script I have. It is important to have a view of the CAR closeness given by RSSI. An approximate distance can be calculated (have it done already in an ESP) but adding a wall between will make distance being higher and thus misleading.

 #!/bin/bash
# BogdanDIA

echo Start RSSI detection

# print BLE Local Name for which we want the MAC
BLE_LOCAL_NAME=S1122334455667788C
echo BLE_LOCAL_NAME: $BLE_LOCAL_NAME

# timeouts et all
DEVICES_TIMEOUT=5
LOOP_COUNT=6
SCAN_TIMEOUT=$((DEVICES_TIMEOUT*$LOOP_COUNT+2))

echo DEVICES_TIMEOUT: $DEVICES_TIMEOUT
echo LOOP_COUNT: $LOOP_COUNT
echo SCAN_TIMEOUT: "$SCAN_TIMEOUT"

# start scan
bluetoothctl --timeout "$SCAN_TIMEOUT" scan on > /dev/zero &

INFOMAC=""
INFORSSI=""
for (( i=0; i<$LOOP_COUNT; i++ ))
do
        DEVICES=$(bluetoothctl --timeout "$DEVICES_TIMEOUT" devices | grep "$BLE_LOCAL_NAME")
        echo Loop: $i, DEVICES: "$DEVICES"

        if [[ -n "$DEVICES" ]]; then
                echo Loop: $i, Matched car\'s BLE name

                INFOMAC=$(echo "$DEVICES" | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}')
                echo Loop: $i, INFOMAC: "$INFOMAC"

                INFORSSI=$(bluetoothctl --timeout 1 info "$INFOMAC" | grep RSSI)
                if [[ -n "$INFORSSI" ]]; then
                        break;
                fi
        fi
done

echo MAC: "$INFOMAC"
echo RSSI: "$INFORSSI"

echo End RSSI detection
iainbullock commented 2 months ago

The latest and probably final update has been released today in the main branch (v.1.1.2). It provides multi-car support (for commands, but not BLE presence), various bug fixes, and enhancements suggested by users.

The project is being migrated to a new one which has three developers (including me). With three of us working on it, we expect to improve functionality, quality, and responsiveness to issues. Check it out at https://github.com/tesla-local-control/tesla-local-control-addon

I will keep this project open until the first release at the new repository.

If your Issue remains unresolved by this release, please review existing Issues at the new repo, and open a new Issue there if required.

I will close the Issue here as the repo will soon be archived.

Thanks a lot for your input and support on this project.