Last active
July 28, 2019 12:22
-
-
Save tribela/d573fda522800af828949aca7c9c8f18 to your computer and use it in GitHub Desktop.
Mpris listener to change yeelight color
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gi.repository.GLib | |
from dbus.mainloop.glib import DBusGMainLoop | |
from io import BytesIO | |
from pprint import pprint | |
import colorthief | |
import mpris2 | |
import requests | |
DBusGMainLoop(set_as_default=True) | |
class LightManager(): | |
API_KEY = '7fb78a81b20bee7cb6e8fad4cbcb3694' | |
API_URL = 'https://ws.audioscrobbler.com/2.0/' | |
YEELIGHT_URL = 'http://sakura.lan:31337/light' | |
def __init__(self): | |
player_uri = next(mpris2.get_players_uri()) | |
self.player = mpris2.Player(dbus_interface_info={ | |
'dbus_uri': player_uri}) | |
self.player.PropertiesChanged = self.property_handler | |
self.last_song = None | |
self.handle_changed() | |
def run(self): | |
mloop = gi.repository.GLib.MainLoop() | |
mloop.run() | |
def handle_changed(self): | |
artist = str(self.player.Metadata['xesam:artist'][0]) | |
album = str(self.player.Metadata['xesam:album']) | |
title = str(self.player.Metadata['xesam:title']) | |
if (artist, album, title) != self.last_song: | |
print(f'{artist} - {album} - {title}') | |
self.last_song = (artist, album, title) | |
cover = self.get_lastfm_cover(artist, album) | |
if not cover: | |
return | |
color = self.get_colorcode(cover) | |
self.change_color(color) | |
def property_handler(self, *args, **kwargs): | |
data = args[1] | |
if 'Metadata' in data: | |
self.handle_changed() | |
def change_color(self, color): | |
resp = requests.post(self.YEELIGHT_URL, { | |
'rgb': color | |
}) | |
print(resp.reason) | |
@classmethod | |
def get_lastfm_cover(cls, artist, album): | |
res = requests.get(cls.API_URL, { | |
'method': 'album.getInfo', | |
'artist': artist, | |
'album': album, | |
'api_key': cls.API_KEY, | |
'format': 'json', | |
}).json() | |
if 'error' in res: | |
print(res) | |
return | |
return res['album']['image'][-1]['#text'] | |
@staticmethod | |
def get_colorcode(image_url): | |
resp = requests.get(image_url) | |
file = BytesIO(resp.content) | |
ct = colorthief.ColorThief(file) | |
r, g, b = ct.get_color() | |
print('Color: {:02x}{:02x}{:02x}'.format(r, g, b)) | |
r //= 2 | |
print('Color (Adjusted): {:02x}{:02x}{:02x}'.format(r, g, b)) | |
return '{:02x}{:02x}{:02x}'.format(r, g, b) | |
lm = LightManager() | |
lm.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment