Git Product home page Git Product logo

teslamateagile's Introduction

TeslaMateAgile

Description

This app will automatically update your cost for charge sessions in TeslaMate within a specified geofence (usually home) using data from your smart electricity tariff.

Supported energy providers / tarriffs:

How to use

You can either use it in a Docker container or go to the releases and download the zip of the latest one and run it on the command line using ./TeslaMateAgile.

Alternatively, if you are using Home Assistant OS (or supervised) @tougher has wrapped this project in a Home Assistant Addon: tougher/hassio-addon-TeslaMateAgile.

If you have used the TeslaMate Docker install guide you can simply add this section to the services: section of the docker-compose.yml file and change the variables as required:

services:

  teslamateagile:
    image: mattjeanes/teslamateagile:latest
    restart: always
    environment:
      - DATABASE_USER=teslamate
      - DATABASE_PASS=secret
      - DATABASE_NAME=teslamate
      - DATABASE_HOST=database
      - TeslaMate__UpdateIntervalSeconds=300
      - TeslaMate__GeofenceId=1
      - TeslaMate__EnergyProvider=Octopus
      - Octopus__RegionCode=A # Octopus Energy only
      - Tibber__AccessToken=abc123 # Tibber only

See below for how to configure the environment variables appropriately

Required environment variables

- TeslaMate__UpdateIntervalSeconds=3600 # Scan interval for finished charges, should not exceed lookback days if set
- TeslaMate__GeofenceId=1 # You can get this by editing the Geofence inside TeslaMate and getting it from the url 

Octopus Energy

- TeslaMate__EnergyProvider=Octopus
- Octopus__RegionCode=A # See below Octopus Region Code section

Tibber

- TeslaMate__EnergyProvider=Tibber
- Tibber__AccessToken=abc123 # See below Tibber Access Token section
- Tibber__HomeId=c0693acc-567d-49d4-87d9-71a66d10f5c7 # Optional: See below Tibber Multiple Homes section

Fixed Price

- TeslaMate__EnergyProvider=FixedPrice
- FixedPrice__TimeZone=Europe/London # IANA (tz database) time zone code, used for below times 
- FixedPrice__Prices__0=08:00-13:00=0.1559 # Cost is in your currency e.g. pounds, euros, dollars (not pennies, cents, etc)
- FixedPrice__Prices__1=13:00-20:00=0.05 # You can have as many as these as you need
- FixedPrice__Prices__2=20:00-03:30=0.04
- FixedPrice__Prices__3=03:30-06:00=0.035
- FixedPrice__Prices__4=06:00-08:00=0.02

aWATTar

- TeslaMate__EnergyProvider=Awattar
- Awattar__VATMultiplier=1.00 # Optional (default: 1.19), you should not need to set this unless your VAT differs from the default

Energinet

- TeslaMate__EnergyProvider=Energinet
- Energinet__Region=YYYYY # See below Energinet regions section
- Energinet__Currency=DKK # See below Energinet currencies section
- Energinet__VAT=1.25 # Optional: VAT multiplier. In this example 25%
- Energinet__FixedPrices__TimeZone=Europe/Copenhagen # Optional: IANA (tz database) time zone code, used for below times 
- Energinet__FixedPrices__Prices__0=00:00-17:00=0.1432 # Optional: You can have as many as these as you need
- Energinet__FixedPrices__Prices__1=17:00-20:00=0.3983
- Energinet__FixedPrices__Prices__2=20:00-00:00=0.1432

Home Assistant

- TeslaMate__EnergyProvider=HomeAssistant
- TeslaMate__LookbackDays=7 # Optional: Highly recommended, see below Optional environment variables section
- HomeAssistant__BaseUrl=http://homeassistant.local:8123 # URL to your Home Assistant instance
- HomeAssistant__AccessToken=abc123 # Long-lived access token for Home Assistant
- HomeAssistant__EntityId=input_number.energy_price # ID of the number-based entity containing price data in Home Assistant (Cost is in your currency e.g. pounds, euros, dollars (not pennies, cents, etc))

Optional environment variables

- Logging__LogLevel__Default=Debug # Enables debug logging, useful for seeing exactly how a charge was calculated
- Logging__Console__FormatterName=simple # This and the below env var will prepend a timestamp to every log message the same way TeslaMate does
- "Logging__Console__FormatterOptions__TimestampFormat=yyyy-MM-dd HH:mm:ss.fff " # See above env var
- TeslaMate__FeePerKilowattHour=0.25 # Adds a flat fee per kWh, useful for certain arrangements (default: 0)
- TeslaMate__LookbackDays=7 # Only calculate charges started in the last x days (default: null, all charges)
- TeslaMate__Phases=1 # Number of phases your charger is connected to (default: null, auto-detect)

Database connection

You also need to configure the database connection to the TeslaMate PostgreSQL database, you can do this either by supplying a PostgreSQL connection string directly or by using the same ones used by TeslaMate in the docker-compose.yml

- DATABASE_HOST=database
- DATABASE_NAME=teslamate
- DATABASE_USER=teslamate
- DATABASE_PASS=secret
- DATABASE_PORT=5432 # Optional (default: 5432)

OR (not recommended)

- ConnectionStrings__TeslaMate=Host=database;Database=teslamate;User Id=teslamate;Password=secret;

Energy provider setup

Octopus Region Code

Electricity tariffs in Octopus Energy are separated into multiple regions depending on where you live, in order to find your code you can use one of two methods:

  1. Go to https://octopus.energy/dashboard/developer/
  2. Under Unit Rates, just before 'standard-unit-rates' in the URL provided there is a letter, this is your region code
  3. For example in https://api.octopus.energy/v1/products/AGILE-18-02-21/electricity-tariffs/E-1R-AGILE-18-02-21-A/standard-unit-rates/ your region code is A

Or if you're familar with curl / postman / etc

  1. Call GET https://api.octopus.energy/v1/industry/grid-supply-points?postcode=POSTCODEHERE
  2. You will get a response with "group_id": "_A" for example, A is your region code

Tibber

Tibber Access Token

Tibber requires users to supply their access token to provide pricing information for their tarriff. It is only used to query tarriff information and at no point does TeslaMateAgile request or access any data related to consumption or any account details. You can find the related code here.

You can acquire this token here: https://developer.tibber.com/settings/accesstoken

Tibber Multiple Homes

If you have multiple homes, you can specify Tibber__HomeId to select the home you want to use. To find it, you can use the Tibber GraphQL Explorer and run the following query:

{
  viewer {
    homes {
      id
      address {
        address1
        postalCode
        city
        country
      }
    }
  }
}

Energinet

Energinet regions

Currently available areas are DK1, DK2, NO2, SE3, SE4

Energinet currencies

Valid currency options are DKK (Danish Krone) or EUR (Euro)

VAT

Prices on Energinet appear to be without VAT so this defines a multiplier to be applied before using the price for further calculations.

Fixed prices

Support for this is added for accommodating different transmission charges, taxes, etc. This will be added to the price reported from Energinet's API.

Home Assistant

Base Url

This is the URL to your Home Assistant instance, it should include the protocol (http or https) and the port if it's not the default (8123). If you are hosting TeslaMateAgile outside of your home network you will need to ensure that your Home Assistant instance is accessible from the internet.

Access Token

This is a long-lived access token for Home Assistant, you can create one by going to your profile in Home Assistant and clicking "Create Token" under "Long-Lived Access Tokens". This token is only used to query the entity you specify and at no point does TeslaMateAgile request or access any other data.

Entity ID

This is the ID of the number-based entity containing price data in Home Assistant, it should be in the format input_number.energy_price and should be updated by Home Assistant with the price for the current time period. The price should be in your currency e.g. pounds, euros, dollars (not pennies, cents, etc).

Lookback Days

Home Assistant by default only keeps 10 days of history and will fail to calculate charges if the data is missing. It is highly recommended to set this to a value lower than the number of days of history you have in Home Assistant. A good value is 7 days if you have the default 10 days of history.

FAQ

How do I recalculate a charge?

In some cases you may want to tell TeslaMateAgile to recalculate a particular charge, to do this you need to set the cost column in the charging_processes table in the TeslaMate PostgreSQL database to NULL for the charges you want to recalculate.

You should filter this by a particular charge id or by geofence_id if you want to recalculate everything. To find a particular charge id, look in the URL when viewing it in Grafana, it should be on the end of the URL: ...&var-charging_process_id=xxx.

TeslaMate has a guide on manually fixing data here: https://docs.teslamate.org/docs/maintenance/manually_fixing_data

Common SQL queries

Recalculate charge costs for a particular charge: UPDATE charging_processes SET cost=NULL WHERE id={ChargeId} Recalculate charge costs for all charges at your GeofenceId: UPDATE charging_processes SET cost=NULL WHERE geofence_id={GeofenceId}

Please be careful when running SQL queries against your TeslaMate database as they may result in permanent data loss. Take a backup of your database before if you're not sure.

How do I use a more complex time-of-use tariff or one that isn't supported?

If you've got an advanced use case or a tariff that isn't supported and you the FixedPrice provider is too limited for you (e.g. summer / winter pricing), you can use Home Assistant to provide the pricing data to TeslaMateAgile using the HomeAssistant provider.

This way you can use any number of integrations, sensors, automations, etc to provide a number-based entity to TeslaMateAgile which will be used as the price for the charge.

As an example, you can effectively create an Intelligent Octopus integration by using the octopus_intelligent integration along with a couple of automations to update the price entity when the off-peak / peak activates.

If you don't use Home Assistant, unfortunately you will need to wait for your use case to be supported, submit a PR to add support for it or install Home Assistant for this purpose.

Why do short charges sometimes have no cost?

Due to how TeslaMate calculates your electricity phases (TeslaMateAgile uses the same logic), short charges sometimes do not have enough data to determine the phases and this will result in a zero cost. You will see a warning in the logs when this happens that looks like this:

warn: TeslaMateAgile.PriceHelper[0] Unable to determine phases for charges
info: TeslaMateAgile.PriceHelper[0] Calculated cost 0 and energy 0 kWh for charging process 26

To workaround this issue, you can set the TeslaMate__Phases environment variable to override the auto-detection, this will allow short charges to be calculated correctly as long as you set the correct number of phases.

Docker support

This project is available on Docker

teslamateagile's People

Contributors

dependabot-preview[bot] avatar marval avatar mattjeanes avatar tobiasehlert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

teslamateagile's Issues

Support for Tibber

Tibber is an energy provider much like Octopus Energy with a dynamic tariff and a public API to get pricing - this issue is to track the addition of Tibber support to TeslaMateAgile and more generally support for multiple energy providers.

They use a GraphQL API documented here: https://developer.tibber.com/explorer

I have discovered that we can request price info for arbitrary date ranges by using the start and end cursors on the range, which is a base64 encoded ISO 8601 string. For example, the following gets the last 24 hours from before 6am (+1 UTC) on the 1st January 2020:

The ISO 8601 date (2020-01-01T06:00:00+01:00) base64 encoded is MjAyMC0wMS0wMVQwNjowMDowMCswMTowMA==

{
  viewer {
    homes {
      currentSubscription{
        priceInfo{
          range(resolution: HOURLY, last: 24, before: "MjAyMC0wMS0wMVQwNjowMDowMCswMTowMA==") {
            pageInfo {
              endCursor,
              startCursor
            }
            nodes {
              total
              energy
              tax
              startsAt
              level
            }
          }
        }
      }
    }
  }
}

Multiple location support

Question - Is there a way to support different geofences in different Octopus regions?
I'm guessing not as is from the documentation and variables, but could I run 2 docker instances of TeslaMateAgile, one for each location, against the same TeslaMate instance?

Feature request : Show the energy prices in a dashboard

I was wondering if it would be somehow possible to display the instantaneous electricity price (at least for the current day) from Energinet/others in a dashboard. Because these values (from the last 7 days if I am not wrong) are available to TeslaMateAgile and if it can show the instantaneous price (at least for the current day) it would be great.

Tibber "Failed to calculate charging cost"

Tibbers API didn't like me trying to calculate prices of my over 1000 charges in one go. Is there a way to do it in batches?

info: TeslaMateAgile.PriceHelper[0]

  Calculating cost for charges 12/29/2023 08:08:10 UTC - 12/29/2023 08:08:37 UTC

fail: TeslaMateAgile.PriceHelper[0]

  Failed to calculate charging cost / energy for charging process 1226

  GraphQL.Client.Http.GraphQLHttpRequestException: The HTTP request failed with status code TooManyRequests

     at TeslaMateAgile.Services.TibberService.SendRequest(GraphQLHttpRequest request) in /src/TeslaMateAgile/Services/TibberService.cs:line 139

     at TeslaMateAgile.Services.TibberService.GetPriceData(DateTimeOffset from, DateTimeOffset to) in /src/TeslaMateAgile/Services/TibberService.cs:line 67

     at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 96

     at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 74

Some Crashing Entries

Found some entries from the logs that are causing FAIL errors.

Here's the log:

fail: TeslaMateAgile.PriceHelper[0]
      Failed to calculate charging cost / energy for charging process 415
      System.InvalidOperationException: Sequence contains no elements
         at System.Linq.ThrowHelper.ThrowNoElementsException()
         at System.Linq.Enumerable.Average(IEnumerable`1 source)
         at TeslaMateAgile.PriceHelper.DeterminePhases(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 141
         at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 91
         at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 64
info: TeslaMateAgile.PriceHelper[0]
      Calculating cost for charges 01/15/2022 05:13:21 UTC - 01/15/2022 05:13:28 UTC
fail: TeslaMateAgile.PriceHelper[0]
      Failed to calculate charging cost / energy for charging process 416
      System.InvalidOperationException: Sequence contains no elements
         at System.Linq.ThrowHelper.ThrowNoElementsException()
         at System.Linq.Enumerable.Average(IEnumerable`1 source)
         at TeslaMateAgile.PriceHelper.DeterminePhases(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 141
         at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 91
         at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 64
info: TeslaMateAgile.PriceHelper[0]
      Calculating cost for charges 03/14/2022 02:04:18 UTC - 03/14/2022 02:04:26 UTC
fail: TeslaMateAgile.PriceHelper[0]
      Failed to calculate charging cost / energy for charging process 465
      System.InvalidOperationException: Sequence contains no elements
         at System.Linq.ThrowHelper.ThrowNoElementsException()
         at System.Linq.Enumerable.Average[TSource](IEnumerable`1 source, Func`2 selector)
         at TeslaMateAgile.PriceHelper.DeterminePhases(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 145
         at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 91
         at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 64

and here's some sample data (zip of a CSV and SQL insert statements)
charging_processes_202207192202.zip

Calculation fails when the end time of a charge is very close to the beginning of the hour

Hi, awesome project, but ran into an issue using the Energinet provider. I had a charge that finished at the following timestamp:
2023-04-02 13:00:19.299.

When calculating it failed at the following line:

https://github.com/MattJeanes/TeslaMateAgile/blob/179ddd7c201abd178c0a1c79d42e24bb6149aa63/TeslaMateAgile/Helpers/PriceHelper.cs#LL127

With the error:

Charge calculation failed, pricing calculated for 364 / 365, likely missing price data

To fix it, I change the last timestamp of the charges table to 2023-04-02 13:01:19.299 via. psql, that is one minute later. I assume there's some issue related to charging finishing within the first minute of an hour. I didn't dig any deeper as the database modification solved my issue this time.

Let me know if any other information is needed.

Updating price from Home Assistant fails because "The input string 'unavailable' was not in a correct format."

Hi,
I'm on Octopus tracker, Home Assistant is importing the cost of electricity prices via the Octopus add-on and of course I configured teslamate to import the rate of electricity from Home Assistant, this morning something has gone wrong with the add-on and it stored "unavailable" in the data.


Timestamp | State
15/01/2024 18:44 | 0.1764
16/01/2024 00:00 | 0.18396
17/01/2024 00:00 | 0.187845
18/01/2024 00:00 | 0.1722
19/01/2024 00:00 | 0.16653
20/01/2024 00:00 | 0.162015
20/01/2024 00:45 | unavailable
20/01/2024 07:51 | 0.162015

It also happened that my car was in charge at the time, which I think it is causing the issue and it is stopping teslamateagile from adjusting the cost of charge in the database.

In my opinion the software shouldn't try parsing a string which is not a number, and should fill the gap by forward filling the last correct data, which in my specific case would have worked perfectly fine, but I appreciate that it might not be the case in other configuration, but in any case it is better than no data at all.

See log here below.

teslamateagile_1  | info: TeslaMateAgile.PriceHelper[0]
teslamateagile_1  |       Calculating cost for charges 01/19/2024 20:00:51 UTC - 01/20/2024 04:32:35 UTC
teslamateagile_1  | fail: TeslaMateAgile.PriceHelper[0]
teslamateagile_1  |       Failed to calculate charging cost / energy for charging process 3
teslamateagile_1  |       System.FormatException: The input string 'unavailable' was not in a correct format.
teslamateagile_1  |          at System.Number.ThrowFormatException[TChar](ReadOnlySpan`1 value)
teslamateagile_1  |          at System.Number.ParseDecimal[TChar](ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
teslamateagile_1  |          at System.Decimal.Parse(String s)
teslamateagile_1  |          at TeslaMateAgile.Services.HomeAssistantService.GetPriceData(DateTimeOffset from, DateTimeOffset to) in /src/TeslaMateAgile/Services/HomeAssistantService.cs:line 44
teslamateagile_1  |          at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 96
teslamateagile_1  |          at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 74
teslamateagile_1  | info: TeslaMateAgile.PriceService[0]
teslamateagile_1  |       Waiting 300 seconds until next update

TeslaMateAgile.PriceHelper Tibber fails

Hi Guys,

I'm getting some errors, is this an issue on my side or Tibber?

teslamateagile_1 | info: TeslaMateAgile.PriceHelper[0]
teslamateagile_1 | Looking for finished charging processes with no cost set in the 'Home' geofence (id: 1)
teslamateagile_1 | info: TeslaMateAgile.PriceHelper[0]
teslamateagile_1 | Calculating cost for charges 02/23/2024 08:26:26 UTC - 02/23/2024 08:31:02 UTC
teslamateagile_1 | fail: TeslaMateAgile.PriceHelper[0]
teslamateagile_1 | Failed to calculate charging cost / energy for charging process 179
teslamateagile_1 | System.Exception: Mismatch of requested price info from Tibber API (expected: 2, actual: 0)
teslamateagile_1 | at TeslaMateAgile.Services.TibberService.GetPriceData(DateTimeOffset from, DateTimeOffset to) in /src/TeslaMateAgile/Services/TibberService.cs:line 105
teslamateagile_1 | at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 96
teslamateagile_1 | at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 74

No data available if multiple homes exist

I've added another home last week because I will move in 2 months, but now no data is available anymore for the current home, because TeslaMateAgile always takes the first home which the API gives, but I need so select the second home now.

Is there a easy way to do that?

Personalised prices

Hi
Is it a way to define personalised prices for differents periods ?
I don't have Octopus Energy or Tibber provider but a french provider with differents prices according to hours
Between 8.00 am and 11.00pm 0,1799
Between 11.00 pm and 2.00 am 0,1346
Between 2.00 am and 6.00 am 0,1095
Between 6.00 am and 8.00 am 0,1346
It seems that it is not possible to define other provider than the two you set
Thanks

Weekend and Summer/Winter pricing

Hi @MattJeanes, thank you for the great project!

My provider has the following rates:

Summer pricing (between March and October):

  • 00:00 - 07:00 (monday to friday) = 0,0895€ [cheap]
  • 07:00 - 23:59 (monday to friday) = 0,1795€ [expensive]
  • 00:00 - 09:30 (saturday) = 0,0895€ [cheap]
  • 09:31 - 13:00 (saturday) = 0,1795€ [expensive]
  • 13:01 - 18:30 (saturday) = 0,0895€ [cheap]
  • 18:31 - 22:00 (saturday) = 0,1795€ [expensive]
  • 22:01 - 23:59 (saturday) = 0,0895€ [cheap]
  • 00:00 - 23:59 (sunday) = 0,0895€ [cheap]

Then there's the winter pricing, with slightly different hours.

Any thoughts on having the fixed rates system fit these needs?

Change Port from Database

Hi Matt,

nice work you have done here :)
Is there a way to change the default port of the database?

Thanks

Specifying an invalid GeofenceID does not throw errors

There seems to be no check for the existence of a GeoFenceID in the teslamate DB.
This results in the application running just fine, but never actually finding any charging sessions to update.

Consider adding a check for validity of the geofence id on each "update run", in case it does not exist (either by being deleted in between runs, or by being configured with the wrong ID).
Also consider adding logging to show the configured GeofenceID and Name of the geofence when executing an "update run", so that it will be a bit more obvious if the wrong GeofenceID has been configured.

Grid rent

Hi,

Would it be possible to add a configurable grid rent fee? I rent an apartment and therefore i use this addon with teslamate to calculate how much i have to pay to my landlord (who uses tibber so I can calculate prices from there) for my car charging. Currently i have to add the 0.4833NOK per kWh on in another calculation on the side. It would be great to make it possible to add this automatically in some config so that it is added together with the variable fee.

Entsoe transparency API provider support

Many people (in the Nordpool spot areas in particular) have spot price contracts that follow the spot price per hour for their area - similar to what's fetched in the Tibber integration ( #12 ). Usually these contracts have some kind of fixed addition (can be negative, 0 or positive - included already in Tibber data) to the spot price, so this addition could be configurable.

There is a more generic pricing API delivered by entsoe called the "transparency API" where interested parties can download future (day-head) and historical spot prices for each price area (e.g. I'd personally fetch prices for the NO3 price area (link is to price data for jan 8th 2020).

They have an API user guide, and API access is requested after registering an account by sending an email with the subject "Restful API access" to [email protected], with your registered email address in the message body. Token for access is created manually after logging in and having API access granted.

I think the ability of fetching price data from this API based on a selectable (or even dynamic based on positution) price area would be a very valuable addition to TMA. I'll be experimenting a bit with fetching data from entsoe in a small python project and might try my luck at C# if I manage to finish that project.

Error calculating costs with Tibber provider

Hi,
Have used this excellent app with my Teslamate installation.
But now it does not work anymore. Stopped working 3-4 weeks ago.
Get following error on my docker instants when using the Tibber provider.

teslamateagile_1  | dbug: TeslaMateAgile.PriceService[0]
teslamateagile_1  |       Updating prices
teslamateagile_1  | info: TeslaMateAgile.PriceHelper[0]
teslamateagile_1  |       Looking for finished charging processes with no cost set in the 'Garaget' geofence (id: 1)
teslamateagile_1  | info: TeslaMateAgile.PriceHelper[0]
teslamateagile_1  |       Calculating cost for charges 10/28/2022 19:30:04 UTC - 10/28/2022 19:30:10 UTC
teslamateagile_1  | fail: TeslaMateAgile.PriceHelper[0]
teslamateagile_1  |       Failed to calculate charging cost / energy for charging process 1287
teslamateagile_1  |       System.NullReferenceException: Object reference not set to an instance of an object.
teslamateagile_1  |          at TeslaMateAgile.Services.TibberService.GetPriceData(DateTimeOffset from, DateTimeOffset to) in /src/TeslaMateAgile/Services/TibberService.cs:line 68
teslamateagile_1  |          at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 86
teslamateagile_1  |          at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 64
teslamateagile_1  | info: TeslaMateAgile.PriceHelper[0]
teslamateagile_1  |       Calculating cost for charges 11/21/2022 01:23:31 UTC - 11/21/2022 03:28:46 UTC
teslamateagile_1  | fail: TeslaMateAgile.PriceHelper[0]
teslamateagile_1  |       Failed to calculate charging cost / energy for charging process 1313
teslamateagile_1  |       System.NullReferenceException: Object reference not set to an instance of an object.
teslamateagile_1  |          at TeslaMateAgile.Services.TibberService.GetPriceData(DateTimeOffset from, DateTimeOffset to) in /src/TeslaMateAgile/Services/TibberService.cs:line 68
teslamateagile_1  |          at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 86
teslamateagile_1  |          at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 64

Enhancement / Feature Upgrade - integration of EMS evcc

Idea is to integrate evcc. Evcc provides various data via MQTT including a price. Enhancement is that currently solar power (=0 costs) is not dynamically possible with your implementation. With integration of evcc, evcc calculates the price recognizing dynamic tariffs like Tibber, too and provides it via mqtt. Your application could fetch the current calculated price recognizing solar and grid mix and pushed it into teslamate database.

Help needed: "number-based entity" in HomeAssistant clarification

Hi,

I have a sensor in HomeAssistant (entity is sensor.energy_price) that contains the price/kWh at any given moment in time. However, it does not seem to work when I configure it as

  • HomeAssistant__EntityId=sensor.energy_price

The error messages I get are:

info: TeslaMateAgile.PriceHelper[0]
      Calculating cost for charges 05/14/2024 01:00:02 UTC - 05/14/2024 04:54:03 UTC
fail: TeslaMateAgile.PriceHelper[0]
      Failed to calculate charging cost / energy for charging process 282
      System.Net.Http.HttpRequestException: An error occurred while sending the request.
       ---> System.Net.Http.HttpIOException: The response ended prematurely. (ResponseEnded)
         at System.Net.Http.HttpConnection.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at System.Net.Http.HttpConnection.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
         at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
         at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
         at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.<SendCoreAsync>g__Core|5_0(HttpRequestMessage request, Boolean useAsync, CancellationToken cancellationToken)
         at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.<SendCoreAsync>g__Core|5_0(HttpRequestMessage request, Boolean useAsync, CancellationToken cancellationToken)
         at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
         at TeslaMateAgile.Services.HomeAssistantService.GetPriceData(DateTimeOffset from, DateTimeOffset to) in /src/TeslaMateAgile/Services/HomeAssistantService.cs:line 29
         at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 96
         at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 74
info: TeslaMateAgile.PriceService[0]
      Waiting 1200 seconds until next update

Does the entity need to be of type "input_number"? If so, can anyone give me some indications as to how to update the value of an input_number based on the value of a sensor?

Thanks in advance!

Problem going from Octopus Agile to Go

Hi Matt,
I was on Octopus Agile which worked correctly, I've now moved to Go Faster.
I have edited the yml as follows:

      - TeslaMate__UpdateIntervalSeconds=300
      - TeslaMate__GeofenceId=1
      - TeslaMate__Phases=1
      - TeslaMate_EnergyProvider=FixedPrice
      - FixedPrice__TimeZone=Europe/London
      - FixedPrice__Prices__0=00:00-20:30=13.8
      - FixedPrice__Prices__1=20:30-23:30=4.5
      - FixedPrice__Prices__2=23:30-23:59=13.8

but I receive the following error:

Microsoft.Extensions.Options.OptionsValidationException: DataAnnotation validation failed for members: 'RegionCode' with the error: 'The RegionCode field is required.

If I add in the region_code field I previously had then the pricing is derived from the Octopus API lookup ignoring the FixedPrice option.

Thanks

UTC time issue

First of all, thanks for the new 1.11.0 @marval

I was trying to calculate the cost for my most recent charge. It is Tesla Mate identified correctly to have started at 3AM DK time.
image

My config is as simple as possible with no fixed prices added.

teslamateagile:
    image: mattjeanes/teslamateagile:latest
    restart: always
    environment:
    - DATABASE_USER=teslamate
    - DATABASE_PASS=secret
    - DATABASE_NAME=teslamate
    - DATABASE_HOST=database
    - TeslaMate__UpdateIntervalSeconds=10
    - TeslaMate__GeofenceId=4
    - TeslaMate__EnergyProvider=Energinet
    - Energinet__Region=DK2 # See below a list of all Energinet regions
    - Energinet__VAT=1.25 # Optional: VAT multiplier. In this example 25%
#    - Energinet__FixedPrices__TimeZone=Europe/Copenhagen # Optional: IANA (tz database) time zone code, used for below times
#    - Energinet__FixedPrices__Prices__0=00:00-06:00=0.29 # Optional: You can have as many as these as you need
#    - Energinet__FixedPrices__Prices__1=06:00-20:00=0.3983
#    - Energinet__FixedPrices__Prices__2=20:00-00:00=0.1432
    - Logging__LogLevel__Default=Debug

When it is calculating the cost I get the following in the log:

dbug: TeslaMateAgile.PriceHelper[0]
      Calculated charge cost for 01/08/2023 02:00:00 UTC - 01/08/2023 03:00:00 UTC (unit cost: 0.08645000500, fee per kWh: 0): 0.9237491879774529519465957432 for 10.68535725333333354864 energy
dbug: TeslaMateAgile.PriceHelper[0]
      Calculated charge cost for 01/08/2023 03:00:00 UTC - 01/08/2023 04:00:00 UTC (unit cost: 0.08460000, fee per kWh: 0): 0.9292778226959999640258240000 for 10.98437142666666624144 energy
dbug: TeslaMateAgile.PriceHelper[0]
      Calculated charge cost for 01/08/2023 04:00:00 UTC - 01/08/2023 05:00:00 UTC (unit cost: 0.03867500125, fee per kWh: 0): 0.1678530743541153746034887952 for 4.34009228000000063616 energy
info: TeslaMateAgile.PriceHelper[0]
      Calculated cost 2.02 and energy 26.01 kWh for charging process 363

It takes my 03:00-04:00 DK time and converts it ti 02:00-03:00UTC which is correct. However, when looking at a data dump from energidataservice I get the following:

image

So TeslaMateAgile says it pulls a cost of 0.0864500500 from 01/08/2023 02:00:00 UTC - 01/08/2023 03:00:00 UTC but the price is actually 0.03867500125. It seems that TeslaMateAgile thinks it gets the cost from 02:00 UTC to 03:00 UTC, but actually takes the cost from 00:00 UTC - 01:00 UTC.

Failed to calculate charging cost / energy for charging process

Hello,
I have recently setup Teslamate Agile and am using Home Assistant to track import costs of provider.
My particular provider has a plan where my electricity price drops to $0 between the hours of 12pm and 2pm Saturday and Sunday.
There is no API integration with this provide, so I have Home assistant just running a number helper to automate the price change in import costs from the provider.
The helper triggers on schedule and changes the price of import costs, all other services in HA that depend on this cost appear to be representing their data correctly, so I assume I have set that up right.

I have seen this on a few charges and it has cleared itself automatically in the past, but this one is not clearing and has now been overtaken by a newer charge that was calculated.

Attached is the charge id in question
data-1693143085068.csv

info: Microsoft.Hosting.Lifetime[0]
      Content root path: /app/
info: TeslaMateAgile.PriceHelper[0]
      Looking for finished charging processes with no cost set started less than 6 day(s) ago in the 'Home' geofence (id: 1)
info: TeslaMateAgile.PriceHelper[0]
      Calculating cost for charges 08/24/2023 23:43:53 UTC - 08/25/2023 03:19:42 UTC
info: TeslaMateAgile.PriceHelper[0]
      Phase correction: 2 -> 3
fail: TeslaMateAgile.PriceHelper[0]
      Failed to calculate charging cost / energy for charging process 65
      System.Exception: Charge calculation failed, pricing calculated for 628 / 629, likely missing price data
         at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 138
         at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 74
info: TeslaMateAgile.PriceService[0]
      Waiting 14400 seconds until next update

This keeps repeating in the logs. Sadly I recreated the container without saving the old logs, but I am now up to charge process 66 and that one calculated fine.

While reading through closed issues, I saw that it was mentioned that the phase correction was not needed and to be removed, I have done that recently but has not fixes my issue. Here is my compose file

  teslamateagile:
    image: mattjeanes/teslamateagile:latest
    restart: always
    environment:
      - DATABASE_USER=teslamate
      - DATABASE_PASS=secret
      - DATABASE_NAME=teslamate
      - DATABASE_HOST=database
      - TeslaMate__UpdateIntervalSeconds=14400
      - TeslaMate__GeofenceId=1
      - TeslaMate__EnergyProvider=HomeAssistant
      - TeslaMate__LookbackDays=6
      #- TeslaMate__Phases=3 not required https://github.com/MattJeanes/TeslaMateAgile/issues/17
      - HomeAssistant__BaseUrl=<IP>
      - HomeAssistant__AccessToken=<TOKEN>
      - HomeAssistant__EntityId=input_number.re_import_price

Bonus question: Since I only charge every other day, I don't need this process checking every 5 minutes if a charge has completed, so have increased the update interval a little to an arbitrary time (4 hours) so it would only run 6 times a day.
My price only changes for 2 hours in a day, most charging sessions last 4-5 hours and the free energy period will usually be in the middle of the 4-5 hour session. Would the calculations be able to account for that without checking for charge events every 5 minutes?

Thanks

Make logging a little bit more useful

Hi there, thanks for making such a nifty little utility. I recently switched from Octopus Agile to Octopus Go, so I've changed to "FixedPrice", but when I had a look at the logs (docker-compose logs) I noticed that the teslamateagile logs have no timestamps in them (compared to e.g. the teslamate logs). Would it be possible to add a timestamp (in a consistent format)?

A second request would be to expand "Updating prices" to something like "Updating prices: price is now 5p"?

Thanks!

Provider feature request : EDF Tempo French Provider

Hi,

Would it be possible to have a new provider for TeslaMateAgile ? (using API from RTE)

With "EDF" French National provider, there is an offer called "TEMPO"

Hours :
From 6 am to 10 pm : this is Full Hour with specific cost of KWh, and from 10 pm to 6 am, this is off-peak hour with another specific cost of KWh

Days :

  • 300 days a year we have a "blue days" (BLEU) cost, almost cheap.
  • 43 days a year of high consumption on the electrical network, there is more expansive costs "white days" (BLANC) to encourage people to reduce their consumption.
  • 22 days a year of VERY HIGH consumption on the electrical network, there is VERY expansive costs "Red days" (ROUGE) to encourage people to really reduce their consumption.

Of course, there is different costs in full hours costs & off-peak hours costs, for each color of days.....

See full exemple table here : https://images.prismic.io/ekwateur-edito/ff58a9e7-053a-4597-b24f-476aa63ac143_grille-tarifaire-edf-tempo.PNG?auto=compress,format

There is an API documentation here (FR/EN switch at he top right corner window) :
https://data.rte-france.com/catalog/-/api/doc/user-guide/Tempo+Like+Supply+Contract/1.1

With this API, we could know colors of time periods
With color of time period + 2 Fixed costs by color in full hours costs & off-peak hours costs, here we are...

Regards.

Unable to calculate cost of some charges

I have a few charges where the price will not be calculated. I am using Energinet to provide the prices and it oftens works, but in some cases it does not.

Here is the log from the attempt to calculate the cost for this single charge "452"

Any idea what is wrong?

dbug: TeslaMateAgile.PriceService[0]
      Updating prices
info: TeslaMateAgile.PriceHelper[0]
      Looking for finished charging processes with no cost set in the 'Home' geofence (id: 4)
info: TeslaMateAgile.PriceHelper[0]
      Calculating cost for charges 05/23/2023 13:33:21 UTC - 05/23/2023 15:00:10 UTC
dbug: TeslaMateAgile.PriceHelper[0]
      Retrieved 5 prices:
dbug: TeslaMateAgile.PriceHelper[0]
      05/23/2023 10:00:00 UTC - 05/23/2023 11:00:00 UTC: 0.87898751125
dbug: TeslaMateAgile.PriceHelper[0]
      05/23/2023 11:00:00 UTC - 05/23/2023 12:00:00 UTC: 0.69429999125
dbug: TeslaMateAgile.PriceHelper[0]
      05/23/2023 12:00:00 UTC - 05/23/2023 13:00:00 UTC: 0.52374999750
dbug: TeslaMateAgile.PriceHelper[0]
      05/23/2023 13:00:00 UTC - 05/23/2023 14:00:00 UTC: 0.51081250
dbug: TeslaMateAgile.PriceHelper[0]
      05/23/2023 14:00:00 UTC - 05/23/2023 15:00:00 UTC: 0.58975000250
info: TeslaMateAgile.PriceHelper[0]
      Phase correction: 2 -> 3
dbug: TeslaMateAgile.PriceHelper[0]
      Calculated charge cost for 05/23/2023 13:00:00 UTC - 05/23/2023 14:00:00 UTC (unit cost: 0.51081250, fee per kWh: 0): 2.4673334913608334581895300000 for 4.83021361333333357776 energy
dbug: TeslaMateAgile.PriceHelper[0]
      Calculated charge cost for 05/23/2023 14:00:00 UTC - 05/23/2023 15:00:00 UTC (unit cost: 0.58975000250, fee per kWh: 0): 6.4808319197627931300064801272 for 10.98911724000000005088 energy
fail: TeslaMateAgile.PriceHelper[0]
      Failed to calculate charging cost / energy for charging process 452
      System.Exception: Charge calculation failed, pricing calculated for 255 / 256, likely missing price data
         at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 127
         at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 64
dbug: TeslaMateAgile.PriceService[0]
      Price update complete

Costs not calculated after upgrade to 1.8.0

Hello,

The charging costs are not calculated anymore since I've upgraded to 1.8.0. No changes in conf, and no TeslaMateAgile info in logs

Capture d’écran 2021-11-09 à 08 14 36

2021-11-07 : TeslaMateAgile 1.7.0
2021-11-08 : TeslaMateAgile 1.8.0

Conf :

  teslamateagile:
    image: mattjeanes/teslamateagile:latest
    restart: always
    environment:
      - DATABASE_USER=${TM_DB_USER}
      - DATABASE_PASS=${TM_DB_PASS}
      - DATABASE_NAME=${TM_DB_NAME}
      - DATABASE_HOST=database
      - TeslaMate__UpdateIntervalSeconds=300
      - TeslaMate__GeofenceId=1
      - TeslaMate__EnergyProvider=FixedPrice
      - FixedPrice__TimeZone=Europe/Paris
      - FixedPrice__Prices__0=06:30-22:30=0.1853
      - FixedPrice__Prices__1=22:30-06:30=0.1353
      - Logging__LogLevel__Default=Debug

Startup logs

teslamate_1       | 2021-11-09 07:47:01.988 [info] Migrations already up
teslamate_1       | 2021-11-09 07:47:07.647 [info] System Info: Erlang/OTP 24 (jit)
teslamate_1       | 2021-11-09 07:47:07.647 [info] Version: 1.24.2
teslamate_1       | 2021-11-09 07:47:07.980 [info] POST https://auth.tesla.com/oauth2/v3/token -> 200 (293.420 ms)
teslamate_1       | 2021-11-09 07:47:09.728 [info] POST https://owner-api.teslamotors.com/oauth/token -> 200 (1746.672 ms)
teslamate_1       | 2021-11-09 07:47:09.728 [info] Refreshed api tokens
teslamate_1       | 2021-11-09 07:47:09.734 [info] Scheduling token refresh in 5 wk 5 d
teslamate_1       | 2021-11-09 07:47:09.737 [info] Running TeslaMateWeb.Endpoint with cowboy 2.9.0 at :::4000 (http)
teslamate_1       | 2021-11-09 07:47:09.739 [info] Access TeslaMateWeb.Endpoint at http://xxxxx.com
teslamate_1       | 2021-11-09 07:47:10.589 [info] Starting logger for 'Tut Tut Bolide'
teslamate_1       | 2021-11-09 07:47:10.603 [info] MQTT connection has been established
teslamate_1       | 2021-11-09 07:47:11.201 [info] tzdata release in place is from a file last modified Tue, 22 Dec 2020 23:35:21 GMT. Release file on server was last modified Fri, 22 Oct 2021 02:20:47 GMT.
teslamate_1       | 2021-11-09 07:47:11.422 car_id=1 [info] Start / :asleep
teslamate_1       | 2021-11-09 07:47:12.901 [info] Tzdata has updated the release from 2020e to 2021e
teslamate_1       | 2021-11-09 07:55:36.595 [info] GET /
teslamate_1       | 2021-11-09 07:55:36.610 [info] Sent 200 in 14ms

Feature Request: Fixed Pricing Based on Day of Week

My power plan is as follows:

Monday - Friday

  • 00:00-08:00 low tier
  • 08:00-10:00 high tier
  • 10:00-15:00 low tier
  • 15:00-20:00 high tier
  • 20:00-00:00 low tier

Saturday - Sunday

  • 00:00 - 23:59 low tier

When I charge during the weekend, the costs are calculated at a high tier rate if charging during one of the high tier times (only applicable on weekdays) as TeslaMateAgile can’t currently be setup with pricing tiers dependent upon the day of the week.

It would be amazing to be able to set up Fixed Pricing based on the day of the week to account for that.

Can't calculate certain fixed prices

Issue repeat everyday around this time interval : 2021-06-22 23:00:23.707 | 2021-06-23 00:04:17.124 (UTC in database which is 2021-06-23 01:00:23.707 | 2021-06-23 02:04:17.124 local)

Other calculations are ok ...

`

  • teslamateagile_1 | info: TeslaMateAgile.PriceHelper[0]
  • teslamateagile_1 | Calculating cost for charges 06/22/2021 23:00:23 UTC - 06/23/2021 00:04:17 UTC
  • teslamateagile_1 | fail: TeslaMateAgile.PriceHelper[0]
  • teslamateagile_1 | Failed to calculate charging cost / energy for charging process 1032
  • teslamateagile_1 | System.Exception: Charge calculation failed, pricing calculated for 0 / 158, likely missing price data
  • teslamateagile_1 | at TeslaMateAgile.PriceHelper.CalculateChargeCost(IEnumerable`1 charges) in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 106
  • teslamateagile_1 | at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/Helpers/PriceHelper.cs:line 54
    `

I have thoses prices defined :

`

  • FixedPrice__TimeZone=Europe/Madrid
  • FixedPrice__Prices__0=00:00-08:00=0.15
  • FixedPrice__Prices__1=08:00-10:00=0.2
  • FixedPrice__Prices__2=10:00-14:00=0.3
  • FixedPrice__Prices__3=14:00-18:00=0.2
  • FixedPrice__Prices__4=18:00-22:00=0.3
  • FixedPrice__Prices__5=22:00-24:00=0.2
    `

Container running, costs not updating

Hi Matt,

I'm running the container independently, have all connection parameters etc set up just fine.

Logs = blank, no errors reported.

Geofence is set correctly; the charge is showing with a 0 cost - but it just never updates.

Any ideas what could be wrong??

Few things that don't look right:

  • entry point shows 'dotnet,TeslaMateAgile.dll' - is that right? It's highlighted red in the running container
  • It's connected to my right network but does not seem to be picking up an IP. All other containers don't have an issue
  • Container appears to be rebooting itself every few mins

3 Phase 230V calculations are wrong

I just got installed a 3 Phase IT charger for my Tesla Model 3. It is charging at 230V 11.4kW, but if I set phases to 3 in the config, it calculates wrong. I Suspect calculations are for 3 phase 400V TN which is common in europe, but in norway we have 230V IT (only Norway and Albania I believe have this, newer areas in Norway do have 400V though). This causes it to calculate wrong amount of kW and therefor also wrong usage. If I take the calulated amount for 3 phase, and divide it by 1,73 (difference between 400/230), it results in more accurate number compared to TeslaMate. Basically all calculations here will be wrong on IT network with 3 phase.

Would it be possible to add calculations/and config for 230V?

Example from calculations based on 1-2-3 phase:

1 Phase:

  Calculating cost for charges 02/03/2021 00:03:03 UTC - 02/03/2021 04:21:30 UTC
  Calculated cost 13.68 and energy 27.51 kWh for charging process 57
  Mismatch between TeslaMate calculated energy used of 47.65 and ours of 27.51

2-Phase:

  Calculating cost for charges 02/03/2021 00:03:03 UTC - 02/03/2021 04:21:30 UTC
  Calculated cost 27.36 and energy 55.02 kWh for charging process 57
  Mismatch between TeslaMate calculated energy used of 47.65 and ours of 55.02

3-Phase:

  Calculating cost for charges 02/03/2021 00:03:03 UTC - 02/03/2021 04:21:30 UTC
  Calculated cost 41.04 and energy 82.53 kWh for charging process 57
  Mismatch between TeslaMate calculated energy used of 47.65 and ours of 82.53

Configured geofence 'Home' (id: 1) has a cost per unit set which will prevent TeslaMateAgile from working properly

Hi,
I'm seeing this error in the logs.

These are the relevant configs from the yaml file:
- TeslaMate__UpdateIntervalSeconds=300
- TeslaMate__GeofenceId=1
- TeslaMate__EnergyProvider=FixedPrice
- FixedPrice__TimeZone=Etc/UTC # IANA (tz database) time zone code, used for below times
- FixedPrice__Prices__0=23:16-08:16=0.0523 # Night
- FixedPrice__Prices__1=08:16-23:16=0.1818 # Day

This is my geo-fence config in teslamate:
image

I'm running teslmate 1.26.1.

Any help is appreciated.

Thanks!

Multiple providers?

Hi,

I have tibber as provider but in Sweden the energy price consist of two parts, the provider: Tibber and the owner of the network. In my case Ellevio.

I guess I cant combine the fixed proces provider (which would work for the ellevio part) and the tibber prices so that I get the totalt price reported to teslamate?

Unable to Connect to Database Error

Running this:
docker run --env-file /home/pi/TeslaMateAgile/variables.env mattjeanes/teslamateagile

With an variables.env file containing this:

ConnectionStrings__TeslaMate=Server=127.0.0.1;Port=5432;Database=teslamate;User Id=teslamate;Password=teslamate;
TeslaMate__UpdateIntervalSeconds=300
TeslaMate__GeofenceId=1 
TeslaMate__Phases=1
Octopus__RegionCode=J

Returns this:

info: TeslaMateAgile.PriceService[0]
      Price service is starting
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /app/
info: TeslaMateAgile.PriceHelper[0]
      Updating prices
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
      An error occurred using the connection to database 'teslamate' on server 'tcp://127.0.0.1:5432'.
fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'TeslaMateAgile.Data.TeslaMate.TeslaMateDbContext'.
      System.InvalidOperationException: An exception has been raised that is likely due to a transient failure.
       ---> Npgsql.NpgsqlException (0x80004005): Exception while connecting
       ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (111): Connection refused 127.0.0.1:5432
         at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
         at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
         at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
      --- End of stack trace from previous location where exception was thrown ---
         at Npgsql.TaskExtensions.WithCancellation(Task task, CancellationToken cancellationToken)
         at Npgsql.TaskExtensions.WithTimeout(Task task, NpgsqlTimeout timeout)
         at Npgsql.NpgsqlConnector.ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
         at Npgsql.NpgsqlConnector.ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
         at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
         at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
         at Npgsql.ConnectorPool.AllocateLong(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
         at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
         at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         --- End of inner exception stack trace ---
         at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure.
 ---> Npgsql.NpgsqlException (0x80004005): Exception while connecting
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (111): Connection refused 127.0.0.1:5432
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.TaskExtensions.WithCancellation(Task task, CancellationToken cancellationToken)
   at Npgsql.TaskExtensions.WithTimeout(Task task, NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.ConnectorPool.AllocateLong(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
fail: TeslaMateAgile.PriceService[0]
      Failed to update prices
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure.
 ---> Npgsql.NpgsqlException (0x80004005): Exception while connecting
 ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (111): Connection refused 127.0.0.1:5432
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(Exception source)
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.Sockets.Socket.<>c.<ConnectAsync>b__274_0(IAsyncResult iar)
--- End of stack trace from previous location where exception was thrown ---
   at Npgsql.TaskExtensions.WithCancellation(Task task, CancellationToken cancellationToken)
   at Npgsql.TaskExtensions.WithTimeout(Task task, NpgsqlTimeout timeout)
   at Npgsql.NpgsqlConnector.ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.RawOpen(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.ConnectorPool.AllocateLong(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<>c__DisplayClass32_0.<<Open>g__OpenLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(DbContext _, Boolean result, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
   at TeslaMateAgile.PriceHelper.Update() in /src/TeslaMateAgile/PriceHelper.cs:line 45
   at TeslaMateAgile.PriceService.DoWork() in /src/TeslaMateAgile/PriceService.cs:line 58
info: TeslaMateAgile.PriceService[0]
      Waiting 300 seconds until next update

I've confirmed that PostGres is listening on the correct port:

pi@raspberrypi:~/TeslaMateAgile $ sudo netstat -plunt |grep postgres
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      636/postgres        
tcp6       0      0 ::1:5432                :::*                    LISTEN      636/postgres  

I'm running this on a RaspberryPi 4 running Raspian 10 Buster - all of the latest updates applied as of the submission of this issue.

Any ideas?

Failed to update prices - System.ArgumentException: totalHours

Hi,

Likely something lame causing this issue, but I just can't figure out what.
I'm running teslamate and agile on my Synology DS218+ i a docker container. I assume the issue is related to the TimeZone variable or local DS system time somehow?

teslamateagile:
image: mattjeanes/teslamateagile:latest
restart: always
environment:
- DATABASE_USER=teslamate
- DATABASE_PASS=secret
- DATABASE_NAME=teslamate
- DATABASE_HOST=database
- TeslaMate__UpdateIntervalSeconds=300
- TeslaMate__GeofenceId=3
- TeslaMate__EnergyProvider=Energinet
- Energinet__Region=DK1 # See below Energinet regions section
- Energinet__Currency=DKK # See below Energinet currencies section
- Energinet__VAT=1.25 # Optional: VAT multiplier. In this example 25%
- Energinet__FixedPrices__TimeZone=Europe/Copenhagen # Optional: IANA (tz database) time zone code, used for below times
- Energinet__FixedPrices__Prices__0=00:00-00:00=1.42 # Fixed Transport

And I get the follow output when starting teslamate manually:

docker-teslamateagile-1 | info: TeslaMateAgile.PriceService[0]
docker-teslamateagile-1 | Price service is starting
docker-teslamateagile-1 | info: TeslaMateAgile.PriceService[0]
docker-teslamateagile-1 | Using energy provider Energinet
docker-teslamateagile-1 | info: Microsoft.Hosting.Lifetime[0]
docker-teslamateagile-1 | Application started. Press Ctrl+C to shut down.
docker-teslamateagile-1 | info: Microsoft.Hosting.Lifetime[0]
docker-teslamateagile-1 | Hosting environment: Production
docker-teslamateagile-1 | info: Microsoft.Hosting.Lifetime[0]
docker-teslamateagile-1 | Content root path: /app/
docker-teslamateagile-1 | fail: TeslaMateAgile.PriceService[0]
docker-teslamateagile-1 | Failed to update prices
docker-teslamateagile-1 | System.ArgumentException: totalHours (Parameter 'Total hours do not equal 24, currently 0')
docker-teslamateagile-1 | at TeslaMateAgile.Services.FixedPriceService.GetFixedPrices(FixedPriceOptions options) in /src/TeslaMateAgile/Services/FixedPriceService.cs:line 123
docker-teslamateagile-1 | at TeslaMateAgile.Services.FixedPriceService..ctor(IOptions1 options) in /src/TeslaMateAgile/Services/FixedPriceService.cs:line 18 docker-teslamateagile-1 | at TeslaMateAgile.Services.EnerginetService..ctor(HttpClient client, IOptions1 options) in /src/TeslaMateAgile/Services/EnerginetService.cs:line 23
docker-teslamateagile-1 | at lambda_method1(Closure, IServiceProvider, Object[])
docker-teslamateagile-1 | at Microsoft.Extensions.Http.DefaultTypedHttpClientFactory1.CreateClient(HttpClient httpClient) docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.HttpClientBuilderExtensions.AddTransientHelper[TClient,TImplementation](IServiceProvider s, IHttpClientBuilder builder) docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.HttpClientBuilderExtensions.<>c__DisplayClass13_02.b__0(IServiceProvider s)
docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context) docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitDisposeCache(ServiceCallSite transientCallSite, RuntimeResolverContext context) docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass2_0.b__0(ServiceProviderEngineScope scope)
docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
docker-teslamateagile-1 | at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
docker-teslamateagile-1 | at TeslaMateAgile.PriceService.DoWork() in /src/TeslaMateAgile/PriceService.cs:line 57
docker-teslamateagile-1 | info: TeslaMateAgile.PriceService[0]
docker-teslamateagile-1 | Waiting 300 seconds until next update

Feature request? Generic input of dynamic pricing

Hi there,

This is probably a long shot, but is there a way to use this tool to input a tariff dynamically just using like an http endpoint or MQTT or something like that? My utility company (not one of the officially supported ones) uses 'staged' tariffs... Stage 1 is a fixed price for the first 1300 kWh used in a 60 day period, but then it goes up to a different tariff after that, and then it resets after day 60. I am able to get the tariff myself based on my energy usage, and I can publish it through home assistant in a number of different ways, but I'm struggling to find a way to get it into teslamate.

Is there any chance this tool has the ability to do that? If not, is that a feature might consider adding at some point in the future?

Thanks so much!

Feature Request: Octopus Intelligent

Would love to see support added for Octopus Intelligent! Can be dealt with manually for now having a fixed charging cost - but would be better if TeslamateAgile could pull the schedule directly from the Octopus API to account for any unplanned charges.

Create REST endpoint to get price at specific datetime

Would it be possible to create a REST endpoint to get the price per kWh at a specific time? I have a project that charges Teslas based on solar power. This currently works only in Germany as I hard-coded the German spot price as source. If I could use your project as source of the grid price this would help me a lot. Currently I have this issue in my project, which would be a huge hassle to implement, but with having your project as grid price source it would be pretty straight forward. Important would be that you do not update the charge prices as my software calculates a mixed prive based in grid and solar energy.

Very short top-up charges don't get costed.

I have quite a number of charges that are 2-3mins long. The car is just topping up every now and again. These show with a cost of charge 0.00. I get messages in the log for these short duration charges like this:-

  warn:_ TeslaMateAgile.PriceHelper[0] Unable to determine phases for charges
  info: TeslaMateAgile.PriceHelper[0]  Calculated cost 0 and energy 0 kWh for charging process 26

Note the phase warning.

It appears to be caused by this line in your code:

which appears to check there are at least 15 charge rows for any particular charge id otherwise it returns null. The charges with no cost have less than this amount therefore it doesn't calculate the charge cost and generates an error with the erroneous phase message.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.