initial commit

This commit is contained in:
barry committed 2025-01-10 15:37:00 +01:00
commit 26442d418f
16 files changed
+1068

No files matched your search

View File
Whitespace-only changes.
+49
View File
@@ -0,0 +1,49 @@
import requests
class Api:
def __init__(self, refresh_token: str, base_64: str):
self.refresh_token = refresh_token
self.base_64 = base_64
self.access_token = None
self.header = None
def refreshAuth(self) -> None:
uri = "https://accounts.spotify.com/api/token"
data = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
}
req = requests.post(uri, data=data, headers={"Authorization": "Basic " + self.base_64}).json()
self.access_token = req["access_token"]
self.header = {"Authorization": f"Bearer {self.access_token}"}
return req["expires_in"]
def getPlaying(self):
url = "https://api.spotify.com/v1/me/player/currently-playing"
req = requests.get(url, headers=self.header)
if req.status_code == 204:
return "not-playing"
if req.status_code != 200:
warnings.warn(f"Unknown API Error {req.status_code},\n{req.content}")
return None
return self._format_req(req.json())
def _format_req(self, r):
item, album = r["item"], r["item"]["album"]
res = {
"progress_ms": r["progress_ms"],
"duration_ms": item["duration_ms"],
"track": item["name"],
"album": album["name"],
"artists": [artist["name"] for artist in item["artists"]],
"img_url": None,
}
img_urls = album.get("images", [])
if img_urls:
res["img_url"] = img_urls.pop()["url"]
else:
warnings.warn(f"{res['track']} - {res['artists']}\nAlbum art can't be found\n{img_urls}")
return res
+12
View File
@@ -0,0 +1,12 @@
refresh_token: "AQBGNOL-iocPZ_zxtr_sNXx4BZRaxPmg2Ea0cJGorcEu2IW2wSnLdkYDJpVDOuQQHWIQ-LjuNpBcY9PurPtdfPoT5ljXnGpso9CqX6n2alBXaYc767oKya_52qxqWPE0o7k"
base_64: "ZTI5Mzg3NWI3YWQ5NDQzZDg1NDMxYzkwOTEyZTdiMWQ6MjlmNDEzZTJiOTRlNGU0NDlkOWRiYmU0NmM2OTY5MTY="
api_interval: 5
refresh_interval: 0.4
color_theme:
text: [255, 255, 255]
bar_outline: [255, 255, 255]
bar_inside: [30, 215, 96]
background: [25, 20, 20]
+111
View File
@@ -0,0 +1,111 @@
# /*****************************************************************************
# * | File : epdconfig.py
# * | Author : Waveshare team
# * | Function : Hardware underlying interface
# * | Info :
# *----------------
# * | This version: V1.0
# * | Date : 2019-06-21
# * | Info :
# ******************************************************************************
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documnetation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import os
import sys
import time
import spidev
import logging
import numpy as np
class RaspberryPi:
def __init__(self,spi_freq=40000000,rst=27,dc=25,bl=18,bl_freq=1000,i2c=None,i2c_freq=100000):
import RPi.GPIO
self.np = np
self.RST_PIN= rst
self.DC_PIN = dc
self.BL_PIN = bl
self.SPEED =spi_freq
self.BL_freq=bl_freq
self.GPIO = RPi.GPIO
#self.GPIO.cleanup()
self.GPIO.setmode(self.GPIO.BCM)
self.GPIO.setwarnings(False)
self.GPIO.setup(self.RST_PIN, self.GPIO.OUT)
self.GPIO.setup(self.DC_PIN, self.GPIO.OUT)
self.GPIO.setup(self.BL_PIN, self.GPIO.OUT)
self.GPIO.output(self.BL_PIN, self.GPIO.HIGH)
#Initialize SPI
self.SPI = spidev.SpiDev()
self.SPI.open(0, 0)
self.SPI.max_speed_hz = spi_freq
self.SPI.mode = 0b00
def digital_write(self, pin, value):
self.GPIO.output(pin, value)
def digital_read(self, pin):
return self.GPIO.input(pin)
def delay_ms(self, delaytime):
time.sleep(delaytime / 1000.0)
def spi_writebyte(self, data):
if self.SPI!=None :
self.SPI.writebytes(data)
def bl_DutyCycle(self, duty):
self._pwm.ChangeDutyCycle(duty)
def bl_Frequency(self,freq):
self._pwm.ChangeFrequency(freq)
def module_init(self):
self.GPIO.setup(self.RST_PIN, self.GPIO.OUT)
self.GPIO.setup(self.DC_PIN, self.GPIO.OUT)
self.GPIO.setup(self.BL_PIN, self.GPIO.OUT)
self._pwm=self.GPIO.PWM(self.BL_PIN,self.BL_freq)
self._pwm.start(100)
if self.SPI!=None :
self.SPI.max_speed_hz = self.SPEED
self.SPI.mode = 0b00
return 0
def module_exit(self):
logging.debug("spi end")
if self.SPI!=None :
self.SPI.close()
logging.debug("gpio cleanup...")
self.GPIO.output(self.RST_PIN, 1)
self.GPIO.output(self.DC_PIN, 0)
self._pwm.stop()
time.sleep(0.001)
self.GPIO.output(self.BL_PIN, 1)
#self.GPIO.cleanup()
'''
if os.path.exists('/sys/bus/platform/drivers/gpiomem-bcm2835'):
implementation = RaspberryPi()
for func in [x for x in dir(implementation) if not x.startswith('_')]:
setattr(sys.modules[__name__], func, getattr(implementation, func))
'''
### END OF FILE ###
+178
View File
@@ -0,0 +1,178 @@
import time
import lcdconfig
class LCD_2inch(lcdconfig.RaspberryPi):
width = 240
height = 320
def command(self, cmd):
self.digital_write(self.DC_PIN, self.GPIO.LOW)
self.spi_writebyte([cmd])
def data(self, val):
self.digital_write(self.DC_PIN, self.GPIO.HIGH)
self.spi_writebyte([val])
def reset(self):
"""Reset the display"""
self.GPIO.output(self.RST_PIN,self.GPIO.HIGH)
time.sleep(0.01)
self.GPIO.output(self.RST_PIN,self.GPIO.LOW)
time.sleep(0.01)
self.GPIO.output(self.RST_PIN,self.GPIO.HIGH)
time.sleep(0.01)
def Init(self):
"""Initialize dispaly"""
self.module_init()
self.reset()
self.command(0x36)
self.data(0x00)
self.command(0x3A)
self.data(0x05)
self.command(0x21)
self.command(0x2A)
self.data(0x00)
self.data(0x00)
self.data(0x01)
self.data(0x3F)
self.command(0x2B)
self.data(0x00)
self.data(0x00)
self.data(0x00)
self.data(0xEF)
self.command(0xB2)
self.data(0x0C)
self.data(0x0C)
self.data(0x00)
self.data(0x33)
self.data(0x33)
self.command(0xB7)
self.data(0x35)
self.command(0xBB)
self.data(0x1F)
self.command(0xC0)
self.data(0x2C)
self.command(0xC2)
self.data(0x01)
self.command(0xC3)
self.data(0x12)
self.command(0xC4)
self.data(0x20)
self.command(0xC6)
self.data(0x0F)
self.command(0xD0)
self.data(0xA4)
self.data(0xA1)
self.command(0xE0)
self.data(0xD0)
self.data(0x08)
self.data(0x11)
self.data(0x08)
self.data(0x0C)
self.data(0x15)
self.data(0x39)
self.data(0x33)
self.data(0x50)
self.data(0x36)
self.data(0x13)
self.data(0x14)
self.data(0x29)
self.data(0x2D)
self.command(0xE1)
self.data(0xD0)
self.data(0x08)
self.data(0x10)
self.data(0x08)
self.data(0x06)
self.data(0x06)
self.data(0x39)
self.data(0x44)
self.data(0x51)
self.data(0x0B)
self.data(0x16)
self.data(0x14)
self.data(0x2F)
self.data(0x31)
self.command(0x21)
self.command(0x11)
self.command(0x29)
def SetWindows(self, Xstart, Ystart, Xend, Yend):
#set the X coordinates
self.command(0x2A)
self.data(Xstart>>8) #Set the horizontal starting point to the high octet
self.data(Xstart & 0xff) #Set the horizontal starting point to the low octet
self.data(Xend>>8) #Set the horizontal end to the high octet
self.data((Xend - 1) & 0xff)#Set the horizontal end to the low octet
#set the Y coordinates
self.command(0x2B)
self.data(Ystart>>8)
self.data((Ystart & 0xff))
self.data(Yend>>8)
self.data((Yend - 1) & 0xff )
self.command(0x2C)
def ShowImage(self,Image,Xstart=0,Ystart=0):
"""Set buffer to value of Python Imaging Library image."""
"""Write display buffer to physical display"""
imwidth, imheight = Image.size
if imwidth == self.height and imheight == self.width:
img = self.np.asarray(Image)
pix = self.np.zeros((self.width, self.height,2), dtype = self.np.uint8)
#RGB888 >> RGB565
pix[...,[0]] = self.np.add(self.np.bitwise_and(img[...,[0]],0xF8),self.np.right_shift(img[...,[1]],5))
pix[...,[1]] = self.np.add(self.np.bitwise_and(self.np.left_shift(img[...,[1]],3),0xE0), self.np.right_shift(img[...,[2]],3))
pix = pix.flatten().tolist()
self.command(0x36)
self.data(0x70)
self.SetWindows ( 0, 0, self.height,self.width)
self.digital_write(self.DC_PIN,self.GPIO.HIGH)
for i in range(0,len(pix),4096):
self.spi_writebyte(pix[i:i+4096])
else :
img = self.np.asarray(Image)
pix = self.np.zeros((imheight,imwidth , 2), dtype = self.np.uint8)
pix[...,[0]] = self.np.add(self.np.bitwise_and(img[...,[0]],0xF8),self.np.right_shift(img[...,[1]],5))
pix[...,[1]] = self.np.add(self.np.bitwise_and(self.np.left_shift(img[...,[1]],3),0xE0), self.np.right_shift(img[...,[2]],3))
pix = pix.flatten().tolist()
self.command(0x36)
self.data(0x00)
self.SetWindows ( 0, 0, self.width, self.height)
self.digital_write(self.DC_PIN,self.GPIO.HIGH)
for i in range(0,len(pix),4096):
self.spi_writebyte(pix[i:i+4096])
def clear(self):
"""Clear contents of image buffer"""
_buffer = [0xff]*(self.width * self.height * 2)
self.SetWindows ( 0, 0, self.height, self.width)
self.digital_write(self.DC_PIN,self.GPIO.HIGH)
for i in range(0,len(_buffer),4096):
self.spi_writebyte(_buffer[i:i+4096])
+128
View File
@@ -0,0 +1,128 @@
from PIL import Image, ImageDraw, ImageFont
import textwrap
import time
import requests
from io import BytesIO
import warnings
from datetime import datetime
import yaml
from typing import Dict
from lib import LCD_2inch
from api import Api
def parse_config(path="spotiplayer_pi/config.yaml"):
with open(path, "r") as file:
data = yaml.safe_load(file)
for key, value in data["color_theme"].items():
data["color_theme"][key] = tuple(value)
return data
def display_loop(api: Api, cfg: Dict):
try:
d = LCD_2inch()
d.Init()
d.clear()
bg = Image.new("RGB", (d.height, d.width), (0, 0, 0))
d.ShowImage(bg)
Font0 = ImageFont.truetype("Font/Font00.ttf", 14)
Font1 = ImageFont.truetype("Font/Font00.ttf", 18)
Font2 = ImageFont.truetype("Font/Font00.ttf", 36)
unavailable_img = Image.open("imgs/unavailable.jpg")
error_img = Image.new("RGB", (240, 320), color=(255, 0, 0))
draw = ImageDraw.Draw(error_img)
draw.text((150, 150), "Error", font=Font1, fill=cfg["color_theme"]["text"])
del draw
spoti_logo = Image.open("imgs/logo128.jpg")
qr = Image.open("imgs/qr.jpg")
spoti_logo = spoti_logo.resize((128, 128))
not_playing_img = Image.new("RGB", (320, 240), (0, 0, 0))
not_playing_img.paste(spoti_logo, (0, 10))
not_playing_img.paste(qr, (120, 40))
draw = ImageDraw.Draw(not_playing_img)
draw.text((124, 10), "Connect to speakers", font=Font1, fill=cfg["color_theme"]["text"])
del spoti_logo, qr, draw
last_api_call = 0
last_auth_refresh = 0
current_mode = None
last_track = None
data = None
auth_interval = 0
while True:
if time.time() - last_auth_refresh >= auth_interval:
auth_interval = api.refreshAuth() - 120
last_auth_refresh = time.time()
print(f'Refreshed auth at {datetime.now().strftime("%d-%m %H:%M:%S")}')
if time.time() - last_api_call >= cfg["api_interval"]:
data = api.getPlaying()
last_api_call = time.time()
if data == None:
warnings.warn("No data found")
d.ShowImage(error_img)
elif data == "not-playing":
draw = ImageDraw.Draw(not_playing_img)
current_time = datetime.now().time()
draw.rectangle([(00, 120), (119, 170)], fill=(0, 0, 0))
draw.text((20, 120), f"{current_time.hour}:{current_time.minute:02d}", font=Font2, angle=0)
if current_mode != 0:
current_mode = 0
print("Standby mode")
d.ShowImage(not_playing_img)
time.sleep(cfg["api_interval"])
elif type(data) == dict:
current_track = data["track"] + data["artists"][0] + data["album"]
if current_track != last_track:
print('updating track')
last_track = current_track
img = None
try:
img = requests.get(data["img_url"], timeout=cfg["refresh_interval"]/2)
img = Image.open(BytesIO(img.content))
except Exception as e:
warnings.warn(f"Failed to fetch album cover at: {data['img_url']}\n{e}")
if img == None:
img = unavailable_img
img = img.resize((128, 128))
bg = Image.new("RGB", (320, 240), cfg["color_theme"]["background"])
bg.paste(img, (10, 30))
draw = ImageDraw.Draw(bg)
draw.text((150, 40), "\n".join(textwrap.wrap(", ".join(data["artists"]), width=16)), font=Font1, fill=cfg["color_theme"]["text"])
draw.text((10, 160), "\n".join(textwrap.wrap(data["track"], width=32)), font=Font1, fill=cfg["color_theme"]["text"])
w, h = bg.size
w -= 92
progress_time = data["progress_ms"] + int((time.time() - last_api_call) * 1000)
progress= progress_time / data["duration_ms"]
bar_width = int(w * progress)
draw.rectangle([(8, h - 22), (w + 2, h - 8)], outline=cfg["color_theme"]["bar_outline"])
draw.rectangle([(10, h - 20), (w, h - 10)], fill=cfg["color_theme"]["background"])
draw.rectangle([(10, h - 20), (bar_width, h - 10)], fill=cfg["color_theme"]["bar_inside"])
f_current_time = "{:02.0f}:{:02.0f}".format(*divmod(progress_time // 1000, 60))
f_total_time = "{:02d}:{:02d}".format(*divmod(data["duration_ms"]// 1000, 60))
draw.rectangle([(234, 215), (310, 235)], fill=cfg["color_theme"]["background"])
draw.text((235, 215), f"{f_current_time}/{f_total_time}", font=Font0, fill=cfg["color_theme"]["text"])
d.ShowImage(bg)
time.sleep(cfg["refresh_interval"])
except IOError as e:
raise e
except KeyboardInterrupt:
d.module_exit()
if __name__ == "__main__":
cfg = parse_config()
api = Api(cfg["refresh_token"], cfg["base_64"])
display_loop(api, cfg)