Introduction
Many people believe that unplugging their TV overnight saves electricity, but the reality is more nuanced. While unplugging does save energy, modern TVs often consume power even when turned off through standby mode. In this tutorial, you'll learn how to measure your TV's actual power consumption and set up automated power management using Python and smart plugs. This approach gives you precise control over your energy usage and helps you understand exactly how much power your TV consumes in different states.
Prerequisites
- Python 3.7 or higher installed on your computer
- A smart plug that supports Wi-Fi and can be controlled via API (such as TP-Link Kasa or Xiaomi Smart Plug)
- Basic understanding of Python programming and command-line interfaces
- Access to your home Wi-Fi network
- TV with a power cable that can be controlled by the smart plug
Step-by-Step Instructions
Step 1: Set Up Your Smart Plug
1.1 Install the Smart Plug App
Download and install the companion app for your smart plug (e.g., TP-Link Kasa or Xiaomi Home) on your smartphone. This app will help you configure the plug and get its unique device ID.
1.2 Connect to Your Wi-Fi Network
Follow the manufacturer's instructions to connect your smart plug to your home Wi-Fi network. The plug will typically appear as a new device in your app, and you'll need to note its IP address or device ID for later use.
Step 2: Install Required Python Libraries
2.1 Create a Virtual Environment
It's good practice to create a virtual environment for this project to avoid conflicts with other Python packages.
python -m venv tv_power_env
source tv_power_env/bin/activate # On Windows: tv_power_env\Scripts\activate
2.2 Install Required Packages
Install the necessary Python packages for controlling smart plugs and measuring power consumption.
pip install kasa
pip install pandas
pip install matplotlib
Step 3: Identify Your Smart Plug
3.1 Discover Connected Devices
Use the Kasa library to discover your smart plug on the network. This will help you identify the device's unique identifier.
from kasa import Discover
# Discover all devices on the network
devices = await Discover.discover()
for device in devices:
print(f"Device: {device}")
print(f"IP: {device.host}")
print(f"Device ID: {device.device_id}")
3.2 Get Device Details
Once you've identified your plug, get more detailed information about its capabilities.
from kasa import SmartPlug
# Replace with your plug's IP address
plug = SmartPlug("192.168.1.100")
await plug.update()
print(f"Plug Model: {plug.model}")
print(f"Plug Alias: {plug.alias}")
print(f"Power Consumption: {plug.current_consumption()} watts")
Step 4: Create Power Monitoring Script
4.1 Build the Monitoring Function
Create a script that can measure power consumption and control the plug automatically.
import asyncio
import time
from kasa import SmartPlug
import pandas as pd
async def monitor_power_consumption(plug_ip, duration_minutes=30):
"""Monitor power consumption of a device for a specified duration"""
plug = SmartPlug(plug_ip)
await plug.update()
# Create a list to store measurements
measurements = []
# Monitor for specified duration
start_time = time.time()
while time.time() - start_time < duration_minutes * 60:
await plug.update()
current_watts = plug.current_consumption()
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
measurements.append({
'timestamp': timestamp,
'watts': current_watts,
'device': plug.alias
})
print(f"{timestamp}: {current_watts} watts")
await asyncio.sleep(60) # Take measurement every minute
return measurements
4.2 Create Power Control Functions
Add functions to turn the plug on and off programmatically.
async def turn_on_plug(plug_ip):
"""Turn on the smart plug"""
plug = SmartPlug(plug_ip)
await plug.update()
await plug.turn_on()
print("Plug turned ON")
async def turn_off_plug(plug_ip):
"""Turn off the smart plug"""
plug = SmartPlug(plug_ip)
await plug.update()
await plug.turn_off()
print("Plug turned OFF")
Step 5: Implement Automated Power Management
5.1 Create an Automated Schedule
Set up a script that automatically turns off your TV during non-use hours to save energy.
import datetime
async def smart_power_schedule(plug_ip, start_hour=22, end_hour=7):
"""Automatically turn off plug during specified hours"""
current_hour = datetime.datetime.now().hour
if start_hour <= current_hour <= end_hour:
await turn_off_plug(plug_ip)
else:
await turn_on_plug(plug_ip)
print(f"Smart schedule: {"OFF" if start_hour <= current_hour <= end_hour else "ON"}")
5.2 Create a Complete Monitoring Script
Combine all functions into a complete monitoring solution.
async def main():
plug_ip = "192.168.1.100" # Replace with your plug's IP
# Monitor power consumption
print("Starting power monitoring...")
measurements = await monitor_power_consumption(plug_ip, duration_minutes=5)
# Save measurements to CSV
df = pd.DataFrame(measurements)
df.to_csv('tv_power_consumption.csv', index=False)
print("Measurements saved to tv_power_consumption.csv")
# Turn off plug for energy saving
await turn_off_plug(plug_ip)
# Turn on plug when needed
await turn_on_plug(plug_ip)
# Run the main function
asyncio.run(main())
Step 6: Analyze Your Results
6.1 Create Power Consumption Charts
Use matplotlib to visualize your power consumption data.
import matplotlib.pyplot as plt
# Read data from CSV
df = pd.read_csv('tv_power_consumption.csv')
# Convert timestamp to datetime
df['timestamp'] = pd.to_datetime(df['timestamp'])
# Plot power consumption
plt.figure(figsize=(12, 6))
plt.plot(df['timestamp'], df['watts'], marker='o')
plt.title('TV Power Consumption Over Time')
plt.xlabel('Time')
plt.ylabel('Power Consumption (Watts)')
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig('tv_power_consumption.png')
plt.show()
6.2 Calculate Energy Savings
Calculate the potential energy savings from your smart plug setup.
# Calculate average power consumption
avg_watts = df['watts'].mean()
print(f"Average power consumption: {avg_watts:.2f} watts")
# Calculate daily energy consumption (in kWh)
# Assuming 24 hours of operation
kwh_per_day = (avg_watts * 24) / 1000
print(f"Daily energy consumption: {kwh_per_day:.4f} kWh")
# Calculate cost savings (assuming $0.12 per kWh)
cost_per_day = kwh_per_day * 0.12
print(f"Daily cost: ${cost_per_day:.4f}")
Summary
This tutorial demonstrates how to use Python and smart plugs to monitor and manage your TV's power consumption effectively. By creating automated control systems, you can achieve better energy savings than simple unplugging. The approach allows you to measure exactly how much power your TV consumes in standby mode and implement smart scheduling to minimize energy waste. This method provides precise data and automation capabilities that go beyond basic power-saving advice, helping you make informed decisions about your energy usage.