Smarthome Auditing - Logging Kasa Devices to Splunk

Home automation is just the greatest thing ever, isn't it? Because who doesn't love the idea of being able to control their entire house with the swipe of a finger on a tiny screen? I mean, why bother actually getting up and flipping a light switch when you can just tap a button on your phone? And don't even get me started on the energy savings - who cares about the environment when you can save a few cents on your electricity bill? Oh, and let's not forget about the added security benefits - because nothing says "I feel safe in my own home" like being alerted every time a fly lands on your windowsill. Overall, home automation is a total game-changer and everyone should definitely get on board.

In this blog post I explore how home automation devices can be logged and audited to make the output more vendor agnostic (i.e not having to use the Kasa app to read the power usage of your devices, and collecting more data over time)

First, using the Pypi kasa library we can poll Kasa devices on the network.

from kasa import SmartPlug

ip = '192.168.1.1' # Change this to a real IP or use the kasa discover feature
item = SmartPlug(ip)
await item.update()  # Request the update

alias = item.alias
on = item.is_on
off = item.is_off
rssi = item.rssi
watts = await item.current_consumption()

print(watts)

Being able to query and collect this data is powerful in itself. In this Python script we could do all sorts of automation. For example: Turning off a device when another device turns on to prevent the breaker from tripping.

Next, we'll send this information to Splunk using the HEC (HTTPS Event Collector)

headers = {'Authorization': f'Splunk {config["hec_token"]}'}
    r = requests.request('post',config['hec_address'],headers=headers,data=data,verify=False)

We can also collect the current weather to later compare temperature and electric usage.

import requests
import asyncio

requests.packages.urllib3.disable_warnings()

config = {
    'breaker_max':1650, #value in watts that when exceeded the system should start shutting down things to prevent breaker tripping
    'weather_api_key':'xxx',
    'weather_latitude':'xxx',
    'weather_longitude':'xxx',
    'hec_address':'https://192.168.1.x:8088/services/collector/raw',
    'hec_token':'xxx',
}

async def sendtoHEC(config,data):
    headers = {'Authorization': f'Splunk {config["hec_token"]}'}
    r = requests.request('post',config['hec_address'],headers=headers,json=data,verify=False)
    return

def getCurrentWeather(config):
    r = requests.request('get',f'https://api.openweathermap.org/data/2.5/weather?lat={config["weather_latitude"]}&lon=-{config["weather_longitude"]}&units=imperial&appid={config["weather_api_key"]}')
    current_weather_json = r.json()
    weather = current_weather_json['main']
    weather['weather'] = current_weather_json['weather'][0]['main']
    weather['weather_description'] = current_weather_json['weather'][0]['description']
    return weather

async def getWeather():
    while True:
        now_weather = getCurrentWeather(config)
        await sendtoHEC(config,now_weather)
        await asyncio.sleep(120)

asyncio.run(getWeather())

You'll need an Openweathermap API key for this. This script is optional but Openweather does provide useful information which is helpful to have in Splunk:

Create one HTTP Event Collector for each index that you want to ingest to. The HEC Token dictates which index our Splunk script writes to. As long as our script runs and writes, Splunk will ingest that data. It does make sense to custom field extractions so that the data is parsed consistently.

It makes sense to set up one Smart Plug per device, as we can then track the energy usage more discretely. You can continue to rename these Kasa devices in the app and the name will reflect here in the data model as well.

All in all, we can then create nice dashboards such as this one, which is definetly more detailed than the Kasa app:

We can now query, collect and display our Kasa Smarthome device output in a meaningful way.

I will leave you with this haiku about IoT:

IoT devices hum
Connected to the internet
Smart homes come alive