Switching from using JPEG to JSON files

pull/695/head
thirdr 2023-03-01 11:08:49 +00:00
rodzic 45a12892b8
commit 0cec01cf37
1 zmienionych plików z 57 dodań i 22 usunięć

Wyświetl plik

@ -1,7 +1,8 @@
import gc
import random
import jpegdec
from urllib import urequest
from ujson import load
import qrcode
gc.collect() # We're really gonna need that RAM!
@ -13,19 +14,39 @@ HEIGHT = 0
FILENAME = "random-joke.jpg"
JOKE_IDS = "https://pimoroni.github.io/feed2image/jokeapi-ids.txt"
JOKE_IMG = "https://pimoroni.github.io/feed2image/jokeapi-{}-{}x{}.jpg"
JOKE_IMG = "https://pimoroni.github.io/feed2image/jokeapi-{}.json"
UPDATE_INTERVAL = 60
gc.collect() # Claw back some RAM!
# We don't have the RAM to store the list of Joke IDs in memory.
# the first line of `jokeapi-ids.txt` is a COUNT of IDs.
# Grab it, then pick a random line between 0 and COUNT.
# Seek to that line and ...y'know... there's our totally random joke ID
joke = []
def measure_qr_code(size, code):
w, h = code.get_size()
module_size = int(size / w)
return module_size * w, module_size
def draw_qr_code(ox, oy, size, code):
size, module_size = measure_qr_code(size, code)
graphics.set_pen(1)
graphics.rectangle(ox, oy, size, size)
graphics.set_pen(0)
for x in range(size):
for y in range(size):
if code.get_module(x, y):
graphics.rectangle(ox + x * module_size, oy + y * module_size, module_size, module_size)
def update():
global joke
try:
socket = urequest.urlopen(JOKE_IDS)
@ -49,34 +70,48 @@ def update():
print("Random joke ID: {}".format(random_joke_id))
url = JOKE_IMG.format(random_joke_id, WIDTH, HEIGHT)
url = JOKE_IMG.format(random_joke_id)
socket = urequest.urlopen(url)
gc.collect()
# 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()
del data
gc.collect() # We really are tight on RAM!
# Grab the data
try:
socket = urequest.urlopen(url)
gc.collect()
j = load(socket)
socket.close()
joke = j
del j
gc.collect()
except OSError as e:
print(e)
def draw():
jpeg = jpegdec.JPEG(graphics)
gc.collect() # For good measure...
code = qrcode.QRCode()
graphics.set_pen(1)
graphics.clear()
try:
jpeg.open_file(FILENAME)
jpeg.decode()
except OSError:
if joke:
if joke['type'] == "single":
graphics.set_pen(4)
graphics.text(joke['joke'], 10, 10, WIDTH - 75, 5)
if joke['type'] == "twopart":
graphics.set_pen(4)
graphics.text(joke['setup'], 10, 10, WIDTH - 75, 5)
graphics.set_pen(3)
graphics.text(joke['delivery'], 10, 290, WIDTH - 75, 5)
graphics.set_pen(0)
# Donate link QR
code.set_text("https://github.com/sponsors/Sv443")
draw_qr_code(WIDTH - 75, HEIGHT - 75, 75, code)
graphics.text("curated by jokeapi.dev", 10, HEIGHT - 15, WIDTH, 1)
graphics.text("donate <3", WIDTH - 65, HEIGHT - 12, WIDTH, 1)
else:
graphics.set_pen(4)
graphics.rectangle(0, (HEIGHT // 2) - 20, WIDTH, 40)
graphics.set_pen(1)