Skip to content

Instantly share code, notes, and snippets.

@fvdbosch

fvdbosch/energy.py Secret

Created Mar 15, 2021
Embed
What would you like to do?
Live Energy Monitor
#!/usr/bin/env python3
import math
import time
import unicornhathd
import urllib.request
import json
# Rotate the display to the desired orientation
unicornhathd.rotation(-90)
unicornhathd.brightness(1.0)
# Colours for positive and negative measurements
bar_colour_down = [64, 0, 128]
bar_colour_up = [0, 128, 0]
# P1 Meter API
url = "http://192.168.0.221/api/v1/data"
# Store measurements
measurements = []
leds = []
# Get the data from the API and parse the desired value
def getDataFromP1(url):
response = urllib.request.urlopen(url)
data = response.read()
values = json.loads(data)
return values["active_power_w"]
# Store the measurements in an array
def updateMeasurements(array):
if len(array) >= 16:
array.pop(0)
array.append(getDataFromP1(url))
# Convert the measurements to number of LEDs to light up
def transformMeasurements(arrayIn, arrayOut):
arrayOut.clear()
for element in arrayIn:
arrayOut.append(math.ceil(element/250))
# Update the Unicorn HAT
def updateDisplay(array):
unicornhathd.clear()
offset = 0
column = 0
for height in array:
# Respect the boundaries of the display
if height > 8:
height = 8
if height < -8:
height = -8
for pixel in range(abs(height)):
# Use the top half of the display for positive measurements
if height > 0:
offset = 8
r = bar_colour_down[0]
g = bar_colour_down[1]
b = bar_colour_down[2]
unicornhathd.set_pixel(column, offset + pixel, r, g, b)
# Use the bottom half of the display for negative measurements
if height < 0:
offset = 7
r = bar_colour_up[0]
g = bar_colour_up[1]
b = bar_colour_up[2]
unicornhathd.set_pixel(column, offset - pixel, r, g, b)
column += 1
unicornhathd.show()
# Continuously retrieve measurements and update the display
while True:
updateMeasurements(measurements)
transformMeasurements(measurements, leds)
updateDisplay(leds)
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment