Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Coernel82 committed Dec 1, 2024
1 parent b885c87 commit d7d8b6d
Show file tree
Hide file tree
Showing 39 changed files with 5,655 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Ignoriere den __pycache__ Ordner
__pycache__/

# Ignoriere das Verzeichnis dont publish
dontpublish/

# Ignoriere die settings.json Datei
backend/data/settings.json

cache/
*cache*

# Ignoriere die Datei Zugangsdaten.py
Zugangsdaten.py


SmartCharge.code-workspace
settings.json
Abhängigkeit Temperatur und realie Reichweite.ods
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) [2024] [Cornelius Berger]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Binary file added assets/project_graphic.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
123 changes: 123 additions & 0 deletions backend/data/correction_factor_log.txt

Large diffs are not rendered by default.

16 changes: 16 additions & 0 deletions backend/data/loadpoint_assignments.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"assignments": [
{
"LOADPOINT_ID": 0,
"CAR_NAME": "Opel"
},
{
"LOADPOINT_ID": 1,
"CAR_NAME": "VW"
},
{
"LOADPOINT_ID": 2,
"CAR_NAME": "Tesla"
}
]
}
94 changes: 94 additions & 0 deletions backend/data/settings_example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
{
"OneCallAPI": {
"API_KEY": "YOUR_API_KEY",
"LATITUDE": 51.534,
"LONGITUDE": 7.454
},
"Home": {
"HomeBatteries": {
"0": {
"BATTERY_LOADING_ENERGY": 3300,
"BATTERY_PURCHASE_PRICE": 5000,
"BATTERY_PURCHASE_YEAR": 2024,
"BATTERY_MAXIMUM_LOADING_CYCLES_LIFETIME": 10000,
"BATTERYSYSTEM_EFFICIENCY": 0.93,
"BATTERY_RESIDUAL_SOC": 25,
"BATTERY_DEGRADATION": 0.02,
"BATTERY_INVERTER_LIFETIME_YEARS": 20,
"BATTERY_INVERTER_PRICE": 5000
}
}
},
"EVCC": {
"EVCC_API_BASE_URL": "http://192.168.178.28:7070 - your evcc url"
},
"InfluxDB": {
"INFLUX_BASE_URL": "http://192.168.178.28:8086/ - your influx url",
"INFLUX_ORGANIZATION": "zu Hause - your organization",
"INFLUX_BUCKET": "evcc - or whatever you named your evcc bucket",
"INFLUX_LOADPOINT": "W\u00e4rmepumpe",
"INFLUX_ACCESS_TOKEN": "your-influx-token",
"TIMESPAN_WEEKS": 4,
"TIMESPAN_WEEKS_BASELOAD": 4
},
"Loadpoints": [
{
"LOADPOINT_ID": 0,
"CHARGER_ENERGY": 7200,
"MINIMUM_CHARGE_POWER": 1380,
"default": true
},
{
"LOADPOINT_ID": 1,
"CHARGER_ENERGY": 11000,
"MINIMUM_CHARGE_POWER": 2000
}
],
"Cars": [
{
"CAR_NAME": "Opel",
"BATTERY_CAPACITY": 50000,
"BATTERY_YEAR": 2021,
"DEGRADATION": 0.02,
"CONSUMPTION": 16000,
"BUFFER_DISTANCE": 20,
"default": true
},
{
"CAR_NAME": "VW",
"BATTERY_CAPACITY": 77000,
"BATTERY_YEAR": 2020,
"DEGRADATION": 0.015,
"CONSUMPTION": 18000,
"BUFFER_DISTANCE": 20
}
],
"House": {
"ENERGY_CERTIFICATE": 7000,
"HEATED_AREA": 222,
"INDOOR_TEMPERATURE": 21,
"MAXIMUM_PV": 7200,
"SUMMER_THRESHOLD": 15,
"SUMMER_THRESHOLD_HYSTERESIS": 1.5,
"note on hysteresis": "the hysteresis will be applied as + and - to the threshold",
"correction_factor_winter": 0.0046,
"correction_factor_summer": 0.0046,
"correction_factor_radiation": 0.8,
"adjustment_rate": 0.2,
"info:": "adjustment rate must be between 0 and 1",
"integrated_devices": {
"heatpump": {
"POWER": 4000,
"COP": 4.5
}
}
},
"EnergyAPIs": {
"SOLCAST_API_URL": "https://api.solcast.com.au/rooftop_sites/YOUR_SITE_ID/forecasts?format=json&api_key=YOUR_API_KEY&period=PT60M&hours=24",
"TIBBER_API_URL": "https://api.tibber.com/v1-beta/gql",
"TIBBER_HEADERS": {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_TIBBER_API_KEY"
}
}
}
51 changes: 51 additions & 0 deletions backend/data/usage_plan.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"Opel": {
"recurring": [
{
"description": "to work - optional",
"departure": "Sunday",
"departure_time": "13:30",
"distance": 290,
"return": "Sunday",
"return_time": "15:00"
},
{
"departure": "Tuesday",
"departure_time": "16:00",
"distance": 25,
"return": "Tuesday",
"return_time": "17:00"
}
],
"non_recurring": [
{
"description": "This is an example for a non-recurring trip far in the future - otherwise it will be delted automatically",
"departure": "2055-10-15",
"departure_time": "09:00",
"return": "2055-10-17",
"return_time": "18:00",
"distance": 199
}
]
},
"VW": {
"recurring": [
{
"departure": "Monday",
"departure_time": "12:05",
"distance": 60,
"return": "Monday",
"return_time": "17:00"
},
{
"departure": "Tuesday",
"departure_time": "12:59",
"distance": 12,
"return": "Tuesday",
"return_time": "12:05"
}
],
"non_recurring": []

}
}
139 changes: 139 additions & 0 deletions backend/evcc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# evcc.py

# This project is licensed under the MIT License.

# Disclaimer: This code has been created with the help of AI (ChatGPT) and may not be suitable for
# AI-Training. This code ist Alpha-Stage

import datetime
import logging
import requests
import json
import os
import initialize_smartcharge

# Logging configuration with color scheme for debug information
logger = logging.getLogger('smartCharge')
RESET = "\033[0m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
CYAN = "\033[96m"
GREY = "\033[37m"

EVCC_API_BASE_URL = initialize_smartcharge.settings['EVCC']['EVCC_API_BASE_URL']

def get_evcc_state():
logging.debug(f"{GREEN}Retrieving EVCC state from {EVCC_API_BASE_URL}/api/state{RESET}")
try:
response = requests.get(f"{EVCC_API_BASE_URL}/api/state")
response.raise_for_status() # Check for HTTP errors
evcc_state = response.json()
# logging.debug(f"{GREY}Response from EVCC API: {evcc_state}{RESET}")
return evcc_state
except requests.RequestException as e:
logging.critical(f"{RED}Error retrieving the EVCC state: {e}{RESET}")
# stop the whole program if the EVCC state cannot be retrieved as this is vital
raise SystemExit

# Function to send the calculated state of charge to EVCC
def set_evcc_soc(car_name, target_soc, time_windows):
current_time = datetime.datetime.now().astimezone()
in_time_window = False
for window in time_windows:
window_start = window['startsAt']
# Ensure window_start is datetime object
if isinstance(window_start, str):
window_start = datetime.datetime.fromisoformat(window_start)
price_end = window_start + datetime.timedelta(hours=1)
window_start = window_start.astimezone()
price_end = price_end.astimezone()
if window_start <= current_time < price_end:
in_time_window = True
break
if in_time_window:
logging.debug(f"{CYAN}Within cheapest time window. Setting target SoC to {target_soc:.2f}%{RESET}")
# Bevor wir den minSoC setzen, lesen wir den aktuellen Wert und cachen ihn
get_evcc_minsoc(car_name)
# Send target SoC to EVCC
EVCC_API_BASE_URL = initialize_smartcharge.settings['EVCC']['EVCC_API_BASE_URL']
url = f"{EVCC_API_BASE_URL}/api/vehicles/{car_name}/minsoc/{int(target_soc)}"
try:
response = requests.post(url)
if response.status_code == 200:
logging.debug(f"{GREEN}Successfully set target SoC to {target_soc:.2f}%{RESET}")
else:
logging.error(f"{RED}Failed to set target SoC. Response code: {response.status_code}{RESET}")
except Exception as e:
logging.error(f"{RED}Error setting target SoC: {e}{RESET}")
else:
logging.debug(f"{CYAN}Not within cheapest time window. Not setting target SoC.{RESET}")


def get_evcc_minsoc(car_name):
logging.debug(f"{GREEN}Retrieving EVCC minSoC for {car_name} from {EVCC_API_BASE_URL}/api/state{RESET}")
cache_file = "evcc_minsoc_cache.json"
lock_file = "evcc_minsoc_cache.lock"

# Wenn Lockfile existiert, nicht überschreiben
if os.path.exists(lock_file):
logging.debug(f"{YELLOW}Lockfile {lock_file} exists. Not overwriting minSoC cache.{RESET}")
return None

try:
# API-Request an EVCC
response = requests.get(f"{EVCC_API_BASE_URL}/api/state")
response.raise_for_status() # Prüfe auf HTTP-Fehler
evcc_state = response.json()
# logging.debug(f"{GREY}Response from EVCC API: {evcc_state}{RESET}")

# Suche nach dem Fahrzeug mit dem Namen car_name in der API-Antwort
vehicles = evcc_state.get('result', {}).get('vehicles', {})
logging.debug(f"{GREEN}Vehicles retrieved: {vehicles}{RESET}")

# Überprüfe, ob car_name in vehicles vorhanden ist
if car_name in vehicles:
vehicle = vehicles[car_name]
min_soc = vehicle.get('minSoc')
logging.debug(f"{GREEN}Retrieved minSoC value for {car_name}: {min_soc}{RESET}")

if min_soc is not None:
logging.debug(f"{GREEN}Caching vehicle minSoC: {min_soc}{RESET}")
try:
with open(cache_file, "w") as f:
json.dump({"min_soc": min_soc}, f)
logging.debug(f"{GREEN}minSoC successfully cached in {cache_file}{RESET}")
# Lockfile erstellen
with open(lock_file, 'w') as f:
f.write('locked')
logging.debug(f"{GREEN}Created lockfile {lock_file}{RESET}")
except Exception as file_error:
logging.error(f"{RED}Error writing to cache file: {file_error}{RESET}")
return min_soc
else:
logging.error(f"{RED}The minSoC could not be found for vehicle {car_name}{RESET}")
return None
else:
logging.error(f"{RED}No vehicle with the name {car_name} found in the API response{RESET}")
return None

except requests.RequestException as e:
logging.error(f"{RED}Error retrieving the EVCC minSoC: {e}{RESET}")
return None

def set_upper_price_limit(upper_limit_price_battery):
"""
Sets the upper price limit for battery charging via API.
"""
if upper_limit_price_battery is not None:
post_url = f"{EVCC_API_BASE_URL}/api/batterygridchargelimit/{upper_limit_price_battery}"
logging.debug(f"{GREY}Setting upper price limit via URL: {post_url}{RESET}")
try:
response = requests.post(post_url)
response.raise_for_status()
logging.info(f"{GREEN}Successfully set upper price limit: {upper_limit_price_battery:.4f} Euro{RESET}")
except Exception as e:
logging.error(f"{RED}Failed to set upper price limit: {e}{RESET}")
else:
logging.warning("Upper limit price is None. Cannot set the price limit.")
Loading

0 comments on commit d7d8b6d

Please sign in to comment.