How-to for importing historical energy/water data from external datasources into the Home Assistant PostgreSQL database so that it can be used in the Energy Dashboard.
Importing historical energy data into Home Assistant is not simple and requires some technical knowledge. It alters the database of Home Assistant so be sure that you always have a recent backup of your Home Assistant data!
- See the generic how-to on how to prepare the source data.
- Download and install: DBeaver https://dbeaver.io/ or pgAdmin https://www.pgadmin.org/
- PostgreSQL python library
pip install psycopg2-binary
- Create a backup of the Home Assistant database
- Disable recorder while making the backup ->
Developer tools/Actions/Action: Recorder:disable
- Disable recorder while making the backup ->
- Stop the Home Assistant core
Developer tools/Actions/Action: Home Assistant Core Integration: Stop
- Start
DBeaverorpgAdmin - On first run configure the database connection
- Database type: PostgreSQL
- Hostname/IP: hostname/ip-number of your PostgreSQL machine
- In case PostgreSQL runs on the same machine as Home Assistant this is the same hostname/ip-number of your Home Assistant instance
- User/password: database user and password
- The database user and password can be found in the connection string in the
configuration.yamlrecorder: db_url: postgresql://<user>:<password>@core-postgresql/homeassistant - Port: 5432 (default)
- The database user and password can be found in the connection string in the
- EXTRA SAFETY STEP: Create a copy of your existing Home Assistant database so that it is possible to quickly move back to the original database.
- Run the
ImportData.pyscript from the Datasources directory to import the generated CSV files and use the following command-line parameters:--db-type postgresql--host HOSTHost as defined in the database connection--user USERUsername as defined in the database connection--password PASSWORDPassword as defined in the database connection--database homeassistant--csv-file CSV_FILE [CSV_FILE ...]Location of the CSV files generated in the source data preparation step, wildcards are allowed--verbose
Example:
python ImportData.py --db-type postgresql --host localhost --user postgres --database homeassistant --csv-file "data\*.csv" --verbose
- Verify by querying the database that it now contains the table
import_data
- Load SQL file
Import Energy data into Home Assistant.sqlfrom the PostgreSQL directory - Validate the schema version of the database (Select table: schema_changes and select the data tab on the right and scroll down to the bottom)
- The script has been tested with schema version 53. With higher versions you should validate if the structure of the
statisticsandstatistics_short_termtables have changed.- Used fields in table
statistics:metadata_id,state,sum,start_ts,created_ts - Used fields in table
statistics_short_term:sum
- Used fields in table
- The script has been tested with schema version 53. With higher versions you should validate if the structure of the
- Run the
Sensors.pyscript from the Database directory to determine the sensor configuration and use the following command-line parameters:--db-type postgresql--host HOSTHost as defined in the database connection--user USERUsername as defined in the database connection--password PASSWORDPassword as defined in the database connection--database homeassistant
Example:
python Sensors.py --db-type postgresql --host localhost --user postgres --database homeassistant
- Select the target sensors from Home Assistant and the corresponding source import name identifiers.
- Determine the unit of measurement of the source data (
Source unit). The script will automatically determine the correct correction factor based on the unit of measurement of the source data. - Determine the
cutoff_new_meterandcutoff_invalid_value. The script will automatically fill in the default values based on the unit of measurement of the target sensor. The different cutoffs are described in the script. - Press
Generate SQLwhich will generate the SQL statements that need to be replaced in theImport Energy data into Home Assistant.sqlSQL file.
- Lookup in the
statistics_metatable the IDs of the sensors (Select table:statistics_metaand select the data tab on the right. You can usefilterto find the ID of the sensor, For instance:statistic_id LIKE '%sensor.gas_meter%')- The names of the sensors can be looked up in the Home Assistant Energy dashboard (Settings -> Dashboards -> Energy).
Example:id statistic_id source unit_of_measurement 6 sensor.gas_meter recorder m³ 7 sensor.electricity_meter_feed_in_tariff_1 recorder kWh 8 sensor.electricity_meter_feed_in_tariff_2 recorder kWh 9 sensor.electricity_meter_feed_out_tariff_1 recorder kWh 10 sensor.electricity_meter_feed_out_tariff_2 recorder kWh 352 sensor.solar_energy_produced_today recorder kWh 450 sensor.battery_energy_feed_in recorder kWh 451 sensor.battery_energy_feed_out recorder kWh 653 sensor.watermeter_quantity_m3 recorder m³
- The names of the sensors can be looked up in the Home Assistant Energy dashboard (Settings -> Dashboards -> Energy).
- Change the script and remove/comment out the lines of the sensors that are not needed. They can be found at the top of the script by looking up the lines where
/* Change */has been added in the SQL statement. - Change the script and update the IDs according to the found IDs in the
statistics_metatable. They can be found at the top of the script by looking up the lines where/* Change */has been added in the SQL statement.- Determine the
correctionvalue based on theunit_of_measurementof the sensor and the used datasource. The unit of measurement of the datasource can be found in the readme of the datasource. The different corrections are described in the script. - Determine the
cutoff_new_meterandcutoff_invalid_valuevalues based on the unit of measurement of the target sensor. The different cutoffs are described in the script.
- Determine the
- Execute the SQL and wait for it to complete. (Please be patient because this can take some time!)
- For the first run the
COMMITstatement at the end of the script can be commented out so that the changes are not written to the database. This makes it possible to test the script and see whether it completes without errors. - In case of an error correct the error and execute the script again. The script will automatically rollback any changes before trying again.
- For the first run the
- Restart/reboot Home Assistant (physically reboot Home Assistant or login using PUTTY-SSH and execute the
rebootcommand) - Validate the imported data in the
Energy Dashboard- After validation, the
homeassistant backupdatabase can be removed. Right-click onhomeassistant backupand selectDelete(DBeaver). Optionally, run theCleanup backup data.sqlSQL script to remove the backup data from thehomeassistantdatabase. The backup data can also be removed by using theImportData.pyscript with the--cleanup-backupoption. - In case of issues, the changes can be rolled back with the
Restore backup data.sqlSQL script. This script will revert the changes made by theImport Energy data into Home AssistantSQL script. Make sure not to wait too long before performing this step, as the Home Assistant recorder will start updating the database with new data, making the backup outdated.
- After validation, the
- Enjoy :-)