Add-on:Kodi Callbacks: Difference between revisions

From Official Kodi Wiki
Jump to navigation Jump to search
No edit summary
m (Addon-Bot repo category update)
Tag: Manual revert
 
(121 intermediate revisions by 4 users not shown)
Line 2: Line 2:
|Name=Kodi Callbacks
|Name=Kodi Callbacks
|provider-name=KenV99
|provider-name=KenV99
|ID=service.kodi.callbacks
|ID=script.service.kodi.callbacks
|latest-version=0.9.0
|latest-version=1.0.0
|extension point=xbmc.service
|extension point=xbmc.service
|provides=
|provides=
|Summary=Callbacks for Kodi Events to launch user tasks
|Summary=Callbacks for Kodi
|Description=Perform custom user-defined tasks for multiple events in Kodi
|Description=Provides user definable actions for specific events within Kodi. Credit to Yesudeep Mangalapilly (gorakhargosh on github) and contributors for watchdog and pathtools modules.
      
      
|Platform=all
|Platform=all
|Language=
|Language=en
|License=GNU GENERAL PUBLIC LICENSE. Version 2, June 1991
|License=GNU GENERAL PUBLIC LICENSE. Version 3, June 2007
|Forum=http://forum.xbmc.org/showthread.php?tid=198173
|Forum=http://forum.kodi.tv/showthread.php?tid=256170
|Source=https://github.com/KenV99/service.kodi.callbacks
|Website=http://kodi.wiki/view/Add-on:Kodi_Callbacks
|Source=https://github.com/KenV99/script.service.kodi.callbacks
|Email=
|Email=
|repo=None
|broken=
|broken=
|icon url=http://kodi.wiki/images/0/08/Callbacks-icon.png}}
|icon url=http://mirrors.kodi.tv/addons/leia/script.service.kodi.callbacks/icon.png}}
__TOC__


== Features ==
<!-- Page content goes here -->
<br />
<br />


* Configurable default profile to use when Ambibox starts
== '''Features''' ==
* Configurable audio profile to use during audio only content
* A choice of settings to use when video playback starts
# Use a default video profile for all video content
# Display a menu of video profiles when playback starts that the user can choose from
# Automatically switch profiles based upon the aspect ratio of the video file playing (if discoverable, see below). This method requires editing of an XML file
# Turn off LEDs
* Configure XBMC to capture frames if using the XBMC Direct method of capture
* Configurable profiles to use for 3D video content (this is based strictly on the XBMC recommended filenames for video content see [http://wiki.xbmc.org/index.php?title=3D#Video_filenames_flags here])


== Installation ==
* Runs as a service when Kodi starts
* Runs user configured tasks when events occur in Kodi ([[Add-on:Kodi_Callbacks#List_of_events|jump to list of events]])
* Currently can create tasks for:
# Running an external script with or without the shell
# Running an external python script either directly or via dynamic import
# Running a Kodi builtin
# Sending an http string (response)
# Sending a Json-RPC notification
* 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
* 31 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 userdata/addon_data/script.service.kodi.callbacks/lib/tasks folder
** It is better to put user tasks here than in the addon's tasks folder since that folder may be rewritten during updates
* Credit to Yesudeep Mangalapilly (gorakhargosh on github) and contributors for watchdog and pathtools modules.
 
== '''Installation''' ==


=== Overview ===
=== Overview ===
There are three ways of installing the script currently:
<s>The script is not currently available via the official repo but has been submitted as of 27-02-2016.</s><br />
# During installation of the Ambibox program the script is copied to the correct location.
The addon is now available through the official repo (isengard forward) as of 22-04-2016!!!<br />
# You can install it directly from the Official repo.
It has one dependency - the requests module. This should automatically be installed by Kodi.<br />
# You can download the zip file and manually copy it to the XBMC Add-Ons folder, overwriting the previous version.<br />
If desired, it can also be downloaded manually copied to the Kodi Add-Ons folder, overwriting the previous version.<br />
The most recent version of the script can be downloaded here: https://github.com/AmbiBox/AmbiBox-XBMC/archive/master.zip
Or after download you can load it via the settings addon 'install from zip' action.<br />
The most recent version of the script can be downloaded here: https://github.com/KenV99/service.kodi.callbacks/archive/master.zip
 
PLEASE NOTE: If you are updating from an installation from before 2-27-2016 (version 0.9.7.6 or earlier), you will be required to reset the settings to default and re-input them. I apologize, this could not be avoided.


=== Details ===
=== Details ===


It is assumed that you have already installed the AmbiBox application prior to installing this script. To manually install the script, first unzip the script to a convenient, temporary location and then copy the entire directory named ‘script.ambibox’ with its structure intact to the XBMC add-ons directory. In windows, this is typically located on your system drive at 'Users/Username/AppData/Roaming/XBMC/addons/'. If you have a previous installation, please back it up to a safe place before installing.
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!!!


== Configuration ==
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 ===
=== Overview ===


In XBMC go to System > Add-Ons > Enabled Add-Ons > Services > AmbiBox > Configure
In Kodi go to System > Add-Ons > Enabled Add-Ons > Services > Kodi Callbacks > Configure
 
In general:
# Configure your task.
# On the next page, associate your task with one or more events.
# Click OK to save.
# Re-enter settings by clicking configure.
# Test your setup via the settings page.
# Re-test by triggering your event if possible.


Most of the features require that profiles are set up in the Ambibox program itself. It is suggested that you set up profiles (in Ambibox) for:
# Your entire screen using the capture method of your choosing. If using XBMCDirect, this will be used for all aspect ratios and 3D modes.
# For ColorMusic should you want an LED display based on sound only (Suggested choose Mode [Software] Plugins: Colormusic).
# For common video files that you play that have a different aspect ratio than your full screen (i.e. 4:3, 2.35:1), if not using XBMCDirect.
# If you use 3D, you will also need profiles that capture based on the underlying content (TAB vs SBS), again only if not using XBMCDirect.
=== Details ===
=== Details ===


[[File:Ambibox-general.png|800px|frameless|right]]
There are four pages of settings - Tasks, Events, General and Update
==== Settings - General ====
 
On the first page you can specify which IP address and port that the AmbiBox windows application is using for communication. This will typically be at the local host at 127.0.0.1 and port 3636. As shown. You can also choose to turn on or off notifications, but it is recommended that you leave them on until you are confident that things are working as expected.
==== Settings - Tasks ====
[[File:Kodi-callbacks-settings1-1.PNG|800px|frameless|right]]
 
You can configure up to 10 tasks.
 
For each task, select a type - builtin, http, python, script or json-rpc-notify.
 
For all you can configure:
# The maximum number of this task that can be running simultaneously
# The maximum number of times this task can be run for a given Kodi session
# 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:
*# 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.
*# 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).
*# Under some circumstances such as launching a daemon-like program, it may be desired NOT to wait for completion.
*# 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:
*# Execute the python file directly OR
*# Import the file as a module and call whatever is designated within as 'run' - arguments will be passed as run(args)
 
* A note on Unicode filenames and directories:
*# Please note that using scripts or python files with names with unicode characters beyond the ASCII character set for the above two task types is NOT uniformly supported on all platforms.
*# To ensure that your files work, avoid using filenames or placing the files in directories with names that are outside the ASCII character set.
 
* For http:
*# Put only the url with port here. Further specification will be done on the events page when invoking this task.
*# Optionally a username and password can be provided for Basic Auth only.
*# Choose which http request type is desired (most commonly GET or POST).
*# For POST or PUT, choose what Content-Type you want in the header.
*# Other CGI query type data (i.e ?var1=x&var2=y) will be done on the events page.
 
* For builtins:
*# See the wiki for a list of functions: [[List_of_built-in_functions]]
*# Arguments can be passed via userags when configuring the event


Next you can have the add-on check whether the AmbiBox program is running at the time XBMC starts and if it is installed, it will start it. If started this way, it will be closed when XBMC is closed. In rare circumstances, if XBMC exits with an error, AmbiBox won't be stopped. This will cause an error when relaunching XBMC because of a continued file lock on the XBMC log file. This can be remedied by closing AmbiBox manually.
* For json notifications:
*# You can configure the 'sender' string to be used during the notification broadcast
*# Note that all available data is sent in the 'data' submessage', so userargs is not utilized for this task


If you are making changes to profiles in the AmbiBox program while running XBMC, these changes will not be reflected in the menu choices in the settings pages without refreshing them. Selecting 'Refresh profiles from AmbiBox will refresh them, but it requires hitting back twice to go to the AddOns/Services page and then coming back to the Settings page for AmbiBox.
'''Note the task number as that is how it will be referred to on the next settings page.'''


The following dll is being deprecated. Although clunky, it seems that reading the video dimensions and frame rate are best done from the log and the script attempts to do that. However, in the case that fails (and it almost never does), there is a setting, if selected, that will download a third-party dll - mediainfo.dll to the script.ambibox/resources/lib folder. This dynamic link library provides added functionality to the add-on. It allows the examination of most video files at the time of playing them in XBMC in order to discover their dimensions and DAR. XBMC alone can provide the aspect ratio in most, but not all circumstances and does not provide the dimensions. Specifically, it does not provide this many times when using an external player. In addition, if using XBMCDirect and there is a need for using the highest resolution of capture (this is extremely unlikely), the add-on will use the information provided by mediainfo.dll to provide a full resolution video stream to AmbiBox for processing. More on this below.
[http://mediaarea.net/MediaInfo Mediainfo] is Copyright (c) 2002-2014 [http://mailto:[email protected] MediaArea.net SARL]. All rights reserved. The distribution and use is governed by a [http://mediaarea.net/en/MediaInfo/License BSD-style license].


<br clear=all>
<br clear=all>
==== Settings - Profiles ====
[[File:Ambibox-profiles.png|800px|frameless|right]]
The first option is to setup and enable a default profile. If this is not specified, XBMC will launch with whatever profile is currently being utilized by the AmbiBox windows application. This will be used for the LEDs while in the XBMC GUI. Note that if the profile is using XBMCDirect capture mode, the LEDs will remain dark since this mode only works while video content is playing.
The next option is to enable and specify a profile for use during music playback. Typically this would be a profile utilizing either the built-in ColorMusic mode or the ColorMusic plugin in the AmbiBox application. The same precautions are needed when typing in the name of the profile to ensure that it exactly matches one of your named profiles.


There are four choices for profile switching during video playback:
==== Settings - Events ====
[[File:Kodi-callbacks-settings2-1.PNG|800px|frameless|right]]
 
You can configure up to 10 events and have each use a different task or reuse the same task.
 
Click on 'Choose'. Your choice will appear on the following line after choosing. This was needed to make this work with other languages.
 
For each event, select an event type. There are currently 31 different events.
 
For some events, additional information is required:
 
# For JSON notification events, the sender, method and data are required. This uses the python xbmc.Monitor.OnNotification function. Note that this does not receive ALL notifications. This is a json notification receiver event. It is completely separate from the json-rpc-notify TASK which sends notifications.
# For Window Open and Close events, the window id is needed (see: [[Window_IDs|Kodi Window Ids]]).
# For on Idle events, the idle time in seconds (note that idle is when there is no user interaction and no media is playing).
# 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.
## 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.
## For example setting an on Idle event to dim your lights after 600 seconds and turn them off after 1200 seconds.
## Using on Resume After Idle, one could also set an event to turn them back on with user activity after 601 seconds, if desired.
# For detecting when a portion of a string is written to the log onLogSimple and and onLogRegex require 'matchIf' strings.
## 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.
## Log strings can also be rejected if a different portion matches 'rejectIf'.
# 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)
## For multiple patterns, separate them with a comma without spaces (i.e. "*.mkv,*.mp4,*.mov")
## 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%.
## 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).
## 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. Requires XCODE is installed as well.
# There is a separate File System Change at Startup event
## This takes a snapshot of any monitored folders during a normal Kodi shutdown and saves it in the addon_data folder.
## The snapshot is reloaded at startup and compared to a new snapshot to detect changes, using patterns as above.
## 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, for a space 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.
 
*When the task that is being run is an http task using either POST or PUT, anything following double question-mark "??" will be treated as payload.
*# The ?? will not appear as part of the transmitted url string.
*# What you put following the ?? should depend on the Content-Type selected for the task on the Tasks settings page.
 
'''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. See below 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.


:1) Use a default video profile. This is as above where the profile name is specified and used during video playback, similar to the default and audio profiles.
Then an attempt will be made to run the task with simulated runtime arguments (i.e. the filename, title, etc will be simulated).
:2) Autoswitch based upon AR. This option attempts to read the aspect ratio of the video file and then chooses a profile based upon that aspect ratio.  


:Using this mode requires that the user has setup different profiles for different aspect ratios in the AmbiBox windows application. For instance for users with standard HD sets, there might be a profile for video that is fullscreen 16:9 such as most full screen HD television shows, another for 4:3 for most SD television shows and one at 2.35:1 or 2.40:1 for many movies. These are configured on the next two pages of settings.
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.'''


:3) Show Menu of profiles. Using this option, at the time of video playback, a menu of the currently available profiles that have been setup in the AmbiBox windows application is displayed and the used may select which profile to use. One thing to note is that for users utilizing external video player applications, such as MPC-HC, the player will cover the XBMC window and the menu of choices. This would require the user to minimize the player window temporarily in order to access the menu.
Exceptions or any returned text will then be displayed.


:4) Turn off LED’s. The LED’s are off during video playback.
===== 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.
 
{| class="wikitable"
|+ 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
|-
| onPlayBackPaused || onDPMSActivated || onWindowOpen ||  || || ||
|-
 
| onPlayBackResumed || onDMPSDeactivated || onWindowClose ||  || || ||
|-
 
| onPlayBackSeek || onNotification || onIdle ||  || || ||
|-
 
| onPlayBackSeekChapter || onScanStarted || onResumeAfterIdle ||  || || ||
|-
 
| onPlayBackSpeedChanged || onScanFinished ||  ||  || || ||
|-
 
| onQueueNextItem || onScreensaverActivated ||  ||  || || ||
|-
 
|  || onScreensaverDeactivated ||  ||  || || ||
|}


Next, there is an option to indicate that the AmbiBox windows application is using a screen capture mode with the XBMCDirect method. This method of capture can only be utilized when using the native video player and thus can be turned off if not using XBMCDirect or are using an external player. The following setting configures the amount of data sent to AmbiBox for processing. In most circumstances, this can be left on low. In testing on an LED setup with 140 LEDs, the accuracy of the lights was the same between low and the highest setting. Keeping the setting on low ''may'' decrease processing overhead and the may be desired on systems with limited processing power. At the highest setting, full frame video is sent for processing. The other settings are in between. In the case that the highest setting is chosen and the actual video dimensions can not be discovered, video at the dimensions of the display is sent.


Last, there is a setting to disable the LEDs when the screensaver is started. If the user has manually turned off the lights (Hotkey Cntrl-F7) the LEDs will NOT be re-enabled when waking from the screensaver.


<br clear=all>
<br clear=all>
==== Settings - 2D Aspect ratio profiles ====
 
[[File:Ambibox-2DAR.png|800px|frameless|right]]
==== Settings - General ====
These are the settings that are used when using the '''Auto switch based on AR''' mode. Here, the profiles that have been previously configured in AmbiBox to be used with full screen video of various aspect ratios are configured. The default is None. If no profile is configured for a given aspect ratio, the next closest one will be chosen.
[[File:Kodi-callbacks-settings3-1.PNG|800px|frameless|right]]
 
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. <u>This is only needed if you have created your own custom task</u> and placed it in the userdata/addon_data/script.service.kodi.callbacks/lib/usertasks folder. This will read in whatever settings you need so that they appear on the settings pages.
 
You can force the addon to log all of it's settings to kodi.log. PLEASE do this if you are uploading a log to ask for help troubleshooting.
 
If you have the [http://addons.kodi.tv/show/script.xbmc.debug.log/ Kodi log uploader addon] installed, then you will see a clickable link to send your log directly from this page.
 
 
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 tested to work on Windows, OSX, Linux Mint and Android. There may be an issue detecting a successful builtin test on Jarvis. This will be corrected soon. On Android, python imports cannot be correctly tested, but the method works and has been tested directly.


<br clear=all>
<br clear=all>
==== Settings - 3D Aspect ratio profiles ====
[[File:Ambibox-3DAR.png|800px|frameless|right]]
Similar to the previous page, here the use of profiles configured with the use of 3D content can be configured. First, there is a toggle to attempt to use these modes. There is currently no standard way that video files are tagged as containing containing 3D content. XBMC and hence the plugin senses this through the way the file is named (see above).


<br clear=all>
==== Settings - Update ====
== Notes ==
[[File:Kodi-callbacks-settings4-1.PNG|800px|frameless|right]]
 
Before any update via this page, the current installation is backed up to the addon_data folder for this addon under the sub-directory backup.
 
The last five backups are kept.
# FOR THE NONREPO BRANCH ONLY (this is the version that is not in the official Kodi repository and must be downloaded and installed manually - may be better if you want to participate in development):
## Downloading and installing from Github directly in the addon is not allowed in the official repository, this the need for a separate branch.
## These additional functions are useful to developers especially for multiplatform testing. If you want to develop your own task, consider downloading and installing the nonrepo branch.
## Developers will need to manually edit a couple of lines to point to their own clone on Github. Ask on the forum if you need help with this.
## The typical install from zip from Kodi will overwrite your directory including anything that you have added including git and development gui settings if they are in the addon directory.
## These routines will prevent this from happening during the development/testing cycle and are easier to use on keyboardless systems for testing.
## The first line shows the branch name for the current installation. This corresponds to the available branch names on GitHub. If you install directly via the addon settings page or copy over, this may be inaccurate.
## Repository branch name for downloads from GitHub. When the addon runs it retrieves this info directly from GitHub. This activity triggers a warning in the log because it utilizes urlib3 via the requests module. Don't worry about the warning.
## You can choose to have the addon download from GitHub when updates are available and install them. An update is triggered when the version number is bumped in addon.xml. Don't worry, not every commit will be downloaded.
## You can allow the install to take place silently.
## You can manually trigger a check on GitHub and then optionally install the most recent even if the version is the same.
# You can also update from a manually downloaded zip file. This renames the folder name, removing the branch name so that you don't need to do it manually.
# You can also reinstall from one of the automatic backups.
 
* Note: These routines have some advantages over installing from the main addons page built into Kodi. They automatically rename the directory. They will leave any files that you have added into the directory. Only newer files will be copied over via a timestamping mechanism in most circumstances.
 
* Note: I have occasionally encountered an error while downloading from GitHub. If you see an error notification, please just try again. This has always worked for me as long as I have an internet connection.
 
== '''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 provide information via a settings page to configure it properly.
 
=== First steps ===
 
Take a look at the current tasks in the resources/lib/tasks folder and the [https://github.com/KenV99/service.kodi.callbacks/blob/master/resources/lib/taskExample.py 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.
 
You would put your own task code in an appropriately named .py file and place it in the following directory: ''userdata/addon_data/script.service.kodi.callbacks/lib/tasks''
 
=== 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.
 
'''Example scripts:'''
* To have a script execute after Kodi exits on windows while passing pid as an argument:
<pre>@echo off
:loop
tasklist | find " %1 " >nul
if not errorlevel 1 (
    timeout /t 2 >nul
    goto :loop
)
REM Put the code you want to run here</pre>
 
* To have a script execute after Kodi exits in other OS's while passing pid as an argument:


<pre>#!/usr/bin/env bash
while kill -0 $1 > /dev/null 2>&1
do
    sleep 0.2
done
# insert your code here</pre>


* Using the option to switch profiles based upon a file's display aspect ratio depends on the file being properly formatted. In some circumstances XBMC is able to provide that information to the script. If not, that information can sometimes be retrieved using a dll called mediainfo, which may be optionally downloaded and installed from the settings page. Not all files comply with formatting standards or have the correct information available. Furthermore, if the letterboxing is hardcoded into the file (i.e. there is actually black boxes in the video frame itself), this will not be detected.
* To have a script run as sudo while passing the full path to script as a parameter:
* Switching profiles for 3D content is solely based on the file name.
* XBMCDirect capture has to be enabled as a capture mode BOTH in the Ambibox program itself and in the XBMC settings. This works by mapping the memory for video frames directly in XBMC and then passing that information on to AmbiBox. Whether this is better or worse that other capture modes is highly dependent on your system. The best way to figure this out is trial and error. This method CANNOT be used if you are using an external video player such as MPC-HC.


== Limitations ==
<pre>#!/usr/bin/env bash
* For modes other than PlayClaw or XBMCDirect, XBMC must be run in fullscreen windowed mode.
bash "$*"</pre>
* If using an external player and not using mediainfo, the DAR may not be detected by the system.
* XBMCDirect does not work with external players.
* XBMCDirect will only activate the lights while playing audio or video content. The lights will remain off in the XBMC GUI.
* XBMCDirect will not work with most streaming video as opposed to playing from a file.
* For LiveTV content that is in a DAR other than your display's DAR, there may be black bars embedded in the content. If the video is not zoomed to fill the display window, the capture areas may not be capturing areas with active video content. This is true for all capture modes.
* XBMCDirect may not work with LiveTV SD content due to the black bar areas.
* XBMCDirect does NOT work with DSPlayer builds of XBMC Gotham.
* The automatic sensing of using a 3D mode in the GUI is not directly supported.
* Currently only hSBS and hTAB 3D video modes are supported and in a limited fashion.


== FAQs ==
== '''FAQs''' ==


'''Why would I want to go through the trouble of setting up all of these different profiles, my display is 16:9, why would I use other profiles?'''
'''I need to a respond to an event that isn't listed as an event. Can you make it so that I can?'''


When video files are played that have display aspect ratios that differ from your display, some people may either zoom or stretch the video so that it fills the screen. Under those circumstances, only one profile is needed because the video content reaches to the edge of the screen and can be correctly captured in order to drive the LED’s.
Most likely, no. Pretty much everything that can be detected is already there.
The other, often preferred, method of display is using letterboxing or pillaring. Black or gray bars are placed either above and below or on either side of the video in order to display the content without distortion. In this case, there is no active video content in these areas and the AmbiBox application would be capturing whatever color is in those bars if it is using a standard setup to capture around the periphery of the display. By setting up different capture profiles for content with different aspect ratios, one can capture from the edge of the active content and have the LED’s display correctly.


'''Why don’t my LED’s light while music is playing?'''
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 have set up a profile using ColorMusic and AmbiBox switches to it but the lights remain dark.
If all else fails, try looking in the log to see if something specific is written there when whatever it is that you are trying to detect occurs and then use the onLogSimple or onLogRegex events to detect your event.
AmbiBox cannot hook into the audio stream if you are using WASAPI for audio output. Please go to System -> System -> Audio Output and go to the very bottom (often times this setting isn’t seen if you do not scroll) to Audio Output Device and choose something other than WASAPI.


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


The two best places to get script help are: via the XBMC forum thread here: http://forum.kodi.tv/showthread.php?tid=198173 or via the Adafruit forums in this thread: http://forums.adafruit.com/viewtopic.php?f=47&t=36032
The best place to get script help is in the KODI forum thread here: http://forum.kodi.tv/showthread.php?tid=256170
 
If things broke after a new update, please try rebuilding your settings first:
# Note down your settings
# On the settings page click 'Default' and then click 'OK'
# Rebuid your settings
# Click OK
# Restart Kodi
 
If you believe that things are not working as expected after trying the above,
# From the 'General' Settings page:
## Turn on 'Show debugging info in normal log'
## Click OK
## Recreate your problem
## Go back to Settings and on the General page, click to write your settings into the log.
## Exit Kodi
# Find your log file: [[Log_file/Advanced#Location|Wiki: Log File Location]]
# UPLOAD AN '''ENTIRE''' COPY OF 'kodi.log' TO: [http://xbmclogs.com/ XBMCLogs] or [http://pastebin.com/ pastebin]
# INCLUDE A LINK TO THE LOG IN YOUR POST ON THE FORUM
 
Please do not turn on Kodi's debug mode before uploading a log unless asked to do so. This typically just generates more noise in the log, making it harder to pinpoint the problem.
 
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.
 
If you are going to edit python for Kodi, PyCharm is the way to go!!!
You can apply for a free license to open source projects.


If you believe that things are not working as expected, please also include the ''version number'' of the script and any ''relevant entries in the XBMC logs'' in your post.
[[File:Icon_PyCharm.png]]


[[Category:Gotham add-on repository]]
[[Category:Add-ons with license tag]]
[[Category:Add-ons with source tag]]
[[Category:Add-ons with website tag]]
[[Category:All add-ons]]
[[Category:Service add-ons]]
[[Category:Isengard add-on repository]]
[[Category:Jarvis add-on repository]]
[[Category:Jarvis add-on repository]]
[[Category:Krypton add-on repository]]
[[Category:Leia add-on repository]]

Latest revision as of 04:16, 26 September 2021

Kodi Callbacks
icon.png

See this add-on on the kodi.tv showcase

Author: KenV99
Website: link
Type: Services
Repo:

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

Provides user definable actions for specific events within Kodi. Credit to Yesudeep Mangalapilly (gorakhargosh on github) and contributors for watchdog and pathtools modules.

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 (jump to list of events)
  • 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)
  5. Sending a Json-RPC notification
  • 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
  • 31 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 userdata/addon_data/script.service.kodi.callbacks/lib/tasks folder
    • It is better to put user tasks here than in the addon's tasks folder since that folder may be rewritten during updates
  • 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 but has been submitted as of 27-02-2016.
The addon is now available through the official repo (isengard forward) as of 22-04-2016!!!
It has one dependency - the requests module. This should automatically be installed by Kodi.
If desired, it can also be downloaded manually copied to the Kodi Add-Ons folder, overwriting the previous version.
Or after download you can load it via the settings addon 'install from zip' action.
The most recent version of the script can be downloaded here: https://github.com/KenV99/service.kodi.callbacks/archive/master.zip

PLEASE NOTE: If you are updating from an installation from before 2-27-2016 (version 0.9.7.6 or earlier), you will be required to reset the settings to default and re-input them. I apologize, this could not be avoided.

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 four pages of settings - Tasks, Events, General and Update

Settings - Tasks

Kodi-callbacks-settings1-1.PNG

You can configure up to 10 tasks.

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

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)
  • A note on Unicode filenames and directories:
    1. Please note that using scripts or python files with names with unicode characters beyond the ASCII character set for the above two task types is NOT uniformly supported on all platforms.
    2. To ensure that your files work, avoid using filenames or placing the files in directories with names that are outside the ASCII character set.
  • For http:
    1. Put only the url with port here. Further specification will be done on the events page when invoking this task.
    2. Optionally a username and password can be provided for Basic Auth only.
    3. Choose which http request type is desired (most commonly GET or POST).
    4. For POST or PUT, choose what Content-Type you want in the header.
    5. Other CGI query type data (i.e ?var1=x&var2=y) will be done on the events page.
  • For builtins:
    1. See the wiki for a list of functions: List_of_built-in_functions
    2. Arguments can be passed via userags when configuring the event
  • For json notifications:
    1. You can configure the 'sender' string to be used during the notification broadcast
    2. Note that all available data is sent in the 'data' submessage', so userargs is not utilized for this task

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



Settings - Events

Kodi-callbacks-settings2-1.PNG

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

Click on 'Choose'. Your choice will appear on the following line after choosing. This was needed to make this work with other languages.

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

For some events, additional information is required:

  1. For JSON notification events, the sender, method and data are required. This uses the python xbmc.Monitor.OnNotification function. Note that this does not receive ALL notifications. This is a json notification receiver event. It is completely separate from the json-rpc-notify TASK which sends notifications.
  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. Requires XCODE is installed as well.
  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, for a space 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.
  • When the task that is being run is an http task using either POST or PUT, anything following double question-mark "??" will be treated as payload.
    1. The ?? will not appear as part of the transmitted url string.
    2. What you put following the ?? should depend on the Content-Type selected for the task on the Tasks settings page.

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. See below 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
onPlayBackPaused onDPMSActivated onWindowOpen
onPlayBackResumed onDMPSDeactivated onWindowClose
onPlayBackSeek onNotification onIdle
onPlayBackSeekChapter onScanStarted onResumeAfterIdle
onPlayBackSpeedChanged onScanFinished
onQueueNextItem onScreensaverActivated
onScreensaverDeactivated



Settings - General

Kodi-callbacks-settings3-1.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 userdata/addon_data/script.service.kodi.callbacks/lib/usertasks folder. This will read in whatever settings you need so that they appear on the settings pages.

You can force the addon to log all of it's settings to kodi.log. PLEASE do this if you are uploading a log to ask for help troubleshooting.

If you have the Kodi log uploader addon installed, then you will see a clickable link to send your log directly from this page.


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 tested to work on Windows, OSX, Linux Mint and Android. There may be an issue detecting a successful builtin test on Jarvis. This will be corrected soon. On Android, python imports cannot be correctly tested, but the method works and has been tested directly.


Settings - Update

Kodi-callbacks-settings4-1.PNG

Before any update via this page, the current installation is backed up to the addon_data folder for this addon under the sub-directory backup.

The last five backups are kept.

  1. FOR THE NONREPO BRANCH ONLY (this is the version that is not in the official Kodi repository and must be downloaded and installed manually - may be better if you want to participate in development):
    1. Downloading and installing from Github directly in the addon is not allowed in the official repository, this the need for a separate branch.
    2. These additional functions are useful to developers especially for multiplatform testing. If you want to develop your own task, consider downloading and installing the nonrepo branch.
    3. Developers will need to manually edit a couple of lines to point to their own clone on Github. Ask on the forum if you need help with this.
    4. The typical install from zip from Kodi will overwrite your directory including anything that you have added including git and development gui settings if they are in the addon directory.
    5. These routines will prevent this from happening during the development/testing cycle and are easier to use on keyboardless systems for testing.
    6. The first line shows the branch name for the current installation. This corresponds to the available branch names on GitHub. If you install directly via the addon settings page or copy over, this may be inaccurate.
    7. Repository branch name for downloads from GitHub. When the addon runs it retrieves this info directly from GitHub. This activity triggers a warning in the log because it utilizes urlib3 via the requests module. Don't worry about the warning.
    8. You can choose to have the addon download from GitHub when updates are available and install them. An update is triggered when the version number is bumped in addon.xml. Don't worry, not every commit will be downloaded.
    9. You can allow the install to take place silently.
    10. You can manually trigger a check on GitHub and then optionally install the most recent even if the version is the same.
  2. You can also update from a manually downloaded zip file. This renames the folder name, removing the branch name so that you don't need to do it manually.
  3. You can also reinstall from one of the automatic backups.
  • Note: These routines have some advantages over installing from the main addons page built into Kodi. They automatically rename the directory. They will leave any files that you have added into the directory. Only newer files will be copied over via a timestamping mechanism in most circumstances.
  • Note: I have occasionally encountered an error while downloading from GitHub. If you see an error notification, please just try again. This has always worked for me as long as I have an internet connection.

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 provide information via a settings page to configure it properly.

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.

You would put your own task code in an appropriately named .py file and place it in the following directory: userdata/addon_data/script.service.kodi.callbacks/lib/tasks

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.

Example scripts:

  • To have a script execute after Kodi exits on windows while passing pid as an argument:
@echo off
:loop
tasklist | find " %1 " >nul
if not errorlevel 1 (
    timeout /t 2 >nul
    goto :loop
)
REM Put the code you want to run here
  • To have a script execute after Kodi exits in other OS's while passing pid as an argument:
#!/usr/bin/env bash
while kill -0 $1 > /dev/null 2>&1
do
    sleep 0.2
done
# insert your code here
  • To have a script run as sudo while passing the full path to script as a parameter:
#!/usr/bin/env bash
bash "$*"

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.

If all else fails, try looking in the log to see if something specific is written there when whatever it is that you are trying to detect occurs and then use the onLogSimple or onLogRegex events to detect your event.

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 things broke after a new update, please try rebuilding your settings first:

  1. Note down your settings
  2. On the settings page click 'Default' and then click 'OK'
  3. Rebuid your settings
  4. Click OK
  5. Restart Kodi

If you believe that things are not working as expected after trying the above,

  1. From the 'General' Settings page:
    1. Turn on 'Show debugging info in normal log'
    2. Click OK
    3. Recreate your problem
    4. Go back to Settings and on the General page, click to write your settings into the log.
    5. Exit Kodi
  2. Find your log file: Wiki: Log File Location
  3. UPLOAD AN ENTIRE COPY OF 'kodi.log' TO: XBMCLogs or pastebin
  4. INCLUDE A LINK TO THE LOG IN YOUR POST ON THE FORUM

Please do not turn on Kodi's debug mode before uploading a log unless asked to do so. This typically just generates more noise in the log, making it harder to pinpoint the problem.

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.

If you are going to edit python for Kodi, PyCharm is the way to go!!! You can apply for a free license to open source projects.

Icon PyCharm.png