
Combining a grid cleanliness score from the WattTime API and an inexpensive smart bulb, I’ll walk through the creation of the "grid bulb," which visualizes how dirty the local electric grid is at any moment. Knowledge is power and knowing when our local energy production is cleaner empowers us to choose to reduce pollution and carbon emissions by deciding when to consume some of our electricity. A conversation with Geoff Hancock at WattTime inspired this project.
Before we get started you should know that I get a commission for any items purchased through the affiliate links in this post. That commission helps to support the creation of future posts like this one.
Whenever you turn on an electrical device plugged into the wall, you increase the demand on the power grid by a small amount. That demand is met by a power plant increasing its production to add the necessary energy to the grid. If that plant burns coal, plugging in your device causes more carbon emissions than if that plant is a wind farm or even a natural gas plant. The more energy your device draws, the bigger the difference. So by knowing when your grid is cleanest, you can reduce your emissions just by choosing when to do something like charging your electric vehicle.
But how do we know when our grid is cleanest? I’ve used an innovative API provided by WattTime. WattTime is a nonprofit organization that set out to answer the question, "How clean is the electricity I’m using right now?" They’ve answered that question for the United States, Canada, and other countries that mandate emissions reporting by power plants. They are currently working on expanding that ability to the rest of the world through their partnership with ClimateTrace.
The WattTime API scores each grid on a scale of 0–100, where 0 is the cleanest and 100 is the dirtiest it gets. This is the real-time data that will power our "grid bulb."
I’m using this $7 light bulb, which like most cheap smart devices, is connected to the Tuya platform. These bulbs expose a local API to communicate directly with them from any computer on our LAN, which means we do not need a smart hub or any other smart devices for this to work. If you purchase the bulb through a link in this article I may receive a
Combining these two APIs and a sprinkling of Python, we’ll create a lamp that shows the current grid cleanliness, with green being the cleanest and red representing the dirtiest.
The WattTime API
The WattTime API is straightforward to use, and the documentation provides excellent examples. While the Data Plan page is a bit confusing, I found that a free plan allows access to current local grid conditions.
Here is what we will do to get the emissions score:
- Register for the WattTime API.
- Authenticate.
- Determine our latitude and longitude with Google Maps.
- Get real-time Emissions.
Register for the WattTime API
You register for the API through the API itself, which is very efficient. Remember to replace USER_NAME
, PASSWORD
, EMAIL
, and ORG
with your information.
import requests
params = {'username': 'THE USER_NAME YOU WANT',
'password': 'THE PASSWORD YOU WANT',
'email': 'YOU EMAIL',
'org': 'ORG NAME'}
register_url = 'https://api2.watttime.org/v2/register'
rsp = requests.post(register_url, json=params)
print(rsp.text)
If all goes well, you will get a success message showing that you have successfully registered for the API.
{"user":"benbogart","ok":"User created"}
If you get an error, adjust your parameters accordingly. In the case below, we would have to pick a different username and try again.
{"error":"That username is taken. Please choose another."}
Authenticate
The WattTime API uses HTTP basic authentication to exchange your username and password for an access token. This, too, is very simple, usingHTTPBasicAuth
from requests.auth
.
from requests.auth import HTTPBasicAuth
login_url = 'https://api2.watttime.org/v2/login'
auth = HTTPBasicAuth(params['username'], params['password']))
rsp = requests.get(login_url, auth=auth)
token = rsp.json()['token']
print(rsp.json())
Inspect the response to make sure you received a token. If so, we can move on.
Determine our Latitude and Longitude with Google Maps
I’ll use Bloomington, IN City Hall for this example. You should use your address.
Search for your address, then right-click, two-finger click, or ctrl+click on the red pin on the map. This will bring up a dialog box that shows the latitude and longitude of the pin. Click on the latitude and longitude, which will copy them to your clipboard.

We now assign these values to latitude
and longitude
.
lat = 39.17100708872063
long = -86.53651334662412
Get Realtime Emissions
Now we have everything we need to get real-time emissions for our region.
index_url = 'https://api2.watttime.org/index'
params = {'latitude': lat, 'longitude': long}
rsp=requests.get(index_url, headers=headers, params=params)
print(rsp.text)
Which returns something like:
{
"freq": "300",
"ba": "MISO_INDIANAPOLIS",
"percent": "57",
"point_time": "2021-07-31T17:00:00Z"
}
freq
shows how often the data is updated.ba
is the region.percent
is the current pollution value for our region.point_time
is the time the score was last updated.
We are going to use percent
to update the color of our smart bulb.
Connecting to the Smart Bulb
The directions here are for connecting to a wifi smart bulb designed for the Tuya platform. The vast majority of low-cost smart devices use this platform, including any bulb that uses the Smart Life app.
These bulbs expose an API that allows us to directly control them over the local network. Unfortunately, we need to jump through some hoops to get the API key for the bulb. Also, these bulbs generally only work on 2.4Ghz networks.
Tuya uses a smartphone application to connect smart devices to the local wifi network and register them on the Tuya network. Registering the device on the Tuya platform is what allows us to retrieve the bulb’s API key, so while we will not be using the Tuya platform nor the Smart Life app to control the bulb, we still must register the bulb to get the API key to access the bulb’s API.
Here are the steps we will take to connect to our bulb.
- Download and set up the Smart Life app.
- Connect the bulb to our wifi and register it in the Smart Life app.
- Get the bulb’s API key through the Tuya developer platform.
- Connect to the bulb.
Download and set up the Smart Life app
Connect the bulb to our wifi and register it in the Smart Life app
Most modern wifi networks use both the 2.4Ghz and 5Ghz channels on a single network id. Our inexpensive bulb can only use the 2.4Ghz network, and it gets confused when using the default EZ pairing method from the Smart Life App. We will pair it with the "AP Mode," which seems to solve this problem. This method is a bit longer than the "EZ" method, but that’s the price we pay for being cheap.
- From the Smart Life app, tap "Add Device" or the + icon in the top left of the screen.
- From the "Add Manually" tab, select Lighting and the kind of bulb you purchased. I selected "Light Source (Wi-Fi)."

- Change the pairing mode. The following screen will ask us to reset the device. Before you do that, go to the upper right corner and tap "EZ Mode." Then, from the resulting menu, select "AP Mode."

- Next, reset the bulb two times in a row: Turn it off and on 3 times, wait for the bulb to start blinking rapidly, turn it off and on again, and wait for it to start blinking slowly.
- When blinking slowly, the bulb creates a wifi hotspot. The Smart Life app will direct you to go to your wifi settings and connect to the bulb.

- Return to the app and complete the pairing. Now you should see your bulb in the Smart Life app. This is a good time to play around with the app to see what your bulb can do.

Get the bulb’s API key through the Tuya developer platform
Now that the bulb is connected to our local network and we can control it from our phone, the next step is to get the device id and extract the API key from the Tuya developer platform.
Part 1: Tuya Setup
- Create a free Tuya developer account at iot.tuya.com. (select "sign up" below the sign-in box).
- You can skip the organization type dialog.
- After logging in, select "Cloud" in the left navigation bar. The first time you do this, Tuya will ask you to pick a plan. Select the free "Trial Edition" and check out. You will have to check out as if you were buying the plan, but you won’t be charged anything and you do not have to supply any payment information.

- Return to the IoT platform and select Cloud again. This time select "Create Cloud Project."

- Fill in the Create Cloud Project dialog box, making sure to select "Smart Home" as the development method.

- On the next screen, verify that "Smart Home Device Management," "Authorization," and "Smart Home Family Management" are listed under Selected API Products and Click Authorize.

- Following this step, Tuya will take you to your new project. Go to the Devices Tab and select "Link Tuya App Account."

Tuya will show a QR code which we need to scan with our Smart Life app. In the Smart Life app on your phone, go to "Me" and the scan icon in the top right of the screen. This will bring up a QR code reader.

- After you scan the QR code, click "Confirm Login," and your devices will appear in the Tuya IoT Platform Devices tab of the IoT Platform.

Don’t close this page yet. We will need two more pieces of information from here, but we are done with the account setup.
Part 2: Get the API key
Now everything is in place for us to extract the API key for our light bulb. I found the tinytuya
package to have both the most straightforward way of extracting the API key and connecting to the bulb.
- Install
tinytuya
pip install tinytuya
- Get device Id: To log in to the API, we will need the id of any smart device associated with the account. Since we only have one bulb, we’ll need to get its device id. We can do this with
tinytuya
from the command line.
$ python -m tinytuya scan

This polls ports 6666 and 6667 of devices on our local network and returns any Tuya devices. We can see from the scan above that the Device ID is listed in blue.
- Navigate to the directory in which you will create your python script. The following wizard generates a JSON file that must be saved in the same directory as your script.
- Run the following on the command line, then read on for where to retrieve each requested item.
python -m tinytuya wizard
- Enter your API Key (aka Client ID) and API Secret (aka Client Secret) from the Tuya project page.

- Enter your device ID from the tiny tuya scan in the previous step
- Enter the closest region from the options in the list.
The result will look something like this.

Ok, all the hard stuff is done! We don’t need the Tuya API for anything else, but you will need to repeat the above steps if you ever remove the bulb from your Smart Life app.
Now for the magic.
Connect to the Bulb
We have everything we need to connect directly to the bulb. The easiest way to see it all in one place is to repeat the device scan now that we have connected to the Tuya API.
- Repeat device scan either at the command prompt…
$ python -m tinytuya scan
… or in a Jypyter Notebook.
import tinytuya
intytuya.scan()
This time the scan gives us everything we need to connect to our bulb, including the local API key.
Note: This requires access to the devices.json file generated by
tinytuya wizard
. Make sure you either run this command from the same directory or copy devices.json to your working directory.

- In your notebook or code editor, connect to the bulb by replacing the details of your bulb in the code below.
bulb = tinytuya.BulbDevice(dev_id='DEVICE ID',
address='ADDRESS',
local_ley='LOCAL KEY')
bulb.set_version(VERSION)
print(f'set status result {bulb.status()}')
If the connection is successful, you will get a response that looks something like this:
set status result {'devId': '42313382e09806b2e707', 'dps': {'20': True, '21': 'white', '22': 1000, '23': 1000, '24': '000003e803e8', '25': '000e0d0000000000000000c80000', '26': 0}}
- Play around a little with the bulb. Feel free to laugh out loud when this works.
Try turning the bulb on:
bulb.turn_on()
Turn the bulb off:
bulb.turn_off()
Set the brightness on a scale of 0–100:
bulb.set_brightness_percentage(25)
Set the color of the bulb:
bulb.set_colour(0,255,255)
You can find a full list of the tinytuya
supported commands in the tinytuya
documentation.
Visualize the WattTime score on the Smart Bulb
All that is left is to use the smart bulb to display the WattTime grid dirtiness score on the bulb. I’ve chosen to use red for dirtiest and green for cleanest because I think this is intuitive and because the math is easy.
You can find the code below or in the Github repository. Save the file as gridbulb.py
and run it with python gridbulb.py
. The script will run until you stop it with ctrl
+c
. Don’t forget to replace the fields in square brackets with your information.
NOTE: You can run the script in the background by appending
&
. This will fork the script giving it its own process id. If you haven’t done this before I recomend some light reading on the subject here.Conclusion
While this article is about visualizing how clean your local energy grid is on a smart bulb, each component can be applied to other tasks. You could connect a smart switch to your EV charger, so your car only charges on the cleanest energy. You could visualize a BitCoin volatility score on your smart bulb. The possibilities are only limited by your imagination.
Connecting to a cheap smart bulb requires a significant amount of effort, but we only have to jump through the hoops once. Still, if I had to do this again, I might consider spending a few extra dollars for a bulb that would connect directly to my Samsung Smart Hub. Hopefully, though, using a $7 bulb makes this accessible to more people.
Now go use your smart bulb to do some good.
Resources
- GitHub repository for this post
- WattTime API documentation
tinytuya
documentation- $7 smart bulb on amazon