Add-on:Kodi Callbacks: Difference between revisions

From Official Kodi Wiki
Jump to navigation Jump to search
Line 172: Line 172:
{| class="wikitable"
{| class="wikitable"
|+ Event listing
|+ Event listing
! Player Publisher !! Monitor Publisher !! Loop Publisher !! Log Publisher !! Main Thread || Watchdog
! Player Publisher !! Monitor Publisher !! Loop Publisher !! Log Publisher !! Main Thread || Watchdog || Schedule
|-
|-
| onPlayBackStarted || onCleanStarted || onStereoModeChange || onLogSimple || onStartup || onFileSystemChange
| onPlayBackStarted || onCleanStarted || onStereoModeChange || onLogSimple || onStartup || onFileSystemChange || onDailyAlarm
|-
|-
| onPlayBackEnded || onCleanFinished || onProfileChange || onLogRegex || onShutdown|| onFileSystemChangeAtStartup  
| onPlayBackEnded || onCleanFinished || onProfileChange || onLogRegex || onShutdown|| onFileSystemChangeAtStartup || onIntervalAlarm
|-
|-
| onPlayBackEnded || onDPMSActivated || onWindowOpen ||  || ||  
| onPlayBackEnded || onDPMSActivated || onWindowOpen ||  || || ||  
|-
|-


| onPlayBackResumed || onDMPSDeactivated || onWindowClose ||  || ||  
| onPlayBackResumed || onDMPSDeactivated || onWindowClose ||  || || ||  
|-
|-


| onPlayBackSeek || onNotification || onIdle ||  || ||  
| onPlayBackSeek || onNotification || onIdle ||  || || ||  
|-
|-


| onPlayBackSeekChapter || onScanStarted || onResumeAfterIdle ||  || ||  
| onPlayBackSeekChapter || onScanStarted || onResumeAfterIdle ||  || || ||  
|-
|-


| onPlayBackSpeedChanged || onScanFinished ||  ||  || ||  
| onPlayBackSpeedChanged || onScanFinished ||  ||  || || ||  
|-
|-


| onQueueNextItem || onScreensaverActivated ||  ||  || ||  
| onQueueNextItem || onScreensaverActivated ||  ||  || || ||  
|-
|-


|  || onScreensaverDeactivated ||  ||  || ||  
|  || onScreensaverDeactivated ||  ||  || || ||  
|}
|}



Revision as of 19:57, 27 February 2016

Kodi Callbacks
{{{icon url}}}

See this add-on on the kodi.tv showcase

Author: KenV99

Type: Services
Repo:

License: GPL v2.0
Source: Source code
Summary: Callbacks for Kodi Events to launch user tasks
Home icon grey.png   ▶ Add-ons ▶ Kodi Callbacks
Attention talk.png Need help with this add-on? See here.

Perform custom user-defined tasks for multiple events in Kodi

Installing

This add-on is installed from the Add-on browser located in Kodi as follows:

  1. Settings
  2. Add-ons
  3. Install from repository
  4. Services
  5. Kodi Callbacks
  6. Install

Features

  • Runs as a service when Kodi starts
  • Runs user configured tasks when events occur in Kodi
  • Currently can create tasks for:
  1. Running an external script with or without the shell
  2. Running an external python script either directly or via dynamic import
  3. Running a Kodi builtin
  4. Sending an http string (response)
  • Utilizes a simple substitution language so that runtime arguments can be mixed with static user-defined elements to send to the external file as arguments
  • 29 different Kodi events are supported
  • Tasks can be tested directly from the Settings page with direct user feedback for troubleshooting
  • New tasks can be created and shared with others by subclassing an abstract base class and then placing the file in the resources/lib/tasks folder
  • Credit to Yesudeep Mangalapilly (gorakhargosh on github) and contributors for watchdog and pathtools modules.

Installation

Overview

The script is not currently available via the official repo (it's a localized string issue that prevents submission). You can download the zip file and manually copy it to the Kodi Add-Ons folder, overwriting the previous version.
The most recent version of the script can be downloaded here: https://github.com/KenV99/service.kodi.callbacks/archive/master.zip

Details

To manually install the script, first unzip the script to a convenient, temporary location and then copy the entire directory named ‘service.kodi.callbacks-master’ with its structure intact to the Kodi addons directory. In windows, this is typically located on your system drive at 'Users/Username/AppData/Roaming/Kodi/addons/'. If you have a previous installation, consider backing it up to a safe place before installing.

Remove the '-master' from the end of the folder name!!!

If you are replacing xbmc.callbacks2 which will no longer be developed, the settings from there are not compatible. Copy your settings over to the new addon and then disable or delete xbmc.callbacks2

Configuration

Overview

In Kodi go to System > Add-Ons > Enabled Add-Ons > Services > Kodi Callbacks > Configure

In general:

  1. Configure your task.
  2. On the next page, associate your task with one or more events.
  3. Click OK to save.
  4. Re-enter settings by clicking configure.
  5. Test your setup via the settings page.
  6. Re-test by triggering your event if possible.

Details

There are three pages of settings - Tasks, Events and General

Settings - Tasks

Kodi-callbacks-settings1.PNG

You can configure up to 10 tasks.

For each task, select a type - builtin, http, python or script.

For all you can configure:

  1. The maximum number of this task that can be running simultaneously
  2. The maximum number of times this task can be run for a given Kodi session
  3. A refractory period after a task is run where it won't be re-run

For different types, there may be additional parameters to configure:

  • For scripts:
    1. Whether the script requires the shell to run. In the majority of cases this is NOT needed. The addon will use bash on *nix or sh on Android for any .sh files.
    2. Also, whether the program should wait for the task to complete (useful to wait during testing if the outside script prints to stdout which will be displayed).
    3. Under some circumstances such as launching a daemon-like program, it may be desired NOT to wait for completion.
    4. NOTE: The script file line is displayed twice: the first opens a file picker dialog. The second will allow you to edit the line or you can enter text directly. This allows you to use standard naming short cuts (i.e ~/.) or otherwise edit the way the command is sent to the interpreter instead of being committed to only picking a file.
  • For python:
    1. Execute the python file directly OR
    2. Import the file as a module and call whatever is designated within as 'run' - arguments will be passed as run(args)
  • For http optionally a username and password can be provided for Basic Auth only.

Note the task number as that is how it will be referred to on the next settings page.



Settings - Events

Kodi-callbacks-settings2.PNG

You can configure up to 10 events and have each use a different task or reuse the same task.

For each event, select an event type. There are currently 29 different events.

For some events, additional information is required:

  1. For JSON notification events, the sender, method and data are required.
  2. For Window Open and Close events, the window id is needed (see: Kodi Window Ids).
  3. For on Idle events, the idle time in seconds (note that idle is when there is no user interaction and no media is playing).
  4. For on Resume after Idle events, the idle time in seconds. This event will fire only after there is user activity after the defined idle time.
    1. All of the timers for on Idle and on Resume After Idle events are completely independent of one another and multiple definitions of idle time is supported.
    2. For example setting an on Idle event to dim your lights after 600 seconds and turn them off after 1200 seconds.
    3. Using on Resume After Idle, one could also set an event to turn them back on with user activity after 601 seconds, if desired.
  5. For detecting when a portion of a string is written to the log onLogSimple and and onLogRegex require 'matchIf' strings.
    1. A simple match detects a case-sensitive substring in an individual log line, while a regex match matches whatever you configure it to on a line.
    2. Log strings can also be rejected if a different portion matches 'rejectIf'.
  6. For File System Change events, the folder to be monitored, the file or folder patterns to monitor (ie. *.txt, *.*), the patterns to reject, whether to monitor folder changes and whether or not to monitor subfolders (recursive)
    1. For multiple patterns, separate them with a comma without spaces (i.e. "*.mkv,*.mp4,*.mov")
    2. Similar to Script Tasks, there are two lines on the settings page for the folder. The first is a standard folder picker and the second is a free text field. This allows one to edit or type the folder directly. The free text line will allow translation of Kodi's special directories (i.e. special://) as well as OS specific substitutions such as '~/.' or %appdata%.
    3. In many cases monitoring folder changes is not desirable as it may create two events for each change (i.e. adding a file causes a fileAdded event AND a folderChange event).
    4. Note that on OSX, this publisher will use a low-performing, resource intensive polling routine. If this presents an issue and you are adept, install watchdog via 'pip' and then go to your site-packages directory and copy over _fsevents.so and _watchdog_fsevents.so to the resources/lib directory.
  7. There is a separate File System Change at Startup event
    1. This takes a snapshot of any monitored folders during a normal Kodi shutdown and saves it in the addon_data folder.
    2. The snapshot is reloaded at startup and compared to a new snapshot to detect changes, using patterns as above.
    3. If any changes are detected, a single event is fired. The user can obtain the list of changes via argument substitution, if desired.
Argument variable substitution

A variable substituted argument string can then optionally be provided to pass additional information to your task.

The variables that can be passed are dependent on the event and are shown on the settings page.

Only the variables shown will be searched for and substituted.

To ensure that literal percent signs are passed correctly, use '%%'.

Because of the way arguments are passed to script files and python files, they are usually split where spaces or commas occur.

If you need to ensure that a space is not split, use %_ (percent underscore) and for a comma, use %__ (percent underscore underscore).

Spaces can also cause problems when they appear in the substituted variables.

Depending on how your file processes arguments, consider placing double-quotes around variables that may contains spaces such as titles, filenames and loglines.

Note: If you wish to use the On Shutdown event to run a script after Kodi exits, one would use a task script which does not wait and pass out the pid (%pi) to the script. The script can then be configured to wait until the pid is no longer running and then execute the desired code. Look in the resources/lib/tests folder for onQuit.bat and onQuit.sh for example code using this technique.

Testing

A fully configured event can be tested from the Event Settings Page.

First click OK to cause any changes made to be written to the user settings file.

Then re-enter Settings and navigate back to the event to be tested and click "Test command'.

First some simple validation tests will be run and if they fail, this will be reported back to the user on the screen.

Then an attempt will be made to run the task with simulated runtime arguments (i.e. the filename, title, etc will be simulated).

NOTE: The test will, in most circumstances, wait for the task to 'return'. So if the task launches a program, no further information will be provided until that program ends.

Exceptions or any returned text will then be displayed.

List of events

Events are monitored by different publishers. The events are published as topics. Tasks then subscribe to specific topics. For performance reasons, true decoupling was not achieved in this Publish/Subscribe pattern, in that only subscribed window open and close events and log matching events are published. Publishers are only started if there is a subscription to one of the topics it publishes.

Event listing
Player Publisher Monitor Publisher Loop Publisher Log Publisher Main Thread Watchdog Schedule
onPlayBackStarted onCleanStarted onStereoModeChange onLogSimple onStartup onFileSystemChange onDailyAlarm
onPlayBackEnded onCleanFinished onProfileChange onLogRegex onShutdown onFileSystemChangeAtStartup onIntervalAlarm
onPlayBackEnded onDPMSActivated onWindowOpen
onPlayBackResumed onDMPSDeactivated onWindowClose
onPlayBackSeek onNotification onIdle
onPlayBackSeekChapter onScanStarted onResumeAfterIdle
onPlayBackSpeedChanged onScanFinished
onQueueNextItem onScreensaverActivated
onScreensaverDeactivated



Settings - General

Kodi-callbacks-settings3.PNG

The addon can optionally show a brief notification each time a task is run.

Polling frequencies can be configured. If you have a low powered system and performance suffers causing video stuttering, consider increasing the times.

The Loop Frequency is for events such as onIdle, onWindow open or close, profile changes and stereomode changes.

The Log frequency is for the log checker.

The Task frequency is for the main task dispatcher.


An option is provided to elevate all routine messages to the normal log, instead of the debug log.

A request has been made by the Kodi developers that addons avoid writing to the normal log and will be the default in Krypton and beyond.

This setting allows you to selectively elevate messages to the normal (non-debug) log for troubleshooting and then turn it back off once fixed.

This avoids having the user turn on the full debug mode with its OSD.

You can click to regenerate the addon's settings.xml file. This is only needed if you have created your own custom task and placed it in the resources/lib/tasks folder. This will read in whatever settings you need so that they appear on the settings pages.

Last, you can run a test to ensure that tasks are working properly on your system. The results will be found in the log. You may see the debug OSD come on briefly and the system mute toggle on and off. The results may be separated in the log so look through carefully. This has been test to work on Windows, Linux Mint and Android.


Create your own custom task

Why would you want to do this?

If you have some code that does something useful and would like to make it available to others.

Specifically if your code is written in python and others would need to give it information via the settings page.

First steps

Take a look at the current tasks in the resources/lib/tasks folder and the resources/lib/taskExample file which is better documented (had to be placed here to avoid it's auto-discovery).

Each imports a few standard needed things and then defines a class that subclasses resources.lib.taskABC.AbstractTask.

This abstract base class provides needed functionality to work with the rest of the code.

Note that this is itself a subclass of threading.Thread.

Class definition

At the class level, you need to define a 'tasktype'. Make it unique so that it doesn't conflict but descriptive.

Also at the class level, designate any variables that users would need to provide.

Each requires an 'id' that you will use to refer to it later in your code.

Then information in settings is used to format the way it should look on the settings page.

Refer to the Kodi wiki for the different 'types' of settings.

Class methods

Then define your __init__ and call the super.

Next you need to create a staticmethod for validate(). The user input info will be passed in as a dict with the 'id' above as the key. Return True if the input is valid, False if it's not.

Lastly, define run(). This is the code that will be run when the event occurs.

The reformatted variable substituted user args can be accessed via self.runtimeargs. This is provided as a list. Rejoin as necessary or overload self.processUserargs.

The original task variables are a dict keyed for 'id' as above (self.taskKwargs).

Try not to raise exceptions in your code. Assemble return information or errors in a 'msg' string and set err=True if an error occurred.

The last thing the run code block should do is call self.threadReturn(err, msg).

Once your custom task is placed in the proper folder, the settings.xml file for the addon needs to be regenerated via the third settings page (see above).

Post questions on the forum. Better to put them in public and not message me directly so that others can read and learn and so I don't answer the same question privately over and over.


Notes

The log checking events consume the most resources and regex checks utilize more than simple checks.

The watchdog file system watcher may also consume a lot of resources, depending on the system.

The loop checking items consume the next most (onStereoModeChange, onProfileChange, onWindow Open or Close and onIdle/afterIdle).

Each publisher is only started if there is a task configured that utilizes an event that it generates.

FAQs

I need to a respond to an event that isn't listed as an event. Can you make it so that I can?

Most likely, no. Pretty much everything that can be detected is already there.

A number of users have requested to launch a task when another addon/plugin launches. The only way to do that is for you to hack into their plugin and insert code to write something to the log which you then can detect via the log checker. There is an undocumented function using xbmcvfs that can list running addons, however, his doesn't work for plugins, only script and service addons. Plugins run in a 'detached' state and often each page click causes the plugin script to run again so detecting each run is often not exactly what one may desire.

I am having an issues, how can I get help?

The best place to get script help is in the KODI forum thread here: http://forum.kodi.tv/showthread.php?tid=256170

If you believe that things are not working as expected, please also UPLOAD A COPY OF 'kodi.log' TO: XBMCLogs or pastebin AND INCLUDE A LINK TO THE LOG IN YOUR POST!

I do not have a magic crystal ball. The program does not report back to me directly with your issue. No log link usually means no help can be provided.

The forum moderators frown upon posting your log directly in the forum.