Add initial JSR223 documentation (#428)

Signed-off-by: Steve Bate <svc-github@stevebate.net> (github: steve-bate)
pull/444/head^2
Steve Bate 2017-07-14 08:07:51 -04:00 committed by Thomas Dietrich
parent b7d1d99928
commit 7ad0c7ce93
6 changed files with 406 additions and 1 deletions

View File

@ -9,7 +9,7 @@ github_username: openhab
markdown: kramdown
exclude: ["CNAME", "pom.xml", "README.md", "CONTRIBUTING.md", "process_addons.groovy", "update.sh", "Vagrantfile"]
# Additional gems for sitemap generation
gems:
plugins:
- jekyll-sitemap
collections:
actions:

View File

@ -43,6 +43,7 @@
<li><a href="{{docu}}/configuration/transform.html">Transformations</a></li>
<li><a href="{{docu}}/configuration/persistence.html">Persistence</a></li>
<li><a href="{{docu}}/configuration/rules-dsl.html">Rules</a></li>
<li><a href="{{docu}}/configuration/jsr223.html">JSR223 Scripting</a></li>
<li><a href="{{docu}}/configuration/services.html">Services</a></li>
<hr />
<li><a href="{{docu}}/configuration/packages.html">Initial Setup Packages</a></li>

View File

@ -24,6 +24,7 @@ In order to represent all of these, openHAB defines the following few base compo
* [Transformations](transform.html) - Helper functions to transform your data
* [Persistence](persistence.html) - Services to store data over time
* [Rules](rules-dsl.html) - Automation logic, the "smart" in your Smart Home!
* [JSR223 Scripting](jsr223.html) - Define rules and other runtime objects using [Javascript](http://openjdk.java.net/projects/nashorn/), [Jython](http://www.jython.org) or [Groovy](http://www.groovy-lang.org/).
The individual articles hold all details needed to understand the concepts behind these building bricks for your Smart Home.
For more details on the base concept behind openHAB, please visit the [Concepts Overview page]({{base}}/concepts/index.html).

View File

@ -0,0 +1,16 @@
---
layout: documentation
title: JSR223 Javascript Scripting
---
{% include base.html %}
# JSR223 Javascript (Nashorn)
No special configuration is needed for using JSR223 Javascript since the Nashorn Javascript interpreter is included with Java.
## Resources
- [Scripted Rule Support](https://github.com/eclipse/smarthome/wiki/Scripted-Rule-Support)
Early documentation on JSR223 usage in openHAB 2. Includes Javascript examples and IDE setup instructions.

View File

@ -0,0 +1,156 @@
---
layout: documentation
title: JSR223 Jython Scripting
---
{% include base.html %}
# JSR223 Jython Scripting
## Configuration
[Download](http://www.jython.org/downloads.html) the Jython 2.7.x installer package.
Install Jython on the local filesystem and make note of the installation directory location.
The Jython implementation will need to be added to openHAB's Java classpath.
How this is done depends on the specific installation technique and operating system.
### Linux Package Installers
Modify the `EXTRA_JAVA_OPTS` environment variable in `/etc/default/openhab2` to:
```bash
EXTRA_JAVA_OPTS=-Xbootclasspath/a:/home/pi/jython2.7.0/jython.jar \
-Dpython.home=/home/pi/jython2.7.0 \
-Dpython.path=/etc/openhab2/lib/python
```
This will add the Jython library to the Java classpath,
set the Jython home directory and specify the initial Python path for the Jython runtime.
Python modules and packages can be installed into the `python.path` locations and imported from scripts.
Note that library modules and packages are not automatically reloaded when they change.
### Mac and Windows or Manual Installation
Set the `EXTRA_JAVA_OPTS` environment variable to the value described in the Linux configuration.
Note that on Windows the environment variable value should be set as a single line
(without backslashes to combine the line fragments).
## Configuration Testing
In the `automation/jsr223` directory create an empty file called `test.py`.
Watch the openHAB log file carefully ([Karaf logging]({{base}}/administration/logging.html)
or viewing the `openhab.log` file directly).
You should see a log line with information similar to:
```text
... [INFO ] [s.i.GenericScriptEngineFactory:28 ] - Activated scripting support for ECMAScript
... [INFO ] [s.i.GenericScriptEngineFactory:28 ] - Activated scripting support for python
...
... [INFO ] [.a.m.s.r.i.l.ScriptFileWatcher:150 ] - Loading script 'test.py'
```
> NOTE: ECMAScript is Javascript
Look for any potentially related error messages.
To enable debug logging, use the [Karaf logging]({{base}}/administration/logging.html) commands to
enable debug logging for the automation functionality:
```text
log:set DEBUG org.eclipse.smarthome.automation
```
## Script Examples
Jython scripts provide access to almost all the functionality in an openHAB runtime environment.
As a simple example, the following script logs "Hello, World!" into the openhab.log file.
Note that `print` will usually not work since the output has no terminal to display the text.
One exception is when the openHAB server is running from the Eclipse IDE.
The openHAB server uses the [SLFJ](https://www.slf4j.org/) library for logging.
```python
from org.slf4j import LoggerFactory
LoggerFactory.getLogger("org.eclipse.smarthome.automation.examples").info("Hello world!")
```
Jython can [import Java classes](http://www.jython.org/jythonbook/en/1.0/ModulesPackages.html).
Depending on the openHAB logging configuration,
you may need to prefix logger names with `org.eclipse.smarthome.automation`
for them to show up in the log file (or you modify the logging configuration).
> NOTE: Be careful with using wildcards when importing Java packages (e.g., `import org.sl4j.*`).
> This will work in some cases, but it might not work in some situations.
> It's best to use explicit imports with Java packages.
> For more details, see the Jython documentation on
> [Java package scanning](http://www.jython.org/jythonbook/en/1.0/ModulesPackages.html#java-package-scanning).
The script then uses the [LoggerFactory](https://www.slf4j.org/apidocs/org/slf4j/Logger.html)
to obtain a named logger and then logs a message like:
```text
... [INFO ] [.smarthome.automation.examples:-2 ] - Hello world!
```
Notice that no rules were required for this simple script.
This can be a useful way to experiment with simple Jython code before defining rules or other more advanced functionality.
If you want to respond to openHAB events you can create rules in the scripts.
The following script requires two string items, `TestString1` and `TestString2`.
The rule created in the script is triggered by an update to `TestString1` and,
when triggered, the rule updates `TestString2`.
```python
scriptExtension.importPreset("RuleSimple")
scriptExtension.importPreset("RuleSupport")
class MyRule(SimpleRule):
def __init__(self):
self.triggers = [
Trigger("MyTrigger", "core.ItemStateUpdateTrigger",
Configuration({ "itemName": "TestString1"}))
]
def execute(self, module, input):
events.postUpdate("TestString2", "some data")
automationManager.addRule(MyRule())
```
When a script is loaded, some names are already defined in the script *scope* (the local Jython namespace).
To define rules, you must include some additional [script *extensions*](jsr223.html#presets)
(implemented as "presets") that add more names to the script scope for specific purposes.
In this case, the `RuleSimple` extension is used to import the `SimpleRule` base class.
The `RuleSupport` extensions provides the `automationManager` that allows you to register rule instances with openHAB.
The Jython rule class uses the `SimpleRule` subclass to simplify some aspects of the openHAB interface for use with JSR223.
n the constructor, the triggers atribute is set to a list of [triggers](jsr223.html#trigger_types).
In this example, the trigger is a state update trigger.
The trigger name identifies the trigger and the configuration direction provides trigger-specific options.
For the item update trigger, the configuration provides the item name of the monitored item.
The `execute` method is invoked when the rule is triggered.
The `module` and `input` arguments can be used in advanced rules.
The information provided varies by the trigger type.
### Resources
- [Scripted Rule Support](https://github.com/eclipse/smarthome/wiki/Scripted-Rule-Support)
Early documentation on JSR223 usage in openHAB 2. Includes IDE setup instructions.
- [openhab2-jython](https://github.com/steve-bate/openhab2-jython) (github)
Provides information and examples related to advanced, exploratory openHAB JSR223 Jython usage.
- Wrappers to simplify `Trigger` usage in rules.
- Python decorators to define simple time-triggered and item-triggered functions
- Python logging bridge to openHAB logger
- Custom Trigger Implementations: `StartupTrigger`, `OsgiEventTrigger`, ...
- OSGI console command implemented in Jython
- OH2 Module Implementations in Jython (things, item providers, ...)
- Jython-based ScriptExtension (preset) provider support.
- Example of using Pykka Actor library.
- Unit-testing support

231
configuration/jsr223.md Normal file
View File

@ -0,0 +1,231 @@
---
layout: documentation
title: JSR223 Scripting
---
{% include base.html %}
# JSR223 Scripting
> Note: This feature is for users who have or are willing to learn some programming skills
> and are comfortable working with the command line prompt of the operating system hosting openHAB.
## Overview
[JSR223](https://docs.oracle.com/javase/6/docs/technotes/guides/scripting/) ([spec](https://jcp.org/aboutJava/communityprocess/pr/jsr223/index.html))
is a standard scripting API for Java Virtual Machine (JVM)
[languages](https://en.wikipedia.org/wiki/List_of_JVM_languages).
The JVM languages provide varying levels of support for the JSR223 API and interoperability with the Java runtime.
Currently the following languages are known to work well for openHAB scripting:
[**Oracle Nashorn**](http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html) (Javascript bundled with Java),
[**Jython**](http://www.jython.org/) (Python on the JVM) and
[**Apache Groovy**](http://www.groovy-lang.org/) (JVM scripting language).
Although JSR223 scripts can be used as a general-purpose extension language for openHAB,
the most common usage will be for defining openHAB rules.
### Language-Specific Documentation
- [Javascript](jsr223-js.html)
- [Jython](jsr223-jython.html)
- Groovy (TODO)
### Script Locations
Scripts should be placed in the 'USERDATA/automation/jsr223' directory. For example,
in Linux installations created with a package installer,
the directory would be `/etc/openhab2/automation/jsr223`.
At system start time the scripts will be loaded in an order based on their name
and then top-down through the directory hierarchy.
Note that while scripts may be placed in subdirectories of `jsr223`,
they should not have the same names as scripts in other directories (this may be changed in the future).
For example, with the following directory structure...
```text
automation/jsr223
01/
script1.py
scriptx.py
00script.py
script2.py
```
the load order will be: `00script.py`, `01/script1.py`, `script2.py`, `01/scriptx.py`.
<a name="trigger_types"></a>
### Trigger Types (all JSR223 languages)
The following trigger types are defined by openHAB (custom triggers can also be defined)
and take the specified configuration parameters.
| Trigger: `core.ItemCommandTrigger` |
|-----------------------------|
| `itemName` | The item name | TEXT |
| `command` | The command | TEXT |
| Trigger: `core.ItemStateUpdateTrigger` |
|-----------------------------|
| `itemName` | The item name | TEXT |
| `state` | The state | TEXT |
| Trigger: `core.ItemStateChangeTrigger` |
|-----------------------------|
| `itemName` | The item name | TEXT |
| `previousState` | The previous state | TEXT |
| `state` | The state | TEXT |
| Trigger: `timer.GenericCronTrigger` |
|-----------------------------|
| `cronExpression` | The cron expression | TEXT |
| Trigger: `timer.TimeOfDayTrigger` |
|-----------------------------|
| `time` | The time in "hh:mm" format | TEXT |
| Trigger: `core.GenericEventTrigger` |
|-----------------------------|
| `eventTopic` | default: "smarthome/*" (for channel events: "smarthome/channels/*/triggered") | TEXT |
| `eventSource` | item name, channel UID | TEXT |
| `eventTypes` | ItemCommandEvent, ItemStateEvent | TEXT |
### Additional Information
- [Scripted Rule Support](https://github.com/eclipse/smarthome/wiki/Scripted-Rule-Support) -
Early documentation on JSR223 usage in openHAB 2. Includes IDE setup instructions.
<a name="presets"></a>
### Predefined Script Variables (all JSR223 languages)
To faciliate JSR223 scripting, several openHAB-related variables are automatically predefined. These presets include:
- [Default](#default_presets)
- [`RuleSimple`](#rulesimple_presets)
- [`RuleSupport`](#rulesupport_presets)
- [`RuleFactories`](#rulefactories_presets)
<a name="default_presets"></a>
#### Default Variables (no preset loading required)
| Variable | Description |
|---------|-------------|
| `State` | `org.eclipse.smarthome.core.types.State` |
| `Command` | `org.eclipse.smarthome.core.types.State` |
| `DateTime` | `org.joda.time.DateTime` (if Jodatime is available) |
| `LocalTime` | `org.joda.time.LocalTime` (if Jodatime is available) |
| `StringUtils` | `org.apache.commons.lang.StringUtils` |
| `URLEncoder` | `java.net.URLEncoder` |
| `FileUtils` | `org.apache.commons.io.FileUtils` |
| `FilenameUtils` | `org.apache.commons.io.FilenameUtils` |
| `File` | `java.io.File` |
| `IncreaseDecreaseType` | `org.eclipse.smarthome.core.library.types.IncreaseDecreaseType` |
| `DECREASE` | `IncreaseDecreaseType` enum item |
| `INCREASE` | `IncreaseDecreaseType` enum item |
| `OnOffType` | `org.eclipse.smarthome.core.library.types.OnOffType` |
| `ON` | `OnOffType` enum item |
| `OFF` | `OnOffType` enum item |
| `OpenClosedType` | `org.eclipse.smarthome.core.library.types.OpenClosedType` |
| `OPEN` | `OpenClosedType` enum item |
| `CLOSED` | `OpenClosedType` enum item |
| `StopMoveType` | `org.eclipse.smarthome.core.library.types.StopMoveType` |
| `STOP` | `StopMoveType` enum item |
| `MOVE` | `StopMoveType` enum item |
| `UpDownType` | `org.eclipse.smarthome.core.library.types.UpDownType` |
| `UP` | `UpDownType` enum item |
| `DOWN` | `UpDownType` enum item |
| `DecimalType` | `org.eclipse.smarthome.core.library.types.DecimalType` |
| `HSBType` | `org.eclipse.smarthome.core.library.types.HSBType` |
| `PercentType` | `org.eclipse.smarthome.core.library.types.PercentType` |
| `PointType` | `org.eclipse.smarthome.core.library.types.PointType` |
| `StringType` | `org.eclipse.smarthome.core.library.types.StringType` |
| `items` | Instance of `java.util.Map&lt;String, State&gt;` |
| `itemRegistry` | Instance of `org.eclipse.smarthome.core.items.ItemRegistry` |
| `ir` | Alias for `itemRegistry` |
| `things` | Instance of `org.eclipse.smarthome.core.thing.ThingRegistry` |
| `events` | (internal) Used to send events, post commands, etc. [Details](#event_operations) below] |
| `rules` | Instance of `org.eclipse.smarthome.automation.RuleRegistry` |
| `scriptExtension` | (internal) For loading script presets. |
| `se` | Alias for `scriptExtension` |
<a name="#event_operations"></a>
##### `events` operations
- `postUpdate(String, String)`
- `postUpdate(Item, Number)`
- `postUpdate(Item, String)`
- `postUpdate(Item, State)`
- `sendCommand(String, String)`
- `sendCommand(Item, Number)`
- `sendCommand(Item, String)`
- `sendCommand(Item, Command)`
- `storeStates(Item...)`
- `restoreStates(Map<Item, State>)`
<a name="rulesimple_presets"></a>
#### RuleSimple Extension/Preset
These variables are loaded using:
```python
scriptExtension.importPreset("RuleSimple")
```
The primary usage of this preset is for defining rule (`SimpleRule`) subclasses.
See language-specific documentation for examples.
| Variable | Description |
|----------|------|-------|
| SimpleRule | Base class for Jython Rules |
| SimpleActionHandler | `org.eclipse.smarthome.automation.module.script.rulesupport.shared.simple.SimpleActionHandler` |
| SimpleConditionHandler | `org.eclipse.smarthome.automation.module.script.rulesupport.shared.simple.SimpleConditionHandler` |
| SimpleTriggerHandler | `org.eclipse.smarthome.automation.module.script.rulesupport.shared.simple.SimpleTriggerHandler` |
| TriggerType | `org.eclipse.smarthome.automation.type.TriggerType` |
| ConfigDescriptionParameter | `org.eclipse.smarthome.config.core.ConfigDescriptionParameter` |
| ModuleType | `org.eclipse.smarthome.automation.type.ModuleType` |
| ActionType | `org.eclipse.smarthome.automation.type.ActionType` |
| Visibility | `org.eclipse.smarthome.automation.Visibility` enum |
<a name="rulesupport_presets"></a>
#### RuleSupport Extension/Preset
These variables are loaded using:
```python
scriptExtension.importPreset("RuleSupport")
```
| Variable | Description |
|----------|-------------|
| automationManager | Instance for managing rules and other openHAB module instances. (e.g., `addRule`) |
| Configuration | `org.eclipse.smarthome.config.core.Configuration` |
| Action | `org.eclipse.smarthome.config.core.Action` |
| Condition | `org.eclipse.smarthome.config.core.Condition` |
| Trigger | `org.eclipse.smarthome.config.core.Trigger` |
| Rule | `org.eclipse.smarthome.config.core.Action.Rule` (use `SimpleRule` for defining rules) |
<a name="rulefactories_presets"></a>
#### RuleFactories Extension
> NOTE: Advanced usage
```python
scriptExtension.importPreset("RuleFactories")
```
| Variable | Description |
|----------|-------------|
| `ActionHandlerFactory` | `org.eclipse.smarthome.automation.module.script.rulesupport.shared.factories.ActionHandlerFactory` |
| `ConditionHandlerFactory` | `org.eclipse.smarthome.automation.module.script.rulesupport.shared.factories.ConditionHandlerFactory` |
| `TriggerHandlerFactory` | `org.eclipse.smarthome.automation.module.script.rulesupport.shared.factories.TriggerHandlerFactory` |
| `TriggerType` | `org.eclipse.smarthome.automation.type.TriggerType` |
| `ConfigDescriptionParameter` | `org.eclipse.smarthome.config.core.ConfigDescriptionParameter` |
| `ModuleType` | `org.eclipse.smarthome.automation.type.ModuleType` |
| `ActionType` | `org.eclipse.smarthome.automation.type.ActionType` |
| `Visibility` | `org.eclipse.smarthome.automation.Visibility` enum |