Skip to content

Instantly share code, notes, and snippets.

@liam-russell
Last active May 6, 2024 23:30
Show Gist options
  • Save liam-russell/a76a1c40427968dad41455ed8644f84e to your computer and use it in GitHub Desktop.
Save liam-russell/a76a1c40427968dad41455ed8644f84e to your computer and use it in GitHub Desktop.
TP-Link Kasa Smart Plug - get energy consumption statistics as a CSV file

TP-Link Kasa Smart Plug - get energy consumption statistics as a CSV file

Background

The TP Link Kasa smart switches log energy consumption data over time, however the app is very limited and won't let you get out data, graph it or see historical usage. This script extracts and saves to a CSV file.

The python-kasa library is used to communicate with the Kasa switch.

Requirements

  • Python must be installed
  • You must be on the same wifi network as the Kasa switch
  • The Kasa switch must be set up

Steps

  1. Run pip install python-kasa python-dateutil to install dependencies
  2. Download the TpLinkKasa-GetEnergyConsumptionAsCsv.py to a folder on your computer
  3. Edit the file and set the date range you want to get energy consumption data for
  4. Run python TpLinkKasa-GetEnergyConsumptionAsCsv.py in the folder with the python script downloaded
  5. A file called output.csv will be created. You can import this file into Excel or Google Sheets
import asyncio
import kasa
import datetime
from dateutil.relativedelta import relativedelta
import csv
# SET DATE RANGE HERE
start = datetime.date(2023, 3, 4)
end = datetime.date(2023, 5, 4)
async def run():
found_devices = await kasa.Discover.discover()
with open('output.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
writer.writerow(['Device', 'Date', 'Usage (kWh)'])
for device_key in found_devices:
dev = found_devices[device_key]
await dev.update()
month_offset = 0
month_diff = (12 * (end.year - start.year)) + \
(end.month - start.month)
while (month_offset <= month_diff):
current_start = start + relativedelta(months=month_offset)
print(
f'Getting month {current_start.month} for year {current_start.year}')
result = await dev.get_emeter_daily(year=current_start.year, month=current_start.month)
print(f'We got {result.__len__()} days(s) of usage statistics')
for result_key in result:
if (month_offset == 0 and result_key < start.day):
continue
if (month_offset == month_diff and result_key > end.day):
continue
writer.writerow(
[dev.alias, f'{result_key}/{current_start.month}/{current_start.year}', result[result_key]])
month_offset = month_offset + 1
asyncio.run(run())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment