Skip to content

fb42000/kanzi

 
 

Repository files navigation

Alexa Integration With Kodi

Contents

About Kodi-Alexa

This is a skill for Amazon Alexa that allows you to control one or more instances of Kodi with your voice.

This repo is forked from the master Kanzi but includes additional PVR control and is based on the previous kodi-alexa and kodi-voice which was not up to date on other areas. Therefore this readme is not as per the Kanzi -lexigram install method, instead using Zappa Deployment as you will need to replace certain files within before uploading. Kanzi - lexigram automates this process for an easier install but will not give you the PVR elements.

Please note this fork and version of readme is based only on using AWS Lambda as the host. Other methods as descirbed on the latest Kanzi master readme but cannot confirm the PVR functions will work as expected.

The process of setting up the skill may seem daunting at first, but the reward -- we feel -- is well worth the effort. If you carefully follow the directions to the tee, you might find it is not as complicated as it seems.

Unfortunately, as of this moment, we cannot simply ship this skill normally as other skills on Amazon's skill marketplace. The main technical hurdle is that some features we would need are currently only supported in the US region. Beyond that, there is the consideration of cost for hosting the skill and the associated database backend. Do try to keep in mind that this is a hobby project for the developers -- we do not get paid in any way.

However, we have made every effort to here to provide clear and concise documentation to allow you to make use of this skill now.

Kodi-Alexa in Action

Amazon Echo - Kodi integration (demo 1)

Amazon Echo - Kodi integration (demo 2)

Supported Commands

Most everything you can do with a remote or keyboard is supported in the skill, and more:

Additional features to Kanzi Master include; (requires a PVR backend and client such as TV Headend)

  • PVR feature to open and change channel by channel name,
  • PVR feature to change channel up, down, previous
  • PVR feature to watch an active programme by name
  • PVR feature to record a channel or programme by name (**v18 nightly from 20/12/18 only due to previous bug)
  • Open and listen to radio channels through the PVR client
  • PVR show TV guide and navigate guide
  • Show info - all media including PVR Channel

Kanzi Master Features Retained;

  • Basic navigation (Up/Down, Left/Right, Page Up/Down, Select, Back, Menu, Zoom, Rotate, Move)
  • Open library views (Movies, Shows, Music, Artists, Albums, Music Videos, Playlists)
  • Open library views by genre (Movies, Shows, Music, Music Videos)
  • Open recently added playlists (Movies, Episodes, Albums, Music Videos)
  • Playback control (Play/Pause, Skip, Previous, Stop, Step/Jump)
  • Adjust volume
  • Shuffle all music by an artist
  • Play/Shuffle specific album
  • Play/Shuffle the latest album by an artist
  • Play a specific song
  • Play/Shuffle audio and video playlists
  • "Party mode" for music (shuffle all)
  • Play/Shuffle music videos
  • Play/Shuffle music videos from a specific genre
  • Play/Shuffle music videos by a specific artist
  • Shuffle all episodes of a TV show
  • Play random TV show
  • Play random TV show from a specific genre
  • Play random episode of a specific TV show
  • Play specific episode of a TV show ('Play season 4 episode 10 of The Office')
  • Play random movie
  • Play random movie from a specific genre
  • Play specific movie
  • Play trailer for a movie in your library (requires plugin.video.youtube addon)
  • Play random music video
  • Play random music video from a specific genre
  • Continue watching next episode of last show that was watched
  • Play next episode of a show
  • Play newest episode of a show
  • Recommend media to watch/listen to
  • List/Play recently added media
  • List available albums by an artist
  • Clean/Update video and audio sources
  • "What's playing?" functionality for music, movies, and shows
  • Report time remaining on current media and when it will end
  • Cycle through audio and subtitle streams
  • Search for something in your library (requires script.globalsearch addon)
  • Execute addons
  • Shutdown/reboot/sleep/hibernate system
  • Toggle fullscreen
  • Eject media

Instead of providing the exact verbiage here for each command, we strive to make the experience as natural as we can. Simply try asking for what you want in a way that feels right to you. If a particular phrase doesn't work and you think it should, see Getting Help to notify us and we will see what we can do to accommodate the phrase you prefer.

Getting Help

If you need help getting a server going or configuring the Skill, please visit the support thread on the Kodi forum.

If you run into an actual issue with the code, please open an Issue here on Github; however, most issues you might run into will be a result of the complexity of the installation, so we urge you to first search the support thread for your issue. If you cannot find a resolution for your issue with a search, post there and someone will help you determine if your problem lies within the skill code or your particular configuration.

Upgrading From a Previous Version

Upgrading the skill from a previous version includes a lot of the initial setup described here, with a few exceptions and a few additional considerations. Therefore, it is very important that you consult the additional documentation in UPGRADING.md before you attempt to update the skill.

Installation

Initial Computer Setup

There are a few things you will need to install before you can get started:

Kodi Setup

Before a command from Alexa can be sent to Kodi, you need to enable the following settings found under Settings -> System -> Services -> Web server in Kodi:

  • Allow remote control via HTTP
  • Allow remote control from applications on this system
  • Allow remote control from applications on other systems

Note that wording might change depending on the version of Kodi you have installed. This example is for Kodi 17:

Kodi settings

Next, supply a Username and Password that you don't use anywhere else. You can share these credentials with all of your Kodi installations, but you should not use the same credentials you might use elsewhere on the web.

Repeat this for every installation of Kodi you have that you wish to control via the skill. All of this information -- including the port number -- can be the same for every installation of Kodi if you wish. If you are unsure, set up every instance of Kodi the same way to avoid confusion.

Unless you have a very specific reason to do so, there is no reason to change the port number from the default. Your router will control access from the outside world.

Make note of the port, username, and password you are using for later steps.

If you have more than one instance of Kodi you would like to control with this skill, make note of the private IP address for each machine as well. Private IP addresses are typically addresses like 192.168.1.9 or 192.168.0.23

Note regarding MySQL and performance

If you are using MySQL as a database backend for Kodi, please note that there are known issues with the optimizer in MySQL 5.7.6+ that will cause any commands that involve queueing items in bulk to be tremendously slow. There is nothing in the skill we can do to fix this, as it is technically a MySQL bug/limitation; however, you can either stay on MySQL < 5.7.6 or you can easily migrate to another that doesn't have this problem, such as MariaDB.

As far as we are aware, SQLite (the default) and Emby do not share this issue.

Obtaining Your Internet Address

This skill is hosted in the "cloud," unless you opt to host it yourself locally. As such, it will need to know your internet address to contact Kodi.

While you can use your public IP address, with most residential internet providers this address can change over time, which would necessitate setting up the skill again.

To avoid this, before you continue, we suggest you set up what's called a Dynamic Domain Name with a service provider such as Dynu. HowToGeek.com provides a guide for setting this up.

Whether you choose to use your public IP address or obtain a dynamic domain name, make note of it before continuing.

Router Setup

Unless you are hosting the skill locally, it is required that you have the Kodi web server(s) opened up to the internet via port forwarding on your router.

For each Kodi instance, you will need a port forwarding rule on your router. For each private IP address (i.e., the local address of each machine on which Kodi is installed), you need to forward a unique external port to that private IP address on your router.

If you followed our suggestion and set up all of your Kodi instances with the default port, you would forward them all like so:

  • Kodi1: external port 8080, internal -> 192.168.1.10:8080
  • Kodi2: external port 8081, internal -> 192.168.1.11:8080
  • Kodi3: external port 8082, internal -> 192.168.1.12:8080

And so on for each instance of Kodi that you wish to control via the skill. The key here is that the external port number needs to be unique for each instance.

For more information on port forwarding, see this HowToGeek guide.

Skill Deployment

Choosing a Deployment Method for the Skill

When you ask an Amazon Alexa skill to do anything, it ultimately contacts another web server which executes code to process your request. This skill isn't any different, and needs such a server as well.

For the purpose of this readme, AWS Lambda is the working option:

AWS Lambda

Pricing

Lambda is a great service which lets the skill run "serverless." AWS provides credits for new accounts and should allow you to run everything the skill needs for free for 12 months. Once you are being billed for it, it will be less than $0.20/month. Very reasonable for what it offers.

Setup

Getting going on Lambda is pretty straightforward. First, you'll need to create an Amazon developer account if you don't have one already. After that, browse to the IAM Management Console where you will create a new user:

First page You can enter whatever username you want here, but make sure that Programmatic access is checked.

Second page Attach the 'AdministratorAccess` permission to the new user.

Third page Confirmation page should look like this.

Fourth page Once you get here, do not leave the page! You need the Access key ID and Secret access key for the next step. If you close now you'll have to create a new user. You can't get access to the Secret access key again.

Next, run these commands to configure your computer for AWS service access: pip install awscli and then aws configure. Just follow the prompts, and copy paste the keys when it asks for them. When it asks for location, if you are in the US, enter: us-east-1, and if you are in Europe: eu-west-1.

After you've done that, run pip install virtualenv. This is required for a later step.

Now, clone my repo: git clone https://github.com/fb42000/kanzi.git and cd kanzi. Once you are inside the project directory, you're going to create a new "Virtual environement" and then activate it: virtualenv venv and source venv/bin/activate (if you are on Windows, that's venv\Scripts\activate.bat or venv\Scripts\activate.ps1 for Powershell).

Next you need to create the file kodi.config from the kodi.config.example template and enter the correct information for: address, port, username, and password. I'll go over the other variables in another section below.

After you've created your config file, run pip install -r requirements.txt and pip install packaging zappa lambda-packages.

Before you can send any code to Lambda, you'll need to set up Zappa. Just run zappa init and accept the defaults for everything. If it doesn't automatically detect that this is a Flask app, tell it that the application function is alexa.app.

THIS IS THE IMPORTANT BIT TO GET PVR FEATURES

Before the skill is deployed, to get the working PVR features you need to overwrite the kodi.py file with the one from my kodi-voice repo kodi.py

Save this file and overwrite the kodi.py in the created directory /kanzi/venv/lib/python2.7/site-packages/kodi_voice/ with kodi.py.

If this does not happen prior to next step below you will not get PVR functions

Ok now we can carry on...

To make an initial deployment to Lambda, just run the following command: zappa deploy dev. It'll take a few minutes, and at the end it will give you a URL that you will need to copy. It will look like this: Lambda deploy

You are now running on Lambda! To update after there is a change here, or you updated your env variables, see the instructions in UPGRADING.md.

Now skip ahead to Skill Setup.

Skill Setup

Once you've set up your server, you'll need to configure an Interaction Model for your skill.

If you don't yet have an Amazon Developer account, you'll need to create one by visiting here and logging in with your usual Amazon credentials. Fill in the required fields, agree to the terms, and answer, "No," when asked if you're going to monetize your apps.

Then, head over to the Skills list on Amazon's developer page and hit the Add new skill button.

Skill Information

This is info updated to all readme based on the new Alexa Developer Console

Inital setup skill

Enter a Skill Name, enter Kodi

For Language, choose your native language. - Repo default is English(UK) - Note any other language files for intents etc will need translation

For Choose a model to add to your skill, select the square Custom.

Then select the blue button Create Skill

On the next page

For Choose a template, select the square Start from Scratch. Yes this may seem a daunting selection but included in the repo is a JSON schema that will fill in lot of the gaps for you

Then select the blue button Choose

You will then be greated with the new Alexa Developer Console.

Developer Console Skill

Alexa Developer Console

This is the area that Alexa will use to pass information to the skill that we've deployed earlier. It will not enable the skill until all four requirements listed down the right hand side are met.

So, here we go, in a change to anything previously published on a readme, this 'should' be a relatively simple painless process as the hard work is done;

First, if you scroll down to JSON Editor and select

When the main window opens, select Drag and Drop a .json file

Then, drag the file IntentSchema.json from your local Kanzi folder (sub folder speech_assets) created earlier

Select Save Model

It will come up with an error on the first attempt as we have not yet set an Invocation. A pop up will even advise you of this

To resolve this error, (do not select another item and then OK in the prompt otherwise you will lose all the JSON code inserted); In the JSON editor window scroll to Line 4 "invocation name" and insert within the RED inverted commas a Name (it can be anything at this stage just to move past the 'error')

Select Save Model This should then populate all the intents and slots and allows you to select your prefered invocation name below. Note it will still report an error when saving as we then need to populate the custom slot values, but all the main JSON schema is now saved.

JSON Editor

To set the Invocation properly (if you need to change the name you used above);

For Invocation, select the word Invocation on the left hand menu. This is the skill invocation name that you will call after the wake word, i.e "Alexa, ask my telly..." where "my telly" is the invocation word (or words). Note the requirements and limitations, this can be changed at any time as this skill won't be published, you will however need to re build the skill each time it is changed.

Select Save Model - get into the habit of using this on every item you change / do - it may help but certainly wont hinder. It will also show a pop up if saved OK or if there is an issue so it is easier to trace the steps to any errors created

Invocation Name

We should now have populated INTENTS with (146) items and SLOT TYPES with (20)

Populated intents

Now we need to populate the Slot Types to stop it complaining about errors (Slot types cannot be empty). This is where it gets personal though so a bit of work to do;

For each slot type it's best to insert all your content, i.e. Movies will need to be filled with all your library movies. This allows the skill to recognise what it is looking for.

Handy as there is an easy way to do this, thanks to the either the web app created by the original dev here. or by running the updated generate_custom_slots.py ;

The web app does however limit the values to a max 100 and therefore for larger libraries running the python script from within the site packages folder alongside a copy of your kodi.config will create a fuller list of slot values to import. This will create txt files with the relevant information which you can then bulk import to each slot value in the developer console. If one of your slots is empty, you can just enter the word 'Empty' or something so that it'll save."

Once it has run you can select and copy each bulk output from each slot type, copy and pasting them as plain text into the Bulk Edit option on each slot type window

Movie Example Screenshot Slot types

Select Submit on each one done and also Save Model

Repeat for;

SHOWS

SHOW GENRES

MOVIES

MOVIEGENRES

MUSICVIDEOS

MUSICVIDEOGENRES

MUSICALBUMS

MUSICSONGS

MUSICGENRES

MUSICPLAYLISTS

VIDEOPLAYLISTS

ADDONS

If you have no slot values to copy over, then you need to ensure you enter at least one Slot Value, "Empty" will be OK

The remaining Slot Types you wont have from this method, or by running the python script, are for CHANNELS and BROADCAST, RADIOCHANNELS, RECORDCHANNEL, RECORDBROADCAST. These are the PVR elements.

I have included a csv file uk_fta_channels.csv for a list of UK FTA TV Channels that I use, this includes the main freeview and freesat channels in the UK. Also a csv file of UK Radio stations (plus an IPTV station I listen to). These are processed in the same way as the TV channels.

If the included file is of use to you, (ie you are in the UK and most if not all of your channels are on it) then skip this next section

Channel Slot Values (Non UK)

If you are not in the UK or all your channels are not listed then the method to get your channel list is as below,

In a web browser address bar, use the JSON request (replacing my.kodi.ip.address:port with your IP:port to your kodi instance);

http://my.kodi.ip.address:port/jsonrpc?request={"jsonrpc": "2.0", "method": "PVR.GetChannels","params":{"channelgroupid": "alltv"},"id": 1}

You should be prompted with your kodi username and password (if not you haven't set up the earlier config process properly)

This will return a JSON list of all of your channels, channel id's and channel labels (real life names). My working version is using TVHeadend as the backend PVR and doesn't pick up actual channel numbers although it is a work in progress for it to.

For a list of your radio channels, replace "alltv" with "allradio" in the JSON request - the process is then the same.

Next we can convert the above JSON list by using an online convertor. I found "convertcsv" website to work well however we cannot be responsible for the use of any external links. Copy and paste the full list output from the above JSON command into the convertor and create your csv text or an excel / ods .csv file.

One thing I needed to do from the converted JSON output in the csv format is to move the channel label column to be read first (ie Column A) as this is what you are more likely to speak rather than a channel id (channel id is not to be confused with channel number - they are not the same or certainly not in TVH)

Once you have your csv file save it within the Kanzi folder created earlier

Channel & Broadcast Slot Values (UK & Non UK)

Now we have a csv file with all our channels on it, we can bulk edit it into the Slot Type

Select CHANNELS under Slot Types on the left hand menu, then select BULK EDIT

Drag and drop the csv file UK users - uk_fta_channels.csv or for Non UK - the csv file created above

Select Save Model

Repeat this process for BROADCASTS

Select Save Model

The process is then the same if you wish to use the radio channel slot type, using the the values from uk_radio.csv or your own created by running "allradio" as above.

The record channel and record broadcast slot types are still a work in progress - you can populate the slot values in the same method as above for Channels & Broadcast.

If you have no need for the radio or record functions you will need to delete the slot types in the developer console.

There should now be no error complaints from the developer console

Save Model Error Free

Endpoint

The last step in the developer console is to insert your endpoint. This is where the skill points to the lambda instance where this was setup under AWS Lambda Setup above. You 'should' have copied an address from this stage here;

"To make an initial deployment to Lambda, just run the following command: zappa deploy dev. It'll take a few minutes, and at the end it will give you a URL that you will need to copy" If you didn't then you can re run by using the steps from activate virtual environment and updating. This will then confirm the address.

Select Endpoint, then select radio button "HTTPS"

Copy and paste the address saved earlier into the "default region field" and on the drop down box below select "My development endpoint is a sub domain ........."

Select Save Endpoint

Then Select Invocation, select Save Model, then Build Model

Give it time to build (approx up to 1 minute)

If all saves and builds correctly without errors, selecting Custom will show all four green ticks now complete on the right hand menu

Testing

First before you test you need to enable the skill in your Alexa App. Under Skills & Games, Your Skills, Dev Skills. Select your skill name and enable

Either test with your Echo device, try for example "Alexa, ask my telly to change to bbc one" (or one of your known channels using the invocation name you chose)

or with the developer console built in test facility

In the developer console, on the main menu bar

Select Test

Enable using the slider to enable

Type a command in the input box

try for example "ask my telly to change to bbc one" You don't need the wake word when using the developer test

Your kodi instance should then react and the return in the box will be printed

Test Complete

Additional Validation of Requests

To verify that incoming requests are only allowed from your own copy of the skill, you can set the skill_id configuration variable to your own Application ID; e.g., amzn1.ask.skill.deadbeef-4e4f-ad61-fe42-aee7d2de083d

Extra Settings for More Functionality

Setting the timezone configuration variable will make it so when you ask how long something has left playing, it'll also tell you when it will end according to your local wall-clock time.

Setting scheme to https allows you to talk to Kodi securely, but this requires that you set up a reverse HTTPS proxy.

By default, the skill allows very generic queries such as, play 99 red balloons or shuffle the office. These very generic commands can be slow however, and may cause timeouts. If these timeouts bother you, you can direct the skill to provide help playing media more specifically instead when it encounters these kinds of requests, by disabling deep_search.

Controlling More Than One Instance of Kodi

As of version 2.6 of the skill, it can now control more than one instance of Kodi. The skill determines which instance to talk to by determining which Echo device received the command.

You set up the mapping in the kodi.config file. There are a few examples there with dummy device IDs.

If a device ID isn't explicitly present in the config file, it will utilize the details in the [DEFAULT] section. So, for example, if you wanted most of your devices to send commands to Kodi in your living room, you would set the [DEFAULT] section to point at that instance. For any that you want to override -- say, office and master bedroom -- you would define override sections with those device IDs.

Further, for override sections, if a variable isn't defined, it will inherit it from the [DEFAULT] section. Thus, if the only thing you need to change is address and port, define just those in the override. You do not need to copy all of the other variables as well.

Getting the device IDs

When you send a request to the skill, it will log an entry on the skill's server that will look something like this:

Sending request to http://mydomain.com:8080/jsonrpc from device amzn1.ask.device.AEFDXCGLSFJFNGCVF8SDJF90FID9G284JDJFGJGHH83358DJFFGIGD734JJDFGK211GDFFHHH23HGFJTYEFGJRT56KJDHDFJ5546DJDFFSWOPPP677P88P873EHZNZDFEIRTYIN2239NDFGIH724JDFKS2AA

For AWS Lambda/Zappa deployments, you can access your logs with:

zappa tail dev

To generate your override sections, you will want to tail (watch the end of) the log file and send any request (like, Alexa, ask Kodi what is playing?) from the Echo device you wish to override. Look for a line that looks like the above. The device ID is everything from amzn1.ask.device. to the end of the line. Copy this text and paste it to the end of the kodi.config file, placing it within square brackets [], like so:

[amzn1.ask.device.AEFDXCGLSFJFNGCVF8SDJF90FID9G284JDJFGJGHH83358DJFFGIGD734JJDFGK211GDFFHHH23HGFJTYEFGJRT56KJDHDFJ5546DJDFFSWOPPP677P88P873EHZNZDFEIRTYIN2239NDFGIH724JDFKS2AA]

Anything in square brackets denotes a new section. In this section, you can override whatever variables you'd like. In this example, this Echo device is my Echo Dot in the office, so I would do something like:

# Office Echo Dot
[amzn1.ask.device.AEFDXCGLSFJFNGCVF8SDJF90FID9G284JDJFGJGHH83358DJFFGIGD734JJDFGK211GDFFHHH23HGFJTYEFGJRT56KJDHDFJ5546DJDFFSWOPPP677P88P873EHZNZDFEIRTYIN2239NDFGIH724JDFKS2AA]
address = office-dot

Developer discussion

If you're interested in chatting with us about the development of the skill, we are on Slack.

About

Alexa skill for controlling Kodi

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python 100.0%