Skip to content

Commit

Permalink
Merge pull request #1 from pimoroni/examples/new-launcher-examples
Browse files Browse the repository at this point in the history
Examples: replaced examples with no longer active API
  • Loading branch information
Gadgetoid authored Dec 3, 2024
2 parents 97bf5fb + 1c84a32 commit 4c92dc1
Show file tree
Hide file tree
Showing 6 changed files with 194 additions and 253 deletions.
120 changes: 120 additions & 0 deletions examples/inkylauncher/carbon_intensity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""
This example connects to the Carbon Intensity API to give you a regional
forecast of how your (UK) electricity is being generated and its carbon impact.
Carbon Intensity API only reports data from the UK National Grid.
Find out more about what the numbers mean at:
https://carbonintensity.org.uk/
Make sure to uncomment the correct size for your display!
"""

import urequests
import inky_frame

graphics = None
WIDTH = None
HEIGHT = None

# Length of time between updates in minutes.
# Frequent updates will reduce battery life!
UPDATE_INTERVAL = 240

# Set (the first half) of your UK postcode here
POSTCODE = "S9"

URL = "https://api.carbonintensity.org.uk/regional/postcode/" + str(POSTCODE)


def update():
global region, forecast, index, power_list, datetime_to, datetime_from
print(f"Requesting URL: {URL}")
r = urequests.get(URL)
# open the json data
j = r.json()
print("Data obtained!")
print(j)

# parse the json data
region = j["data"][0]["shortname"]

forecast = j["data"][0]["data"][0]["intensity"]["forecast"]
index = j["data"][0]["data"][0]["intensity"]["index"]

power_list = []
for power in j["data"][0]["data"][0]["generationmix"]:
power_list.append(power['perc'])

datetime_to = j["data"][0]["data"][0]["to"].split("T")
datetime_from = j["data"][0]["data"][0]["from"].split("T")

# close the socket
r.close()


def draw():
# we're setting up our PicoGraphics buffer after we've made our RAM intensive https request
w, h = WIDTH, HEIGHT
graphics.set_pen(inky_frame.WHITE)
graphics.clear()

# draw lines
graphics.set_pen(inky_frame.BLACK)
graphics.line(0, int((h / 100) * 0), w, int((h / 100) * 0))
graphics.line(0, int((h / 100) * 50), w, int((h / 100) * 50))
graphics.set_font("bitmap8")
graphics.text('100%', w - 40, 10, scale=2)
graphics.text('50%', w - 40, int((h / 100) * 50 + 10), scale=2)

# draw bars
bar_colours = [
inky_frame.ORANGE,
inky_frame.RED,
inky_frame.ORANGE,
inky_frame.RED,
inky_frame.BLUE,
inky_frame.ORANGE,
inky_frame.GREEN,
inky_frame.GREEN,
inky_frame.GREEN
]
for p in power_list:
graphics.set_pen(bar_colours[power_list.index(p)])
graphics.rectangle(int(power_list.index(p) * w / 9), int(h - p * (h / 100)),
int(w / 9), int(h / 100 * p))

# draw labels
graphics.set_font('sans')
# once in white for a background
graphics.set_pen(inky_frame.WHITE)
labels = ['biomass', 'coal', 'imports', 'gas', 'nuclear', 'other', 'hydro', 'solar', 'wind']
graphics.set_thickness(4)
for label in labels:
graphics.text(f'{label}', int((labels.index(label) * w / 9) + (w / 9) / 2), h - 10, angle=270, scale=1)
# again in black
graphics.set_pen(inky_frame.BLACK)
labels = ['biomass', 'coal', 'imports', 'gas', 'nuclear', 'other', 'hydro', 'solar', 'wind']
graphics.set_thickness(2)
for label in labels:
graphics.text(f'{label}', int((labels.index(label) * w / 9) + (w / 9) / 2), h - 10, angle=270, scale=1)

# draw header
graphics.set_thickness(3)
graphics.set_pen(inky_frame.GREEN)
if index in ['high', 'very high']:
graphics.set_pen(inky_frame.RED)
if index in ['moderate']:
graphics.set_pen(inky_frame.ORANGE)
graphics.set_font("sans")
graphics.text('Carbon Intensity', 10, 35, scale=1.2, angle=0)

# draw small text
graphics.set_pen(inky_frame.BLACK)
graphics.set_font("bitmap8")
graphics.text(f'Region: {region}', int((w / 2) + 30), 10, scale=2)
graphics.text(f'{forecast} gCO2/kWh ({index})', int((w / 2) + 30), 30, scale=2)
graphics.text(f'{datetime_from[0]} {datetime_from[1]} to {datetime_to[1]}', int((w / 2) + 30), 50, scale=2)

graphics.update()
127 changes: 0 additions & 127 deletions examples/inkylauncher/daily_activity.py

This file was deleted.

69 changes: 69 additions & 0 deletions examples/inkylauncher/daily_xkcd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import gc
import uos
import machine
import jpegdec
import sdcard
from urllib import urequest

"""
xkcd daily
You *must* insert an SD card into Inky Frame!
We need somewhere to save the jpg for display.
Fetches a pre-processed XKCD daily image from:
https://pimoroni.github.io/feed2image/xkcd-daily.jpg
See https://xkcd.com/ for more webcomics!
"""

graphics = None
WIDTH = None
HEIGHT = None

UPDATE_INTERVAL = 240

gc.collect() # We're really gonna need that RAM!

FILENAME = "/sd/xkcd-daily.jpg"
ENDPOINT = "https://pimoroni.github.io/feed2image/xkcd-daily.jpg"

sd_spi = machine.SPI(0, sck=machine.Pin(18, machine.Pin.OUT), mosi=machine.Pin(19, machine.Pin.OUT), miso=machine.Pin(16, machine.Pin.OUT))
sd = sdcard.SDCard(sd_spi, machine.Pin(22))
uos.mount(sd, "/sd")
gc.collect() # Claw back some RAM!


def update():
url = ENDPOINT

if (WIDTH, HEIGHT) != (600, 448):
url = url.replace("xkcd-", f"xkcd-{WIDTH}x{HEIGHT}-")

socket = urequest.urlopen(url)

# Stream the image data from the socket onto disk in 1024 byte chunks
# the 600x448-ish jpeg will be roughly ~24k, we really don't have the RAM!
data = bytearray(1024)
with open(FILENAME, "wb") as f:
while True:
if socket.readinto(data) == 0:
break
f.write(data)
socket.close()
gc.collect() # We really are tight on RAM!


def draw():

gc.collect() # For good measure...

jpeg = jpegdec.JPEG(graphics)

graphics.set_pen(1)
graphics.clear()

jpeg.open_file(FILENAME)
jpeg.decode()

graphics.update()
8 changes: 4 additions & 4 deletions examples/inkylauncher/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def launcher():
graphics.set_pen(2)
graphics.rectangle(30, HEIGHT - (220 + y_offset), WIDTH - 200, 50)
graphics.set_pen(1)
graphics.text("C. Daily Activity", 35, HEIGHT - (205 + y_offset), 600, 3)
graphics.text("C. Daily XKCD", 35, HEIGHT - (205 + y_offset), 600, 3)

graphics.set_pen(3)
graphics.rectangle(30, HEIGHT - (160 + y_offset), WIDTH - 250, 50)
Expand All @@ -70,7 +70,7 @@ def launcher():
graphics.set_pen(0)
graphics.rectangle(30, HEIGHT - (100 + y_offset), WIDTH - 300, 50)
graphics.set_pen(1)
graphics.text("E. Random Joke", 35, HEIGHT - (85 + y_offset), 600, 3)
graphics.text("E. Carbon Intensity", 35, HEIGHT - (85 + y_offset), 600, 3)

graphics.set_pen(graphics.create_pen(220, 220, 220))
graphics.rectangle(WIDTH - 100, HEIGHT - (340 + y_offset), 70, 50)
Expand Down Expand Up @@ -107,7 +107,7 @@ def launcher():
reset()
if ih.inky_frame.button_c.read():
ih.inky_frame.button_c.led_on()
ih.update_state("daily_activity")
ih.update_state("daily_xkcd")
time.sleep(0.5)
reset()
if ih.inky_frame.button_d.read():
Expand All @@ -117,7 +117,7 @@ def launcher():
reset()
if ih.inky_frame.button_e.read():
ih.inky_frame.button_e.led_on()
ih.update_state("random_joke")
ih.update_state("carbon_intensity")
time.sleep(0.5)
reset()

Expand Down
2 changes: 1 addition & 1 deletion examples/inkylauncher/news_headlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def draw():

graphics.set_pen(3)
graphics.text(feed[0]["description"], 10, 135 if graphics.measure_text(feed[0]["title"]) < 650 else 90, WIDTH - 150, 2)
graphics.text(feed[1]["description"], 130, 320 if graphics.measure_text(feed[1]["title"]) < 650 else 230, WIDTH - 145, 2)
graphics.text(feed[1]["description"], 130, 320 if graphics.measure_text(feed[1]["title"]) < 650 else 340, WIDTH - 145, 2)

graphics.line(10, 215, WIDTH - 10, 215)

Expand Down
Loading

0 comments on commit 4c92dc1

Please sign in to comment.