SensorScripts
From Openpavilion
Contents |
Sensor Scripts
Before digging into the scripting of sensors, you should read this article about the nature of Sensors.
Introduction example
A sensor is comparable to a sensor built into a machine: It gathers numerical values. Sensor scripts are written in [Python] language.
The simpliest sensor script would be:
self.response = 1
The script itself has two major aspects:
- create a numerical value
- return the value as self.response
If you want to test these examples for yourself, please open the Python IDLE editor, which came with the Python installation. Beside IDLE, there are [other IDE's] available.
IMAP example
Now we want to create a sensor, which collects the number of emails residing on an IMAP server.
import imaplib (1)
M = imaplib.IMAP4("mail.openpavilion.org") (2)
M.login("administrator", "xxxxx")
M.select() (3)
typ, data = M.search(None, 'ALL')
M.close() (4)
M.logout()
self.response = data[0][-1:] (5) <-- returns 0,1,2,3 ... (a number) to OpenPavilion
This script logs into an email account gathering the number of emails there. The sensor then returns the number of the last email.
This is an excellent example for the sensors you will create most of the time:
- import Python standard libraries as needed (here you import the imaplib library)
- log into the server, application, database or whatever
- get the data; most of the time the result is not a value you can handle in OpenPavilion, so you have to reformat it to get a number
- close the connection to server, database etc.
- return the result to OpenPavilion
If you look at the IMAP example and realize how simple it is to write (8 lines of code), you can imagine that it will be very easy to setup more observation sensors even for different databases, servers, email systems, application servers and much more. Sensor scripting is all about finding the right Python libraries, connect to the target and get the value you need.
