Table of Contents

Indigo Scripting Tutorial

Talking to the Indigo Server

The Indigo Plugin Host (IPH) provides a python scripting and plugin environment, which makes controlling the Indigo Server easy via the high-level python language (the official python web site has great python tutorials). Every plugin automatically runs inside its own Indigo Plugin Host process, but you can also start the IPH in an interactive mode to directly communicate with the Indigo Server. It is a great way to experiment with Indigo's python environment, which is available to both python scripts run by Indigo and the plugin architecture.

To launch the Terminal utility application (inside /Applications/Utilities/) in an Indigo shell mode choose the Plugins→Open Scripting Shell menu item.

– or –

If you already have a Terminal shell running, you can launch it directly. The file path to the IPH executable is a bit deep, so create an alias to it inside your .bashrc (or .bash_profile) file by copying/pasting this into the Terminal (you only need to do this once!):

echo "alias indigohost='/Library/Application\ Support/Perceptive\ Automation/Indigo\ 5/IndigoPluginHost.app/Contents/MacOS/IndigoPluginHost'" >> ~/.bashrc

Next, close the Terminal window and open a new one to load the shortcut alias to the IPH executable. To start the IPH in interactive mode we pass the -i flag to it inside the Terminal:

indigohost -i

As shown, the IPH will automatically connect to the IndigoServer running on the same Mac and will show the server's version information. Additionally, you'll notice that Indigo Server logs the connection of the interactive shell plugin.

Next, let's tell the Indigo Server to log a message to the Event Log window (again, via the Terminal application):

indigo.server.log("Hello world!")

Connecting Remotely over SSH

If you have SSH configured so you can remotely connect to your Mac running the Indigo Server, then you can use SSH to start the IPH interactively anywhere using the syntax:

ssh username@indigo_mac_ipaddr -t "/Library/Application\ Support/Perceptive\ Automation/Indigo\ 5/IndigoPluginHost.app/Contents/MacOS/IndigoPluginHost" -i

What Else Can it Do?

The IPH gives you full access to the Indigo Object Model (IOM) providing access to create/edit/delete/control Indigo objects, as well as several Indigo utility functions, INSTEON device commands, and X10 device commands. Access to all of this functionality is provided by the indigo module automatically loaded and included in any python scripts run by the IPH (including interactive IPH sessions like we are using here).

Executing Indigo Commands Directly

In addition to communicating interactively with Indigo via the shell, you can also send direct python commands to Indigo via the IPH. For example, to get the current brightness of the device “office lamplinc”:

indigohost -e 'return indigo.devices["office lamplinc"].brightness'

Or to toggle the device “office lamplinc” three times:

indigohost -e '
indigo.device.toggle("office lamplinc")
indigo.device.toggle("office lamplinc")
indigo.device.toggle("office lamplinc")
'

Note when your commands are executed the indigo module is already loaded and connected and you can execute standard python code (loops, conditionals, etc.).

Caveat: Each call creates a new IPH (indigohost) process which must establish a connection to the Indigo Server. Although this is relatively fast, calling it multiple times a second is not recommended.

Executing Indigo Python Files

The IPH can also be used to execute Indigo python (.py) files, like this:

indigohost -x /SomeFolder/indigo_script.py'

Caveat: Each call creates a new IPH (indigohost) process which must establish a connection to the Indigo Server. Although this is relatively fast, calling it multiple times a second is not recommended.

Shared Classes and Methods in Python Files (Python Attachments)

In Indigo, if you want to write AppleScript handlers that are shared by any script that Indigo executes, you can just put an AppleScript full of handlers in the /Library/Application Support/Perceptive Automation/Indigo 5/Scripts/Attachments folder. You can do the same thing with Python using a built-in mechanism that Mac OS X supports for Python. There is a folder in the Library folder at the top level of your boot disk that is very similar to the Attachments folder:

/Library/Python/2.5/site-packages

Any Python files in this directory that define methods and/or classes will be loaded by the Python interpreter whenever it's loaded (note that it's the Library directory at the top level of your boot disk, not the one in your user folder). So, you can create files of handlers you want to share between all Python scripts. Files here can also import the entire IOM - IF the script that's actually running is started by Indigo. Here's a simple shell that you can use that will safely import the IOM and will show a specific error when used from a Python script that's not started by Indigo:

#!/usr/bin/env python2.5
"""
indigoAttachments.py

In this file you can insert any methods and classes that you define.
They will be shared by all Python scripts - you can even import the
IOM (as shown below) but if you do then you'll only be able to import
this script in Python processes started by Indigo. If you don't need
the IOM then skip the import and it'll work in any Python script
no matter where it's run from.
"""

try:
    import indigo
except ImportError:
    print "Attachments can only be used from within Indigo"
    raise ImportError

def specialLog(text):
    indigo.server.log(text, type="indigoAttachments")

Then, when you want to use any of the classes/methods in the file, just import the file and go:

import indigoAttachments
indigoAttachments.specialLog("Here's a special sort of log message")

If you try to run this script in a normal python session, you'll see the print statement followed by the ImportError:

FatMac:testdir jay$ python2.5 testHandlerCall.py 
Attachments can only be used from within Indigo
Traceback (most recent call last):
  File "testCallingIndigo.py", line 3, in <module>
    import indigoAttachments
  File "/Users/jay/Library/Python/2.5/site-packages/indigoAttachments.py", line 14, in <module>
    raise ImportError
ImportError

Scripting Indigo Plugins

Indigo plugins are also scriptable. Because plugin-defined devices look almost identical to built-in devices, you can get (but not set) state information from them (see device examples a bit further down for a lot of examples). You can also get some of the other properties for a plugin. Most importantly you can execute plugin-defined actions, which is how you'd set their state values.

The first step is to get an instance of the plugin:

iTunesId = "com.perceptiveautomation.indigoplugin.itunes" # supplied by the plugin's documentation
iTunesPlugin = indigo.server.getPlugin(iTunesId)

This will always return to you a plugin object, defined with the following properties:

pluginDisplayName The name displayed to users in the clients
pluginId The ID of the plugin (same as was passed to the getPlugin() method above)
pluginSupportURL The URL supplied by the plugin that points to it's user documentation
pluginVersion The version number specified by the plugin

There are also a couple of methods defined by this object.

isEnabled()
This method will return True if the plugin is enabled (running), False otherwise
executeAction(actionId, deviceId, props)
This is the method that actually executes the action. actionId is the unique action id. deviceId is the id of the device that the action on which the action will perform (if it requires a device). props is a dictionary of properties that the action needs to process correctly. See the plugin's documentation for a description of what you need to pass in to execute actions.
restart(waitUntilDone=True)
This method will restart the plugin if it's already running. Pass the optional parameter waitUntilDone=False if you don't want to block while the plugin restarts (waitUntilDone defaults to True if it's no parameters are passed). If you're a plugin developer and you want to restart the plugin from within itself you should pass that parameter.

Plugin developers should test and document their plugin actions to make sure that the necessary information is available to scripters.

Examples

iTunes Toggle Play State

itunesId = "com.perceptiveautomation.indigoplugin.itunes"
itunesPlugin = indigo.server.getPlugin(itunesId)
if itunesPlugin.isEnabled():
	itunesPlugin.executeAction("playPause", deviceId=135305663)

iTunes Set Volume to 50

itunesId = "com.perceptiveautomation.indigoplugin.itunes"
itunesPlugin = indigo.server.getPlugin(itunesId)
if itunesPlugin.isEnabled():
	itunesPlugin.executeAction("setVolume", deviceId=135305663, props={'volume':50})

Pause iTunes and Speak NOAA Weather

itunesId = "com.perceptiveautomation.indigoplugin.itunes"
itunesPlugin = indigo.server.getPlugin(itunesId)
if itunesPlugin.isEnabled():
	myWeatherStation = indigo.devices[1798384204]
	outsideTemp = myWeatherStation.states['temperatureF']
	currentCondition = myWeatherStation.states['currentCondition']
	spokenString = "The current temperature is %s degrees. Current condition is %s." % (outsideTemp, currentCondition)
	itunesPlugin.executeAction("pauseAndSay", deviceId=135305663, props={'message':spokenString})

Check the various plugin documentation for the necessary information and more examples.

Example Code Snippets

Below are some example you can copy/paste directly into the Terminal application (running the IPH via the indigohost -i command explained above). Keep in mind these are only examples, so be sure and read over the full Indigo Object Model (IOM) Reference.

Note: For simplicity some of the samples below specify objects based on name (“office desk lamp”). However, the preferred lookup mechanism is to use the object's ID which can be retrieved by control-clicking on the object name in Indigo's Main Window. By using the ID you ensure the object will be found even if its name is changed.

Device Examples

Turn on the device "office desk lamp":

indigo.device.turnOn("office desk lamp")

Duplicate the device "office desk lamp":

indigo.device.duplicate("office desk lamp", duplicateName="office desk lamp2")

In 4 seconds turn on the device "office desk lamp" for 2 seconds:

indigo.device.turnOn("office desk lamp", duration=2, delay=4)

Turn off all devices:

indigo.device.allOff()

Count the number of device modules:

indigo.devices.len()

Count the number of dimmable device modules:

indigo.devices.len(filter="indigo.dimmer")

Count the number of devices defined by all of our plugin types:

indigo.devices.len(filter="self")

Count the number of irBlaster type devices defined by our plugin:

indigo.devices.len(filter="self.irBlaster")

Get the on state of a device if it has the onState property (uses Python's hasattr() introspection method):

lamp = indigo.devices["office desk lamp"]
if hasattr(lamp, 'onState'):
	isOn = lamp.onState

Get the class of a device (uses Python's %%__class__%% property):

lamp = indigo.devices["office desk lamp"]
if lamp.__class__ == indigo.DimmerDevice:
	theBrightness = lamp.brightness

Variable Examples

Create a new Indigo variable named fooMonster, change its value multiple times, and delete it:

newVar = indigo.variable.create("fooMonster", "default value")
indigo.variable.updateValue(newVar, "asleep")
indigo.variable.updateValue(newVar, "awake")
indigo.variable.delete(newVar)

Getting a variable object and using it's value:

myVar = indigo.variables[123]
if myVar.value == "true":
    indigo.server.log("The variable had a value of 'true'")

Duplicating a variable:

indigo.variable.duplicate("fooMonster", duplicateName="fooMonsterSister")

Date and Time Examples

Get the current server time:

indigo.server.getTime()

Calculate the sunset time in 1 week:

import datetime
one_week = indigo.server.getTime().date() + datetime.timedelta(days=7)
indigo.server.calculateSunset(one_week)

Action Group Examples

Execute Action Group 12345678:

indigo.actionGroup.execute(12345678)

Log Examples

Log to the Indigo Event Log window all of the attributes/properties of the device "office desk lamp":

lamp = indigo.devices["office desk lamp"]
indigo.server.log(lamp.name + ": \n" + str(lamp))
logList = indigo.server.getEventLogList(lineCount=5)
print(logList)

Folder Examples

Iterate over a list of all device folders

for folder in indigo.devices.folders:
	print "Folder id: %s name: %s, remoteDisplay: %s" % (folder.id,folder.name,folder.remoteDisplay)

Create a trigger folder named "My Triggers" and if it exists just return the existing one

try:
	myFolder = indigo.triggers.folder.create("My Triggers")
except ValueError, e:
	if e.message == "NameNotUniqueError":
		# a folder with that name already exists so just get it
		myFolder = indigo.triggers.folders["My Triggers"]
	else:
		# you'll probably want to do something else to make myFolder a valid folder
		myFolder = None

Make a folder visible in remote clients (IWS, Indigo Touch, etc.)

indigo.devices.folder.displayInRemoteUI(123, value=True)

Getting the folder a device is in

lamp = indigo.devices["office desk lamp"]
# An object that's not in a folder will have a folder id of 0, which isn't a valid folder
# so we need to make sure it's a valid folder ID first
if lamp.folderId != 0:
	lampsFolder = indigo.devices.folders[lamp.folderId]
else:
	lampsFolder = None

Miscellaneous Examples

Get a list of all serial ports, excluding any Bluetooth ports:

indigo.server.getSerialPorts(filter="indigo.ignoreBluetooth")

Sending emails

# Simple Example
indigo.server.sendEmailTo("emailaddress@company.com", subject="Subject Line Here", body="Some longish text for the body of the email")

# Putting a variable's data into the subject and body
theVar = indigo.variables[928734897]
theSubject = "The value of %s" % (theVar.name)
theBody = "The value of %s is now %s" % (theVar.name, theVar.value)
indigo.server.sendEmailTo("emailaddress@company.com", subject=theSubject, body=theBody)

# Putting device data into the subject and body
theDevice = indigo.devices[980532604]
theSubject = "Summary of %s" % (theDevice.name)
theBody = "%s is %s\n%s is %s" % ("onState", str(theDevice.onState), "lastChanged", str(theDevice.lastChanged))
indigo.server.sendEmailTo("emailaddress@company.com", subject=theSubject, body=theBody)

FIXME Add examples for:

  • refreshing objects
  • replacing objects
  • enabling/disabling objects
  • sprinkler control
  • etc.
indigo_5_documentation/plugin_scripting_tutorial.txt · Last modified: 2014/05/28 16:15 (external edit)
 

© Perceptive Automation, LLC. · Privacy