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

Add cache control configuration and initialization #81

Merged
merged 4 commits into from
Jan 12, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 14 additions & 49 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ services:
tesla-ble-http-proxy:
image: wimaha/tesla-ble-http-proxy
container_name: tesla-ble-http-proxy
environment:
- cacheMaxAge=30 # Optional, but recommended to set this to anything more than 0 if you are using the vehicle data
volumes:
- ~/TeslaBleHttpProxy/key:/key
- /var/run/dbus:/var/run/dbus
Expand All @@ -44,6 +46,8 @@ Please remember to create an empty folder where the keys can be stored later. In

Pull and start TeslaBleHttpProxy with `docker compose up -d`.

Note that you can optionally set environment variables to override the default behavior. See [environment variables](docs/environment_variables.md) for more information.

### Build yourself

Download the code and save it in a folder named 'TeslaBleHttpProxy'. From there, you can easily compile the program.
Expand All @@ -55,6 +59,8 @@ go build .

Please remember to create an empty folder called `key` where the keys can be stored later.

Note that you can optionally set environment variables to override the default behavior. See [environment variables](docs/environment_variables.md) for more information.

## Generate key for vehicle

*(Here, the simple, automatic method is described. Besides the automatic method, you can also generate the keys [manually](docs/manually_gen_key.md).)*
Expand All @@ -79,59 +85,18 @@ You can now close the dashboard and use the proxy. 🙂

## Setup EVCC

If you want to use solely TeslaBleHttpProxy, you can use the following configuration in evcc (recommended):
You can use the following configuration in evcc (recommended):

```
vehicles:
- name: tesla
type: custom
title: Your Tesla
icon: car
capacity: 60
chargeenable:
source: http
uri: "http://IP:8080/api/1/vehicles/VIN/command/{{if .chargeenable}}charge_start{{else}}charge_stop{{end}}"
method: POST
body: ""
maxcurrent: # set charger max current (A)
source: http
uri: http://IP:8080/api/1/vehicles/VIN/command/set_charging_amps
method: POST
body: '{"charging_amps": "{{.maxcurrent}}"}'
wakeup: # vehicle wake up command
source: http
uri: http://IP:8080/api/1/vehicles/VIN/command/wake_up
method: POST
body: ""
soc:
source: http
uri: http://IP:8080/api/1/vehicles/VIN/vehicle_data?endpoints=charge_state
method: GET
jq: .response.response.charge_state.battery_level
timeout: 30s
limitsoc:
source: http
uri: http://IP:8080/api/1/vehicles/VIN/vehicle_data?endpoints=charge_state
method: GET
jq: .response.response.charge_state.charge_limit_soc
timeout: 30s
range:
source: http
uri: http://IP:8080/api/1/vehicles/VIN/vehicle_data?endpoints=charge_state
method: GET
jq: .response.response.charge_state.battery_range
scale: 1.60934
timeout: 30s
status:
source: http
uri: http://IP:8080/api/1/vehicles/VIN/vehicle_data?endpoints=charge_state
method: GET
jq: (if (.response.response.charge_state.charging_state == "Charging") then "C"
elif (.response.response.charge_state.charging_state == "Stopped") then "B"
elif (.response.response.charge_state.charging_state == "NoPower") then "B"
elif (.response.response.charge_state.charging_state == "Complete") then "B"
else "A" end)
timeout: 30s
type: template
template: tesla-ble
title: Your Tesla (optional)
capacity: 60 # Akkukapazität in kWh (optional)
vin: VIN # Erforderlich für BLE-Verbindung
url: IP # URL des Tesla BLE HTTP Proxy
port: 8080 # Port des Tesla BLE HTTP Proxy (optional)
```

If you want to use this proxy only for commands, and not for vehicle data, you can use the following configuration. The vehicle data is then fetched via the Tesla API by evcc.
Expand Down
19 changes: 19 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config

import (
"os"
"strconv"

"github.com/charmbracelet/log"
)
Expand All @@ -12,8 +13,11 @@ var PrivateKeyFile = "key/private.pem"
type Config struct {
LogLevel string
HttpListenAddress string
CacheMaxAge int // Seconds to cache BLE responses
}

var AppConfig *Config

func LoadConfig() *Config {
envLogLevel := os.Getenv("logLevel")
if envLogLevel == "debug" {
Expand All @@ -30,8 +34,23 @@ func LoadConfig() *Config {
}
log.Info("TeslaBleHttpProxy", "httpListenAddress", addr)

cacheMaxAge := os.Getenv("cacheMaxAge")
if cacheMaxAge == "" {
cacheMaxAge = "0" // default value
}
cacheMaxAgeInt, err := strconv.Atoi(cacheMaxAge)
if err != nil {
log.Error("Invalid cacheMaxAge value, using default (0)", "error", err)
cacheMaxAgeInt = 0
}

return &Config{
LogLevel: envLogLevel,
HttpListenAddress: addr,
CacheMaxAge: cacheMaxAgeInt,
}
}

func InitConfig() {
AppConfig = LoadConfig()
}
37 changes: 37 additions & 0 deletions docs/environment_variables.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Environment variables

You can optionally set environment variables to override the default behavior.

## logLevel

This is the log level. Options: debug, info, warn, error, fatal (Default: info)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it not only "debug" or ""?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, the other options are available but not implemented.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've updated the readme. Thank you!


## cacheMaxAge

This is the number of seconds to cache the BLE responses. If set to 0, the cache is disabled. (Default: 0)

## httpListenAddress

This is the address and port to listen for HTTP requests. (Default: :8080)

# Example

## Docker compose
You can set the environment variables in your docker-compose.yml file. Example:

```
environment:
- logLevel=debug
- cacheMaxAge=30
- httpListenAddress=:5687
```

This will set the log level to debug, the cache max age to 30 seconds, and the HTTP listen address to :5687.

## Command line

You can also set the environment variables in the command line when starting the program. Example:

```
./TeslaBleHttpProxy -logLevel=debug -cacheMaxAge=30 -httpListenAddress=:5687
wimaha marked this conversation as resolved.
Show resolved Hide resolved
```
4 changes: 4 additions & 0 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ services:
tesla-ble-http-proxy:
image: wimaha/tesla-ble-http-proxy
container_name: tesla-ble-http-proxy
environment:
- cacheMaxAge=30 # Optional, but recommended to set this to anything more than 0 if you are using the vehicle data
volumes:
- ~/TeslaBleHttpProxy/key:/key
- /var/run/dbus:/var/run/dbus
Expand All @@ -83,6 +85,8 @@ services:

Exit the file with control + x and type `y` to save the file.

Note that you can optionally set environment variables to override the default behavior. See [environment variables](docs/environment_variables.md) for more information.

### Step A-3: Start the container

Start the container with the following command:
Expand Down
13 changes: 13 additions & 0 deletions internal/api/handlers/tesla.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/charmbracelet/log"
"github.com/gorilla/mux"
"github.com/wimaha/TeslaBleHttpProxy/config"
"github.com/wimaha/TeslaBleHttpProxy/internal/api/models"
"github.com/wimaha/TeslaBleHttpProxy/internal/ble/control"
"github.com/wimaha/TeslaBleHttpProxy/internal/tesla/commands"
Expand Down Expand Up @@ -140,6 +141,8 @@ func VehicleData(w http.ResponseWriter, r *http.Request) {

wg.Wait()

SetCacheControl(w, config.AppConfig.CacheMaxAge)

if apiResponse.Result {
response.Result = true
response.Reason = "The request was successfully processed."
Expand Down Expand Up @@ -189,6 +192,8 @@ func BodyControllerState(w http.ResponseWriter, r *http.Request) {
return
}

SetCacheControl(w, config.AppConfig.CacheMaxAge)

if apiResponse.Result {
response.Result = true
response.Reason = "The request was successfully processed."
Expand All @@ -202,3 +207,11 @@ func BodyControllerState(w http.ResponseWriter, r *http.Request) {
response.Reason = err.Error()
}
}

func SetCacheControl(w http.ResponseWriter, maxAge int) {
if maxAge > 0 {
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d, must-revalidate", maxAge))
} else {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
}
}
4 changes: 2 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ var Version = "*undefined*"
func main() {
log.Infof("TeslaBleHttpProxy %s is loading ...", Version)

config := config.LoadConfig()
config.InitConfig()

control.SetupBleControl()

router := routes.SetupRoutes(static, html)

log.Info("TeslaBleHttpProxy is running!")
log.Fatal(http.ListenAndServe(config.HttpListenAddress, router))
log.Fatal(http.ListenAndServe(config.AppConfig.HttpListenAddress, router))
}
Loading