def setKodiNotification(self, title, msg): try: kodi = Kodi("http://localhost/jsonrpc") kodi.GUI.ShowNotification({"title": title, "message": msg}) except Exception as e: logger.warning( "Beim der Kodianzeigerei is wos passiert: {}".format(str(e)))
def __init__(self, oled, hyp): logger.info("Initializing hardware") import RPi.GPIO as GPIO import smbus self.bus = smbus.SMBus(1) # Rev 2 Pi self.outPa = 18 #Relais für PA2200 self.outTv = 16 #Relais für TV und Sony-Verstärker self.outPhono = 33 #Relais für Phono-Preamp Power self.Out_pwr_rel = 29 #Relais für Ampi-Ringkerntrafo self.inMcpInt = 37 self.inVolDir = 36 self.inVolClk = 7 self.inVolMute = 15 self.validSources = [ 'Aus', 'CD', 'Schneitzlberger', 'Portable', 'Hilfssherriff', 'Bladdnspiela', 'Himbeer314' ] self.source = "Aus" self.ampPwr = False self.tvPwr = False self.oled = oled #OLED-Objekt erzeugen self.hyp = hyp #Hyperion-Objekt erzeugen self.kodi = Kodi("http://localhost/jsonrpc") self.initGpios() #GPIOs initialisieren self.volume = Volume(self.oled, self.bus) #Volumen-Objekt erzeugen self.sources = Sources(self.oled, self.bus) #Quellen-Objekt erzeugen
def send_kodi_message(address, port, data): """This function is used to forward MQTT events to Kodi as notification :param address: :param port: :param data: """ from kodijson import Kodi e, m, display_text = adjust_display_text(data, adapt_for="kodi_display") kodi = Kodi(f"http://{address}:{port}/jsonrpc") try: logger.debug(f"sending message to Kodi {display_text}") time = datetime.datetime.now().strftime("%H:%M") kodi.JSONRPC.Ping() kodi.GUI.ShowNotification({"title": time, "message": display_text}) except ( ConnectionError, ConnectionRefusedError, requests.exceptions.ConnectionError, urllib3.exceptions.NewConnectionError, urllib3.exceptions.MaxRetryError, ): logger.warning(f"Unable to connect to Kodi {address}:{port}") except Exception: logger.exception("Something unexpected went wrong while sending to Kodi")
def stopKodiPlayer(self): try: kodi = Kodi("http://localhost/jsonrpc") playerid = kodi.Player.GetActivePlayers()["result"][0]["playerid"] result = kodi.Player.Stop({"playerid": playerid}) logger.info("Kodi aus!") except Exception as e: logger.warning("Beim Kodi stoppen is wos passiert: {}".format( str(e)))
def kodi(run_kodi_pod): wait_for(urlopen, func_args=[JSON_RPC_URL], timeout=10, handle_exception=True) wait_for( urlopen, func_args=[f"{MOCKSERVER_URL}/user"], timeout=10, handle_exception=True, ) return Kodi(JSON_RPC_URL)
def _get_kodi(self): from kodijson import Kodi args = [self.url] if self.username: args += [self.username] if self.password: args += [self.password] return Kodi(*args)
def test_execute_ping(self): """ Test a call with JSON.Ping """ # the response does not matters responses.add("POST", "http://localhost", "{}") url = "http://localhost/" x = Kodi(url=url) x.execute("JSONRPC.Ping", x=1) expectd_body = { 'id': 0, 'jsonrpc': '2.0', 'method': 'JSONRPC.Ping', 'params': {"x": 1} } assert responses.calls[0].request.url == 'http://localhost/' assert responses.calls[0].request.method == 'POST' assert expectd_body == json.loads( responses.calls[0].request.body.decode("utf-8"))
def main(): #Login with default kodi/kodi credentials kodi = Kodi("http://localhost:8080/jsonrpc") #Login with custom credentials #kodi = Kodi("http://YOURHOST/jsonrpc", "login", "password") # Test the access to JSON_RPC print(kodi.JSONRPC.Ping()) # Navigate throught windows # Go to videos window kodi.GUI.ActivateWindow({"window":"videos"}) #kodi.Player.SetPartymode({"playerid": 0, "partymode": True}) #playlist = kodi.Playlist.GetPlaylists() #print(playlist) #items = kodi.Playlist.GetItems({"playlistid": 1}) #print(items) # Add item to playlist kodi.Playlist.Clear({"playlistid": 1}) kodi.Playlist.Add({"playlistid": 1, "item": {"musicvideoid": 1}}) kodi.Playlist.Add({"playlistid": 1, "item": {"musicvideoid": 25}}) kodi.Playlist.Add({"playlistid": 1, "item": {"musicvideoid": 30}}) videos = kodi.VideoLibrary.GetMusicVideos() print(videos) players = kodi.Player.GetPlayers() print(players) # Open and play file #kodi.Player.Open({"item": {"file":"/home/luiz/bolofofos/Bolofofos - MÚSICA DE ANIVERSÁRIO.mkv"}}) # Open video by musicvideoid on videoLibrary #kodi.Player.Open({"item": {"musicvideoid": 35}}) # Open and play playlist kodi.Player.Open({"item": {"playlistid": 1}}) # Show some notifiations : kodi.GUI.ShowNotification({"title":"Title", "message":"Hello Word, tocando bolofofos"})
def kodi_update(): if 'KODI_URL' not in app_vars or not app_vars['KODI_URL']: return {"success": False, "error": "KODI_URL not set (in environment)"} kodi = Kodi(app_vars['KODI_URL']) response = kodi.VideoLibrary.Scan() # Ideal response: {'id': 1, 'jsonrpc': '2.0', 'result': 'OK'} if False: # TODO also clean library: kodi.VideoLibrary.Clean() if response['result'] == "OK": return {"success": True} return { "success": False, "error": "bad response from Kodi", "details": response }
def test_default(self): """Tests KodiJsonTransport default values""" url = "http://localhost/" x = Kodi(url=url) assert isinstance(x.Addons, Addons) assert isinstance(x.Application, Application) assert isinstance(x.AudioLibrary, AudioLibrary) assert isinstance(x.Favourites, Favourites) assert isinstance(x.Files, Files) assert isinstance(x.GUI, GUI) assert isinstance(x.Input, Input) assert isinstance(x.JSONRPC, JSONRPC) assert isinstance(x.Playlist, Playlist) assert isinstance(x.Player, Player) assert isinstance(x.PVR, PVR) assert isinstance(x.Settings, Settings) assert isinstance(x.System, System) assert isinstance(x.VideoLibrary, VideoLibrary) assert isinstance(x.xbmc, xbmc)
def __init__(self, url="http://10.1.1.4:8080/jsonrpc"): self.kodi = Kodi(url)
#!/bin/env/python from kodijson import Kodi, PLAYER_VIDEO if __name__ == "__main__": kodi = Kodi("http://YOURHOST/jsonrpc") # JSON RPC # Ping print(kodi.JSONRPC.Ping()) # Gui kodi.GUI.ActivateWindow({"window": "home"}) kodi.GUI.ActivateWindow({"window": "weather"}) # Show a notification kodi.GUI.ShowNotification({"title": "Title", "message": "Hello notif"}) # Application kodi.Application.SetMute({"mute": True}) kodi.Application.SetMute({"mute": False}) # Video library kodi.VideoLibrary.Scan() kodi.VideoLibrary.Clean() # Query the video library print( kodi.VideoLibrary.GetTVShows( { "filter": { "field": "playcount", "operator": "is", "value": "0" },
SERVER_IP = [ l for l in ( [ ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.") ][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l ][0][0] cast_cmd = "cvlc --qt-start-minimized screen:// :screen-fps=34 :screen-caching=80 --sout '#transcode{vcodec=mp4v,vb=4096,acodec=mpga,ab=128,sca=Auto,width=1024,height=768}:http{mux=ts,dst=:8089/" + socket.gethostname( ) + "}' --no-video --no-sout-video" + SOUND_DEVICE_SETTINGS disable_local_audio_cmd = "pacmd set-sink-volume " + subprocess.getoutput( "pacmd list-sink-inputs | grep sink | grep -oP '(?<=<).*(?=>)'") + " 100" KODI_URL = upnp_address kodi = Kodi(KODI_URL, "kodi", "") current_cast = {} def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("hermes/hotword/" + site_id + "/detected") # client.subscribe("hermes/audioServer/" + site_id + "/audioFrame") client.subscribe("hermes/dialogueManager/sessionEnded") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg):
from kodijson import Kodi, PLAYER_VIDEO ip = "127.0.0.1" kodi = Kodi(f"http://{ip}:8081/jsonrpc") import json import threading import db import datetime ctype = "null" item = "null" #stopped, playing, paused def get_info(): threading.Timer(0.1, get_info).start() info = kodi.Player.GetActivePlayers() #print(info) if info['result'] == []: db.ps = "stopped" return else: db.playerid = info['result'][0]['playerid'] ctype = info['result'][0]['type'] #print(kodi.Player.GetItem(playerid=playerid, properties=['thumbnail'])) #print(kodi.Player.GetItem(playerid=playerid, properties=['file'])) #time2 = {'time': {'hours': 0, 'milliseconds': 165, 'minutes': 25, 'seconds': 42}} db.time = kodi.Player.GetProperties(playerid=db.playerid, properties=['time'])['result']['time'] db.time = db.time["hours"]*60*60 + db.time["minutes"]*60 + db.time["seconds"] state = kodi.Player.GetProperties(playerid=db.playerid, properties=['speed'])['result']['speed'] if state == 1: db.ps = "playing"
from googlesamples.assistant.grpc import ( assistant_helpers, audio_helpers, device_helpers ) except SystemError: import assistant_helpers import audio_helpers import device_helpers #Login with default kodi/kodi credentials #kodi = Kodi("http://localhost:8080/jsonrpc") #Login with custom credentials # Kodi("http://IP-ADDRESS-OF-KODI:8080/jsonrpc", "username", "password") kodi = Kodi("http://192.168.1.15:8080/jsonrpc", "kodi", "kodi") GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) #Trigger Pin GPIO.setup(22, GPIO.IN, pull_up_down = GPIO.PUD_UP) #Indicator Pins GPIO.setup(25, GPIO.OUT) GPIO.setup(5, GPIO.OUT) GPIO.setup(6, GPIO.OUT) GPIO.output(5, GPIO.LOW) GPIO.output(6, GPIO.LOW) led=GPIO.PWM(25,1) led.start(0)
from kodijson import Kodi from eglantinews.EglantineConfig import EglantineConfig from utils.SearchUtils import simplify config = EglantineConfig() kodi = Kodi(config.get_kodi_config()['url']) movies = kodi.VideoLibrary.GetMovies({ "limits": { "start": 0, "end": 10000 }, "sort": { "order": "ascending", "method": "title", "ignorearticle": True } })['result']['movies'] for movie in movies: print('"' + simplify(movie['label']) + '"')
nfoF.write(" <showtitle>%s</showtitle>\n" % channel_title) nfoF.write(" <aired>%s</aired>\n" % created) nfoF.write(" <plot>%s</plot>\n" % description) nfoF.write(" <runtime>%i</runtime>\n" % round(duration)) nfoF.write(" <thumb>%s</thumb>\n" % thumbURL) nfoF.write(" <videourl>%s</videourl>\n" % videoURL) nfoF.write("</episodedetails>\n") print("---------------------------------") if kodihostname: #Login with custom credentials if not kodiport: kodiport = 8080 # Kodi Web default port kodi = Kodi("http://%s:%i/jsonrpc" % (kodihostname, kodiport), kodiuser, kodipassword) assert kodi.JSONRPC.Ping( )['result'] == 'pong', '\nERROR: bad or response from Kodi (@ %s)' % kodihostname if shouldScanKodi or shouldCleanKodi: kodi.GUI.ShowNotification({ "title": "ToWatchList Downloader", "message": "New videos downloaded, update Kodi library…" }) if shouldScanKodi: print("Scanning Kodi Library (@ %s)" % kodihostname) kodi.VideoLibrary.Scan() if shouldCleanKodi: print("Cleaning Kodi Library (@ %s)" % kodihostname) kodi.VideoLibrary.Clean()
import assistant_helpers import audio_helpers import browser_helpers import device_helpers # logging.basicConfig(filename='/tmp/GassistPi.log', level=logging.DEBUG, # format='%(asctime)s %(levelname)s %(name)s %(message)s') # logger=logging.getLogger(__name__) #Login with default kodi/kodi credentials #kodi = Kodi("http://localhost:8080/jsonrpc") #Login with custom credentials # Kodi("http://IP-ADDRESS-OF-KODI:8080/jsonrpc", "username", "password") kodiurl=("http://"+str(configuration['Kodi']['ip'])+":"+str(configuration['Kodi']['port'])+"/jsonrpc") kodi = Kodi(kodiurl, configuration['Kodi']['username'], configuration['Kodi']['password']) if configuration['Kodi']['Kodi_Control']=='Enabled': kodicontrol=True else: kodicontrol=False ROOT_PATH = os.path.realpath(os.path.join(__file__, '..', '..')) USER_PATH = os.path.realpath(os.path.join(__file__, '..', '..','..')) if GPIOcontrol: #GPIO Declarations GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) pushbuttontrigger=configuration['Gpios']['pushbutton_trigger'][0] GPIO.setup(pushbuttontrigger, GPIO.IN, pull_up_down = GPIO.PUD_UP)
def __init__(self): EglantineTVService.__init__(self) self._kodi = Kodi(self._kodi_config['url']) self._kodi_input = self._kodi_config['input']