PHP Method Reference
Overview
In addition to RPC, Homegear can be controlled through it's built-in PHP script engine. Through this engine, scripts are executed much faster as there is no TCP socket connection to set up. Depending on the system that can safe up to a few hundred milliseconds. The PHP scripts can be executed the following ways:
- Webserver: By placing the files in the webserver root directory (/var/www/homegear/www/rpc by default, customizable in "/etc/homegear/rpcservers.conf"). The script can be executed by opening one of the RPC IP addresses in a web browser (by default HOMEGEAR_IP:2001, HOMEGEAR_IP:2002 [SSL, no auth], HOMEGEAR_IP:2003 [SSL, auth]).
-
CLI: By placing the files in the script directory (/var/www/homegear/scripts by default) and executing:
runscript MyScript.php FirstParam SecondParam
or
rs MyScript.php FirstParam SecondParam
-
Terminal or shell script: By also placing the files in the script directory (/var/www/homegear/scripts by default) and executing:
homegear -e runscript MyScript.php FirstParam SecondParam
or
homegear -e rs MyScript.php FirstParam SecondParam
-
Inline script on CLI, terminal or shell: By executing ($hg is already defined and you don't need to prepend the namespace):
homegear -e runcommand "PHP"
or
homegear -e rc "PHP"
For example with double quotes (weak quoting, you need to escape double quotes, "$" and "\"):
homegear -e rc "\$hg->setValue(12, 2, \"STATE\", true);"
or with single qotes (strong quoting, you only need to escape single quotes):
homegear -e rc '$hg->setValue(12, 2, "STATE", true); print '\''Hello World!'\'';'
or in CLI (no need to escape, quotes are optional):
rc $hg->setValue(12, 2, "STATE", true);
if the command starts with "$" you can even omit the "rc":
$hg->setValue(12, 2, "STATE", true);
-
RPC: By calling the RPC method "runScript":
curl -X POST -d '{
"jsonrpc": "2.0",
"method": "runScript",
"id": 123,
"params": ["Test.php", "param1 param2"]
}' http://HOMEGEAR_IP:2001 --header "Content-Type: application/json"
Starting with Homegear 0.6 PHP 7 is used as script engine. All RPC methods now are accessible through the "Homegear" class in the namespace "Homegear". Either statically:
<?php
Homegear\Homegear::setValue(12, 1, "STATE", true);
?>
or non-statically:
<?php
$hg = new Homegear\Homegear();
$hg->setValue(12, 1, "STATE", true);
?>
In addition to the class Homegear, the following classes are available:
Class |
Description |
HomegearGpio |
Class with functions to get and set GPIO states or wait for GPIO state changes. |
HomegearSerial |
Class with functions for reading and writing to serial devices (UART, RS232, ...). |
HomegearI2c |
Class with functions for communicating with I²C devices. |
HomegearException |
This class is thrown on errors. Inherited from "Exception". |
General
Signatures
void configureGateway(string $host, int $port, $caCert, $gatewayCert, $gatewayKey, $password)
Description
This method remotely sets the certificates on an unconfigured Homegear Gateway. To find gateways and to check if a gateway is configured, you can use Homegear::ssdpSearch("urn:schemas-upnp-org:device:basic:1", 5000). The response contains the field HG-Gateway-Configured which is set to 0 if the gateway is unconfigured. The certificates can be generated using Homegear Management.
Parameters
Name | Type | Description | Example |
---|
host | string | The host name or IP address of the gateway to connect to. | 192.168.178.104 |
---|
port | int | The port number the gateway service listens on. The default value is 2017. | 2017 |
---|
caCert | string | The Base64 encoded CA certificate. | |
---|
gatewayCert | string | The Base64 encoded gateway certificate. | |
---|
gatewayKey | string | The Base64 encoded gateway private key. | |
---|
password | string | The password as specifed in gateway.conf of or printed on the gateway. | aJn10ymAkloiq28nKlOlf4QjsN |
---|
Return Value
Returns void on success.
Exceptions
Exception | Description |
---|
HomegearException | Thrown on any errors. |
---|
Homegear::download
Signatures
bool download(string $hostname, int $port, string $path, string $filename, string $caFile, bool $verifyCertificate)
Description
This method downloads a file from a web server. It was implemented so you can download files (SSL encrypted) on embedded systems when OpenSSL certificate verification is not working. You should not use it to download large files because the download is fully saved to the memory before it is written to the disk.
Parameters
Name | Type | Description | Example |
---|
hostname | string | The hostname of the web server you want to get the source from | www.example.com |
---|
port | int | The port number the web server listens on | 443 |
---|
path | string | The path of the file to be returned | /path/to/file.dat |
---|
filename | string | The filename to which you want to save the file | /local/path/to/file.dat |
---|
caFile | string | The path to the certificate file you want to use to verify the web server certificate | /path/to/my/ca-certificates.pem |
---|
verifyCertificate | bool | Enables certificate verification; disable it only for testing purposes. | true |
---|
Return Value
Returns "true" on success and "false" on errors
Homegear::getHttpContents
Signatures
string getHttpContents(string $hostname, int $port, string $path, string $caFile, bool $verifyCertificate)
Description
This method returns the source of a web page as a string. It was implemented to add the possibility of accessing web pages in an SSL-encrypted manner on embedded systems when OpenSSL certificate verification is not working.
Parameters
Name | Type | Description | Example |
---|
hostname | string | The hostname of the web server that you use to get the source | www.example.com |
---|
port | int | The port number the web server listens on | 443 |
---|
path | string | The path of the file to be returned | /path/to/file.html |
---|
caFile | string | The path to the certificate file that is used to check the web server certificate | /path/to/my/ca-certificates.pem |
---|
verifyCertificate | bool | It enables certificate verification. Disable this only for testing purposes. | true |
---|
Return Value
It returns the source of the specified web page as a string and "false" if there are errors.
Homegear::getScriptId
Signatures
string getScriptId()
Description
Homegear assigns a unique ID to each script. This ID is used to identify the script in different threads. Additionally, a password token is generated, which means that any given script cannot accidently register as a different script. getScriptId() returns the ID and the token for the current script. The string that is returned can then be used to register new threads using "registerThread()". getScriptId() returns valid data only if this method is called in the main thread or after "registerThread()" has been called.
Parameters
This method has no parameters.
Return Value
Returns the script ID as string
Example Output
Homegear::getScriptId()
4241
Homegear::listRpcClients
Signatures
array listRpcClients()
Description
This method returns information about all registered RPC event servers (all servers that have called init()).
Parameters
This method has no parameters.
Return Value
It returns an array that contains one entry for each registered server. Each of these entries is an associative array containing the client information.
Exceptions
Exception | Description |
---|
HomegearException | |
---|
Example Output
var_dump($hg->listRpcClients())
array(1) {
[0]=>
array(13) {
["BINARY_RPC"]=>
bool(true)
["CLIENT_ID"]=>
int(0)
["INIT_BINARY_MODE"]=>
bool(true)
["INIT_INTERFACE_ID"]=>
string(30) "HomegearLib.192.168.0.137:9877"
["INIT_JSON_MODE"]=>
bool(false)
["INIT_KEEP_ALIVE"]=>
bool(true)
["INIT_NEW_FORMAT"]=>
bool(true)
["INIT_SUBSCRIBE_PEERS"]=>
bool(false)
["INIT_URL"]=>
string(27) "binary://192.168.0.137:9877"
["IP_ADDRESS"]=>
string(13) "192.168.0.137"
["JSON_RPC"]=>
bool(false)
["WEBSOCKET"]=>
bool(false)
["XML_RPC"]=>
bool(false)
}
}
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->listRpcClients());'
Homegear::log
Signatures
bool log(int $logLevel, string $message)
Description
This method writes a message to the script engine log and (if there are errors) to the error log file (/var/log/homegear/homegear-scriptengine.log and /var/log/homegear/homegear-scriptengine.err by default). To write to the main log file (homegear.log and homegear.err), use the RPC method writeLog().
Parameters
Name | Type | Description | Example |
---|
logLevel | int | This is the log level of the message. If Homegear's log level value is lower than this value, no message is logged. Valid values are:- 1: Critical
- 2: Error
- 3: Warning
- 4: Info
- 5: Debug
| 4 |
---|
message | string | This is the message that will be written to the log file. The date is prepended automatically. | My message |
---|
Return Value
Returns "true" on success
Errors
Code | Description |
---|
false | The message was empty. |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->log(3, "Hello Homegear!"));'
Homegear::mqttPublish
Signatures
void mqttPublish(string $topic, string $payload)
Description
This method publishes to a MQTT topic. For this to work, make sure, MQTT is enabled in "mqtt.conf".
Parameters
Name | Type | Description | Example |
---|
topic | string | The topic to publish to. The topic is prefixed with Homegear's root topic ("homegear") and the MQTT ID defined in "mqtt.conf" (e. g. "homegear/1234-5678-9abc/"). | MyTopic |
---|
payload | string | The payload to publish. Empty payloads are not allowed. | {"value": 5} |
---|
Exceptions
Exception | Description |
---|
HomegearException | Thrown if the topic or payload are empty. |
---|
Homegear::peerExists
Signatures
bool peerExists(int peerId)
Description
This method checks if a peer is known to Homegear.
Parameters
Name | Type | Description | Example |
---|
peerId | int | The peer ID to be checked | 43 |
---|
Return Value
"true" if the peer exists, "false" if not
Exceptions
Exception | Description |
---|
HomegearException | Occurs if there are parameter errors |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->peerExists(12));'
Homegear::pollEvent
Signatures
array pollEvent([int $timeout = -1])
Description
This method blocks until an event from Homegear is received. General events and events that concern all devices are always returned. Device value and configuration changes are returned only if the script has called subscribePeer() for the device. See the RPC reference for "event", "newDevices", "deleteDevices", and "updateDevice" for more information about the returned values. If you are calling pollEvent() from a thread that is not the main thread, you need to call registerThread() first. When Homegear shuts down, pollEvent() returns
array(
"TYPE" => "event",
"PEERID" => 0,
"CHANNEL" => -1,
"VARIABLE" => "DISPOSING",
"VALUE" => true
)
.
Parameters
Name | Type | Description | Example |
---|
timeout | int | The maximum amount of time the system waits for an event (in milliseconds) | 5000 |
---|
Return Value
It returns an associative array with information about the event:
Key | Value |
---|
TYPE | The event method called ("event", "deleteDevices", "newDevices" or "updateDevice"). |
---|
PEERID | The ID of the peer raising the event. Set for "event" and "updateDevice". |
---|
CHANNEL | The channel the event is raised for. Set for "event" and "updateDevice". |
---|
VARIABLE | The updated variable. Set for "event". |
---|
VALUE | The new value of the variable ("event"), an array of the type DeviceDescription ("newDevices"), or an array with information about the deleted devices ("deleteDevices").. |
---|
HINT | Set for "updateDevice". 0: Device or channel configuration changed; 1: Device links changed; 2: Teams changed. |
---|
Errors
Code | Description |
---|
false | Returned if errors occur |
---|
Example
<?php
/**
* Class to share data between the main script and the event thread.
*/
class SharedData extends Threaded
{
public function __construct($scriptId)
{
$this->scriptId = $scriptId;
$this->resetData();
}
public function resetData()
{
$this->peerId = 0;
$this->variable = '';
$this->value = 0;
}
public function setData($peerId, $variable, $value)
{
$this->peerId = $peerId;
$this->variable = $variable;
$this->value = $value;
}
public function getPeerId()
{
return $this->peerId;
}
public function getVariable()
{
return $this->variable;
}
public function getValue()
{
return $this->value;
}
public function run() {}
}
/**
* Class to process events received from Homegear
*/
class EventThread extends Thread
{
private $sharedData;
public function __construct($sharedData)
{
$this->sharedData = $sharedData;
}
public function run()
{
$hg = new \Homegear\Homegear();
// Make the new thread known to Homegear. Without this, pollEvent() is not working.
if($hg->registerThread($this->sharedData->scriptId) === false)
{
$hg->log(2, "Could not register thread.");
return;
}
// Get all devices
$devices = $hg->listDevices(false, array("ID"));
foreach($devices as $device)
{
// Subscribe to device to receive events.
$hg->subscribePeer($device["ID"]);
}
// Run the thread until Homegear shuts down.
while(!$hg->shuttingDown())
{
// Wait for event.
$result = $hg->pollEvent();
if($result !== false && $result["TYPE"] == "event")
{
// Pass result to main thread
$this->sharedData->setData($result["PEERID"], $result["VARIABLE"], $result["VALUE"]);
// Wake up main thread
$this->synchronized(function($thread){ $thread->notify(); }, $this);
}
}
}
}
$hg = new \Homegear\Homegear();
// Get script id and password token.
$scriptId = $hg->getScriptId();
// Create new object for sharing data between main and event thread.
$sharedData = new SharedData($scriptId);
// Create and start new event thread.
$thread = new EventThread($sharedData);
$thread->start();
// Run main thread until Homegear shuts down.
while(!$hg->shuttingDown())
{
// Wait to be notified by event thread with a timeout of 5 seconds.
$thread->synchronized(function($thread){ $thread->wait(5000000); }, $thread);
// Check if new data is available was set.
if($sharedData->getVariable())
{
// Print variable name and value of last event to log.
$hg->log(4, "Got event: Peer: ".$sharedData->getPeerId().", variable: ".$sharedData->getVariable().", value: ".$sharedData->getValue());
// Reset data.
$sharedData->resetData();
}
}
// Wait for event thread to finish.
$thread->join();
?>
Homegear::raiseDeleteDevice
Signatures
void raiseDeleteDevice(array $serialNumbers)
Description
This method sends deleteDevices() to all RPC event servers that are registered with Homegear. This is done to force the deletion of a device.
Parameters
Name | Type | Description | Example |
---|
serialNumbers | array | List of serial numbers to be deleted | array("JEQ1827519") |
---|
Homegear::registerThread
Signatures
bool registerThread(string $scriptId)
Description
This method makes a new thread known to Homegear. It is required so that the system can receive events.
Parameters
Name | Type | Description | Example |
---|
scriptId | string | This is the script ID and token as returned by "getScriptId()". Note that "getScriptId()" can be called only in the main thread or after registerThread() has been called. | 3,MTIzNDU2Nzg5MDEyMzQ1Ng== |
---|
Return Value
It returns true on success and false if no matching thread could be found.
Example Output
registerThread("3,MTIzNDU2Nzg5MDEyMzQ1Ng==")
true
Homegear::setScriptLogLevel
Signatures
void setScriptLogLevel(int $logLevel)
Description
This method sets the log level for the current script overwriting the global settings. It must be called from the main thread to work for all script threads. If called from a child thread it only sets the log level for this thread.
Parameters
Name | Type | Description | Example |
---|
logLevel | int | The new log level to set. If the log level value of the message to print is higher than this value, no message is logged. You can use values between 0 and 10. The log level values used by Homegear are:- 1: Critical
- 2: Error
- 3: Warning
- 4: Info
- 5: Debug
| 4 |
---|
Return Value
Returns "true" on success.
Errors
Code | Description |
---|
false | The value for "logLevel" is invalid. |
---|
Homegear::shuttingDown
Signatures
bool shuttingDown()
Description
This method checks whether Homegear is shutting down. If it returns "true", the script should exit.
Parameters
This method has no parameters.
Return Value
It returns "true" if Homegear is shutting down and "false" otherwise.
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->shuttingDown());'
Signatures
bool ssdpSearch(string $stHeader, int $timeout)
Description
This method searches for SSDP devices on the network. It sends a M-SEARCH packet and waits for devices to respond. The header field ST of the response must match $stHeader.
Parameters
Name | Type | Description | Example |
---|
stHeader | string | The value of the header field ST (Search Target) the response must contain. When ssdp:all is used, all responses will be returned. | urn:schemas-upnp-org:device:ZonePlayer:1 |
---|
timeout | int | The time in milliseconds within the device needs to respond. This value is placed in the header field MX of the M-SEARCH packet. | 5000 |
---|
Return Value
Returns an array containing the parsed responses including the processed description XML if provided.
Errors
Code | Description |
---|
false | Returned on internal errors. |
---|
Example Output
ssdpSearch("ssdp:all", 5000)
(Array length=1)
{
(Struct length=5)
{
[additionalFields]
{
(Struct length=5)
{
[cache-control]
{
(String) max-age=1800
}
[location]
{
(String) http://192.168.0.107:49000/fboxdesc.xml
}
[server]
{
(String) Fonbox UPnP/1.0 AVM FRITZ!Box Fon WLAN 7390 84.06.83
}
[st]
{
(String) upnp:rootdevice
}
[usn]
{
(String) uuid:123402409-bccb-40e7-8e6c-24651156553F::upnp:rootdevice
}
}
}
[additionalInfo]
{
(Struct length=12)
{
[UDN]
{
(String) uuid:123402409-bccb-40e7-8e6c-24651156553F
}
[deviceType]
{
(String) urn:schemas-upnp-org:device:fritzbox:1
}
[friendlyName]
{
(String) Fonbox
}
[iconList]
{
(Struct length=1)
{
[icon]
{
(Struct length=5)
{
[depth]
{
(String) 8
}
[height]
{
(String) 119
}
[mimetype]
{
(String) image/gif
}
[url]
{
(String) /ligd.gif
}
[width]
{
(String) 118
}
}
}
}
}
[manufacturer]
{
(String) AVM Berlin
}
[manufacturerURL]
{
(String) http://www.avm.de
}
[modelDescription]
{
(String) FRITZ!Box Fon WLAN 7390
}
[modelName]
{
(String) FRITZ!Box Fon WLAN 7390
}
[modelNumber]
{
(String) avm
}
[modelURL]
{
(String) http://www.avm.de
}
[presentationURL]
{
(String) http://192.168.0.107
}
[serviceList]
{
(Struct length=1)
{
[service]
{
(Struct length=5)
{
[SCPDURL]
{
(String) /fboxSCPD.xml
}
[controlURL]
{
(String) /upnp/control/fritzbox
}
[eventSubURL]
{
(String) /upnp/control/fritzbox
}
[serviceId]
{
(String) urn:any-com:serviceId:fritzbox
}
[serviceType]
{
(String) urn:schemas-any-com:service:fritzbox:1
}
}
}
}
}
}
}
[ip]
{
(String) 192.168.0.107
}
[location]
{
(String) http://192.168.0.107:49000/fboxdesc.xml
}
[port]
{
(Integer64) 49000
}
}
}
Homegear::subscribePeer
Signatures
(1) void subscribePeer(int $peerId)
(2) void subscribePeer(int $peerId, int $channel, string $variableName)
Description
This method enables the reception of events for a device. You need to call subscribePeer() for pollEvent() to return events for a device. If you are calling subscribePeer() from a thread that is not the main thread, you need to call registerThread() first.
(1) subscribes to all events of a peer, (2) subscribes to the events of a single variable. (2) can be called to subscribe to multiple variables.
Parameters
Name | Type | Description | Example |
---|
peerId | int | The ID of the peer to get events for | 32 |
---|
channel | int | The channel to get events for. If $channel and $variableName are ommitted, all events for that peer are received. | 2 |
---|
variableName | string | The variable to get events for | 2 |
---|
Exceptions
Exception | Description |
---|
HomegearException | This is thrown only under the following circumstances: it is not in main thread, and the script ID that was registered with registerThread() is invalid or registerThread() was not called. |
---|
Homegear::unsubscribePeer
Signatures
(1) void unsubscribePeer(int $peerId)
(2) void unsubscribePeer(int $peerId, int $channel, string $variableName)
Description
This method disables the reception of events for a device that was previously enabled via the call of subscribePeer(). If you call unsubscribePeer() from a thread that is not the main thread, you need to call registerThread() first.
(1) unsubscribes from all events of that peer, (2) unsubscribes from the event of a single variable. (2) can only be used when the variable to unsubscribe from was explicetly subscribed.
Parameters
Name | Type | Description | Example |
---|
peerId | int | The ID of the peer to be unsubscribed | 32 |
---|
channel | int | The channel to get events for. If $channel and $variableName are ommitted, all events for that peer are unsubscribed. | 2 |
---|
variableName | string | The variable to get events for | 2 |
---|
Exceptions
Exception | Description |
---|
HomegearException | This is thrown only if it is not in main thread and if the script ID registered with registerThread() is invalid or registerThread() was not called. |
---|
lifetick
Signatures
bool lifetick()
Description
This method checks all essential Homegear components. The components are:
All RPC servers
Checks for hanging RPC method calls.
The RPC client
Checks for hanging event broadcasts.
All family modules
Executes lifetick()
on each family module. There is a default implementation and families can implement their own lifetick. The default implementation checks for deadlocks in packet processing of all communication interfaces.
The script engine server
Checks for deadlocks in the communication with script engine clients.
All script engine clients
Checks if the RPC method processing backlog is getting too large. Currently it returns false
if there are more than 1000 items in one of the queues.
The Node-BLUE server
Checks for deadlocks in the communication with Node-BLUE clients.
All Node-BLUE clients
Checks if the node event and RPC method processing backlog is getting too large. Currently it returns false
if there are more than 1000 items in one of the queues.
The IPC server
Checks for deadlocks in the communication with IPC clients.
Parameters
This method has no parameters.
Return Values
Returns true
if all components are ok and false
if at least one component is not ok.
Examples
print_v($hg->lifetick());
print_v
Signatures
string print_v(mixed $variable [, bool $return = false])
Description
This method prints human-readable information about a Homegear variable returned by one of the RPC functions.
Parameters
Name | Type | Description | Example |
---|
variable | mixed | The variable to be printed | |
---|
return | bool | If it is set to "true", the information is returned as string and not printed. | true |
---|
Return Value
Returns information about the variable in question
GPIO Operations
HomegearGpio::close
Signatures
void close(int $index)
Description
This method closes a GPIO that was previously opened with HomegearGpio::open().
Parameters
Name | Type | Description | Example |
---|
index | int | The index of the GPIO to be closed | 18 |
---|
HomegearGpio::export
Signatures
void export(int $index)
Description
This method exports a GPIO. Make sure you have sufficient permissions to do that. If this is not the case, you can set "exportGpios" in /etc/homegear/main.conf. This setting tells Homegear to export the GPIOs when it starts up and before it drops its root privileges.
Parameters
Name | Type | Description | Example |
---|
index | int | The index of the GPIO to be exported | 18 |
---|
HomegearGpio::get
Signatures
bool get(int $index)
Description
This method gets the current state of a GPIO. Before this method is called, the GPIO needs to be opened with HomegearGpio::open().
Parameters
Name | Type | Description | Example |
---|
index | int | The index of the GPIO | 18 |
---|
Return Value
Returns the state of the GPIO
HomegearGpio::open
Signatures
void open(int $index)
Description
This method opens a GPIO. Make sure you have sufficient authorization to export GPIOs. If this is not the case, you can set "exportGpios" in /etc/homegear/main.conf. This setting tells Homegear to export the GPIOs when it starts up and before it drops its root privileges.
Parameters
Name | Type | Description | Example |
---|
index | int | The index of the GPIO to be opened | 18 |
---|
HomegearGpio::poll
Signatures
int poll(int $index, int $timeout [, bool $debounce = false])
Description
This method waits for a GPIO state change to occur. Before it is called, the GPIO needs to be opened by calling HomegearGpio::open(). This method blocks until the configured edge is detected on the GPIO (see setEdge()). It works only if the GPIO is configured as input. If no state change occurs, this method requires almost no system resources.
Parameters
Name | Type | Description | Example |
---|
index | int | The index of the GPIO | 18 |
---|
timeout | int | The maximum time (in milliseconds) the system should wait for a state change | |
---|
debounce | bool | When this is set, Homegear waits for 20 ms after receiving an interrupt. Set it if the GPIO is connected to an analog input, such as a switch. | true |
---|
Return Value
Returns the state (0 or 1) on success
Errors
Code | Description |
---|
-1 | Error reading the GPIO |
---|
-2 | Timeout |
---|
Example Output
poll(17, 5000)
1
Example
<?php
/*
* This example waits for a change on GPIO 22 and mirrors the new state of GPIO 22 to GPIO 24.
*/
use Homegear\HomegearGpio as HomegearGpio;
// Create Homegear object.
$hg = new Homegear\Homegear();
// Create GPIO object.
$gpio = new HomegearGpio();
// Open GPIO.
$gpio->open(22);
// Set direction to input.
$gpio->setDirection(22, HomegearGpio::DIRECTION_IN);
// Set edge to both.
$gpio->setEdge(22, HomegearGpio::EDGE_BOTH);
// We just opened the GPIO, so poll to discard the occured change.
$result = $gpio->poll(22, 1);
$result = -2;
while($result == -2) // Stay in loop if poll times out.
{
// Wait for state change.
$result = $gpio->poll(22, 5000, true);
}
if($result == -1) die("Error reading GPIO");
$hg->log(4, "Value of GPIO 22: ".$result);
// Close GPIO.
$gpio->close(22);
// Open output GPIO
$gpio->open(24);
// Set direction to output.
$gpio->setDirection(24, HomegearGpio::DIRECTION_OUT);
// Set state of GPIO 24 to state of GPIO 22.
$gpio->set(24, $result);
// Close GPIO 24
$gpio->close(24);
?>
HomegearGpio::set
Signatures
void set(int $index, bool $value)
Description
This method sets the state of a GPIO. Before this method is called, the GPIO needs to be opened with HomegearGpio::open().
Parameters
Name | Type | Description | Example |
---|
index | int | The index of the GPIO | 18 |
---|
value | bool | The new state to be set | true |
---|
HomegearGpio::setDirection
Signatures
void setDirection(int $index, int $direction)
Description
This method sets the direction of a GPIO. Before this method is called, the GPIO needs to be opened with HomegearGpio::open().
Parameters
Name | Type | Description | Example |
---|
index | int | The index of the GPIO | 18 |
---|
direction | int | This is the direction to be set. Possible values are HomegearGpio::DIRECTION_IN (0) and HomegearGpio::DIRECTION_OUT (1). | HomegearGpio::DIRECTION_OUT |
---|
HomegearGpio::setEdge
Signatures
void setEdge(int $index, int $edge)
Description
This method sets the edge of a GPIO for which you want to generate interrupts. Before this method is called, the GPIO needs to be opened with HomegearGpio::open().
Parameters
Name | Type | Description | Example |
---|
index | int | The index of the GPIO | 18 |
---|
edge | int | This is the edge for which you want to generate interrupts. Possible values are HomegearGpio::EDGE_RISING (0), HomegearGpio::EDGE_FALLING (1), and HomegearGpio::EDGE_BOTH (2). | HomegearGpio::EDGE_FALLING |
---|
I²C Communication
HomegearI2c::close
Signatures
bool close(resource $handle)
Description
This method closes an I²C device that was previously opened with HomegearI2c::open().
Parameters
Name | Type | Description | Example |
---|
handle | resource | The file pointer resource returned by HomegearI2c::open() | |
---|
Return Value
Returns "true" on success
Errors
Code | Description |
---|
false | The device could not be closed. |
---|
HomegearI2c::open
Signatures
resource open(string $device, int $address)
Description
This method opens an I²C device and returns a device handle that is needed for HomegearI²C::read() and HomegearI²C::write().
Parameters
Name | Type | Description | Example |
---|
device | string | The device to be opened | /dev/ttyAMA0 |
---|
address | int | The I²C device address | 0x28 |
---|
Return Value
Returns the file pointer resource handle of the I²C device
Errors
Code | Description |
---|
false | Could not open device |
---|
HomegearI2c::read
Signatures
string read(resource $handle, int length, bool $returnBinary)
Description
This method reads data from an I²C device that was previously opened with HomegearI2c::open().
Parameters
Name | Type | Description | Example |
---|
handle | resource | The file pointer resource returned by HomegearI2c::open() | |
---|
length | int | The number of bytes to read. | 5 |
---|
returnBinary | bool | Returns raw binary data instead of hexadecimal string | false |
---|
Return Value
Returns the read hexadecimal string on success or raw binary data if "returnBinary" is set to "true".
Errors
Code | Description |
---|
false | Error reading from device |
---|
HomegearI2c::write
Signatures
bool write(resource $handle, string $data [, bool $dataIsBinary = false])
Description
This method writes data to an I²C device that was previously opened with HomegearI2c::open().
Parameters
Name | Type | Description | Example |
---|
handle | resource | The file pointer resource returned by HomegearI2c::open() | |
---|
data | string | The data as a hexadecimal string | 8F727ACC3022 |
---|
dataIsBinary | bool | Data is in raw binary format instead of a hexadecimal string | true |
---|
Return Value
Returns "true" on success
Errors
Code | Description |
---|
false | Error writing to device |
---|
Licensing
Homegear::checkLicense
Signatures
int checkLicense(int $licenseModuleId, int $familyId, int $deviceId [, string $licenseKey])
Description
This method checks if a device or module is licensed or registers a new license key.
Parameters
Name | Type | Description | Example |
---|
licenseModuleId | int | The ID of the license module to be used | 0x7000 |
---|
familyId | int | The ID of the family to be checked or for which you want to register a license key | 12 |
---|
deviceId | int | This is the ID of the device to be checked or for which you want to register a license key. Set it to "-1" to check the whole family. | 216 |
---|
licenseKey | string | The license key to be registered | ABCDEF-GHIJKL-MNOPQR |
---|
Return Value
It returns "0" on success and if the license key is already known. It returns "1" in the case of a new activation.
Errors
Code | Description |
---|
-1 | Application error |
---|
-2 | License module not found |
---|
-3 | Communication error |
---|
-4 | Invalid data from activation server |
---|
-5 | License key is invalid |
---|
-6 | License key is valid but blocked |
---|
-7 | Activation key validation failed |
---|
-8 | Parameter license key is empty, and no activation data was found in the database |
---|
-9 | Parameter license key is empty, and activation key validation via database has failed |
---|
Exceptions
Exception | Description |
---|
HomegearException | |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->checkLicense(0x7000, 12, -1, "ABCDEF"));'
Homegear::getLicenseStates
Signatures
array getLicenseStates(int $licenseModuleId)
Description
This method returns all license information known to a license module.
Parameters
Name | Type | Description | Example |
---|
licenseModuleId | int | The ID of the license module to be used | 0x7000 |
---|
Return Value
It returns an array with one element for each license entry. Each element is an associative array with information about the family, activation state, and license.
Errors
Code | Description |
---|
false | License module not found |
---|
Exceptions
Exception | Description |
---|
HomegearException | |
---|
Homegear::removeLicense
Signatures
int removeLicense(int $licenseModuleId, int $familyId, int $deviceId)
Description
This method removes a license key and activation data previously registered with checkLicense().
Parameters
Name | Type | Description | Example |
---|
licenseModuleId | int | The ID of the license module to be used | 0x7000 |
---|
familyId | int | The ID of the family whose license key is to be removed | 12 |
---|
deviceId | int | The ID of the device whose license key is to be removed. It is set to "-1" if the license key was registered for the whole family. | 216 |
---|
Return Value
It returns "0" on success and if the license key is already known. It returns "1" in the case of a new activation.
Errors
Code | Description |
---|
-1 | Application error |
---|
-2 | License module not found |
---|
Exceptions
Exception | Description |
---|
HomegearException | |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->removeLicense(0x7000, 12, -1));'
Modules
Homegear::listModules
Signatures
array listModules()
Description
This method lists all Homegear modules (loaded and not loaded) located in the module directory (/var/lib/homegear/modules by default).
Parameters
This method has no parameters.
Return Value
It returns an array with one entry for each module. Each of these entries is in turn an associative array containing information about the module.
Exceptions
Exception | Description |
---|
HomegearException | |
---|
Example Output
var_dump($hg->listModules())
array(3) {
[0]=>
array(5) {
["BASELIB_VERSION"]=>
string(10) "0.6.0-1051"
["FAMILY_ID"]=>
int(0)
["FAMILY_NAME"]=>
string(16) "HomeMatic BidCoS"
["FILENAME"]=>
string(22) "mod_homematicbidcos.so"
["LOADED"]=>
bool(true)
}
[1]=>
array(5) {
["BASELIB_VERSION"]=>
string(10) "0.6.0-1051"
["FAMILY_ID"]=>
int(254)
["FAMILY_NAME"]=>
string(13) "Miscellaneous"
["FILENAME"]=>
string(20) "mod_miscellaneous.so"
["LOADED"]=>
bool(true)
}
[2]=>
array(5) {
["BASELIB_VERSION"]=>
string(10) "0.6.0-1051"
["FAMILY_ID"]=>
int(8)
["FAMILY_NAME"]=>
string(7) "EASYLed"
["FILENAME"]=>
string(14) "mod_easyled.so"
["LOADED"]=>
bool(true)
}
}
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->loadModule("mod_miscellaneous.so"));'
Homegear::loadModule
Signatures
int loadModule(string $filename)
Description
This method loads a Homegear module from the module directory (/var/lib/homegear/modules by default).
Parameters
Name | Type | Description | Example |
---|
filename | string | The filename of the module to be loaded | mod_insteon.so |
---|
Return Value
It returns "0" on success and "1" if the module has already been loaded.
Errors
Code | Description |
---|
-1 | Unknown error |
---|
-2 | A module with the provided filename does not exist. |
---|
-3 | Module was compiled for wrong base library version. |
---|
-4 | Device family initialization was not successful |
---|
Exceptions
Exception | Description |
---|
HomegearException | Thrown if parameter errors occur. |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->loadModule("mod_miscellaneous.so"));'
Homegear::reloadModule
Signatures
int reloadModule(string $filename)
Description
This method fully reloads a Homegear module. It can be used to reread the device description files, for example.
Parameters
Name | Type | Description | Example |
---|
filename | string | The filename of the module to be reloaded | mod_insteon.so |
---|
Return Value
Returns "0" on success
Errors
Code | Description |
---|
-1 | Unknown error |
---|
-2 | A module with the filename provided does not exist |
---|
Exceptions
Exception | Description |
---|
HomegearException | Thrown if there are parameter errors |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->reloadModule("mod_miscellaneous.so"));'
Homegear::unloadModule
Signatures
int unloadModule(string $filename)
Description
This method unloads a Homegear module.
Parameters
Name | Type | Description | Example |
---|
filename | string | The filename of the module to be unloaded | mod_insteon.so |
---|
Return Value
It returns "0" on success and "1" if the module is not loaded.
Errors
Code | Description |
---|
-1 | Unknown error |
---|
-2 | A module with the specified filename does not exist. |
---|
Exceptions
Exception | Description |
---|
HomegearException | Thrown if parameter errors occur |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->unloadModule("mod_miscellaneous.so"));'
Nodes
HomegearNodeBase::frontendEventLog
Signatures
void frontendEventLog(string $message)
Description
Write a line to the Node-BLUE event log. Please note that this log is not persistent. It only is written when Node-BLUE is open and connected in a browser.
Parameters
$message
The message to write to the log.
Return Values
No value is returned.
Examples
frontendEventLog('My message to Node-BLUE.');
HomegearNodeBase::invokeIpcProcessMethod
Signatures
variant invokeIpcProcessMethod(int $processId, string $methodName, array $parameters)
Description
Executes a RPC method on a specific process connected using Homegear's IPC interface. I. e. you can start a new process from a node, let this process connect over the IPC interface and then call RPC methods on it.
This method is used for example by Homegear's Python node.
Parameters
$processId
The ID of the process to execute the RPC method in.
$methodName
The name of the RPC method.
$parameters
The parameters.
Return Values
Returns the return value of the RPC call.
Examples
print_v(invokeIpcProcessMethod(5484, 'myRpcMethod, array('My 1st parameter', 2)));
HomegearNodeBase::invokeNodeMethod
Signatures
mixed invokeNodeMethod(string nodeId, string methodName, array parameters [, bool wait = true])
Description
This method is only available within a Node-BLUE node. It invokes a method defined within another node (except simple PHP and Python nodes) and can therefore be used for inter-node communication. This is especially required for a node to communicate with configuration nodes.
Parameters
Name | Type | Description | Example |
---|
nodeId | string | The ID of the node to call the method in. | "9062b368.e6068" |
---|
methodName | string | The name of the method to call. | myMethod |
---|
parameters | array | An indexed array with the parameters to pass to the method. | array(5, "param2") |
---|
wait | | Wait for method to return value. Set this to false if the return value is not needed. This saves a lot of resources. | false |
---|
Return Value
Returns the method's return value on success.
Example
$this->invokeNodeMethod("9062b368.e6068", "myMethod", array(5, "param2"));
HomegearNodeBase::log
Signatures
bool log(int $logLevel, string $message)
Description
This method is only available within a Node-BLUE node. It writes a message to the flows log and (if there are errors) to the error log file (/var/log/homegear/homegear-flows.log and /var/log/homegear/homegear-flows.err by default). To write to the main log file (homegear.log and homegear.err), use the RPC method writeLog().
Parameters
Name | Type | Description | Example |
---|
logLevel | int | This is the log level of the message. If Homegear's log level value is lower than this value, no message is logged. Valid values are:- 1: Critical
- 2: Error
- 3: Warning
- 4: Info
- 5: Debug
| 4 |
---|
message | string | This is the message that will be written to the log file. The date is prepended automatically. | My message |
---|
Return Value
Returns "true" on success
Errors
Code | Description |
---|
false | The message was empty. |
---|
Example
$this->log(3, "Hello Node-BLUE!");
HomegearNodeBase::nodeEvent
Signatures
void nodeEvent(string topic, mixed data[, bool retain = true])
Description
This method sends an event to the Node-BLUE frontend. The following events are available:
- status: Displays a status message below the node. topic needs to be statusBottom/<nodeId> and data an array with the keys text, fill and shape. text can be set to a small string. It is optional and should be short (< 20 characters). fill can be red, green, yellow, blue or grey. Valid values for shape are ring and dot. For example: array('text' => 'connected', 'fill' => 'green', 'shape' => 'dot').
- debug: Appends a message to the frontend debug log. topic has to be set to debug and message to an array with the keys id, name, msg, format and property. id is a node ID that is being displayed as the debug message's header. name is the node's type. msg is the message to display. format is the type of the message and has to be one of: array[<length>], boolean, number, string[<length>], Object or null. property the property of the message that is being shown.
Parameters
Name | Type | Description | Example |
---|
topic | string | The topic directs the message to the correct entity in Node-BLUE. | "statusBottom/9062b368.e6068" |
---|
data | mixed | The data to send to the entity defined by topic. | |
---|
retain | bool | By default node events are retained. Set this parameter to false to only send them once to currently connected frontends. | |
---|
Return Value
Returns void on success.
HomegearNodeBase::output
Signatures
void output(int outputIndex, array message)
Description
This method is only available within a Node-BLUE node. It sends data out of the node's outputs to the next connected nodes.
Parameters
Name | Type | Description | Example |
---|
outputIndex | int | The zero-based index of the output. | 2 |
---|
message | array | The associative array containing the message. There must at least be the element "payload" | array('payload' => 21.5) |
---|
Serial Communication (TTY)
HomegearSerial::close
Signatures
bool close(resource $handle)
Description
This method closes a serial device that was previously opened with HomegearSerial::open().
Parameters
Name | Type | Description | Example |
---|
handle | resource | The file pointer resource returned by HomegearSerial::open() | |
---|
Return Value
Returns "true" on sucess
Errors
Code | Description |
---|
false | Device could not be closed |
---|
HomegearSerial::open
Signatures
resource open(string $device, int $baudrate [, bool $evenParity = false [, bool $oddParity = false [, int $characterSize = 8 [, bool $twoStopBits = false]]]])
Description
This method opens a serial device and returns a device handle required for HomegearSerial::read() and HomegearSerial::write(). Remember to close the device with HomegearSerial::close() if you don't need it anymore.
Parameters
Name | Type | Description | Example |
---|
device | string | The device to be opened | /dev/ttyAMA0 |
---|
baudrate | int | The baudrate to be used | 19200 |
---|
evenParity | bool | Set to "true" if the data contains an even parity bit | true |
---|
oddParity | bool | Set to "true" if the data contains an odd parity bit. "evenParity" and "oddParity" are mutually exclusive. | true |
---|
characterSize | int | The character size in bits. Valid values are 5, 6, 7 or 8. | 7 |
---|
twoStopBits | bool | By default one stop bit is used. Set this argument to "true" to enable two stop bits. | true |
---|
Return Value
Returns the file pointer resource handle of the serial device
Errors
Code | Description |
---|
false | Device could not be opened |
---|
HomegearSerial::read
Signatures
string read(resource $handle, int $timeout)
Description
This method reads one character from a serial device that was previously opened with HomegearSerial::open().
Parameters
Name | Type | Description | Example |
---|
handle | resource | The file pointer resource returned by HomegearSerial::open() | |
---|
timeout | int | The maximum amount of time that the system waits for data (in milliseconds) | 5000 |
---|
Return Value
Returns the read character on success
Errors
Code | Description |
---|
-1 | Error reading from device |
---|
-2 | Timeout |
---|
HomegearSerial::readline
Signatures
string readline(resource $handle, int $timeout)
Description
This method reads one line of data (terminated by a new line character: 0x0A, "\n" or 0x0D0A, "\r\n") from a serial device that was previously opened with HomegearSerial::open().
Parameters
Name | Type | Description | Example |
---|
handle | resource | The file pointer resource returned by HomegearSerial::open() | |
---|
timeout | int | The maximum amount of time that the system should wait for data (in milliseconds) | 5000 |
---|
Return Value
Returns the read data as string on success
Errors
Code | Description |
---|
-1 | Error reading from device |
---|
-2 | Timeout |
---|
Example
<?php
/**
* This example shows you how to send and receive FS20 packets with a CUL stick.
* It logs all received FS20 packets and switches a switch on and off.
*/
define("CUL_DEVICE", "/dev/ttyACM0");
define("SWITCH_ON_PACKET", "F2E8E0011");
define("SWITCH_OFF_PACKET", "F2E8E0000");
/**
* Class to share data between the main script and the read thread.
*/
class SharedData extends Threaded
{
public $handle;
public function run() {}
}
/**
* Class to process events received from Homegear
*/
class ReadThread extends Thread
{
private $sharedData;
public function __construct($sharedData)
{
$this->sharedData = $sharedData;
}
public function run()
{
// Create a new Homegear object
$hg = new \Homegear\Homegear;
//In this special case, no "registerThread" is necessary.
//To call RPC methods, place a call to "registerThread" here.
// Create a new HomegearSerial object.
$serial = new \Homegear\HomegearSerial();
// Run the thread until Homegear shuts down.
while(!$hg->shuttingDown())
{
$result = $serial->readline($this->sharedData->handle, 5000);
if($result === -1) // Read error
{
// Reopen device
$serial->close($this->sharedData->handle);
$this->sharedData->handle = $serial->open(CUL_DEVICE, 38400);
// Listen for FS20 packets
$serial->write($this->sharedData->handle, "X21\n");
continue;
}
else if($result !== -2) // Timeout?
{
$hg->log(4, "FS20 packet received: ".trim($result));
}
else $hg->log(4, "Timeout.");
}
}
}
// Create a new Homegear object
$hg = new \Homegear\Homegear;
// Create a new HomegearSerial object.
$serial = new \Homegear\HomegearSerial();
// Create new object for sharing data between main and event thread.
$sharedData = new SharedData();
// Open the serial device and set speed to 38400 baud. Store the returned handle in $sharedData.
$sharedData->handle = $serial->open(CUL_DEVICE, 38400);
if($sharedData->handle === false) die("Could not open serial device.");
// Listen for FS20 packets
$serial->write($sharedData->handle, "X21\n");
// Create and start new read thread.
$thread = new ReadThread($sharedData);
$thread->start();
$on = false;
// Run main thread until Homegear shuts down.
while(!$hg->shuttingDown())
{
// Wait to be notified by event thread with a timeout of 5 seconds.
$thread->synchronized(function($thread){ $thread->wait(5000000); }, $thread);
if(!$on) // Switch on
{
$hg->log(4, "Sending \"switch on packet\"...");
if($serial->write($sharedData->handle, SWITCH_ON_PACKET."\n") === false)
{
$hg->log(2, "Error writing to CUL stick.");
}
$on = true;
}
else // Switch off
{
$hg->log(4, "Sending \"switch off packet\"...");
if($serial->write($sharedData->handle, SWITCH_OFF_PACKET."\n") === false)
{
$hg->log(2, "Error writing to CUL stick.");
}
$on = false;
}
}
// Wait for event thread to finish.
$thread->join();
?>
HomegearSerial::write
Signatures
bool write(resource $handle, string $data)
Description
This method writes one line of data (terminated by a new line character: 0x0A, "\n" or 0x0D0A, "\r\n") to a serial device that was previously opened with HomegearSerial::open().
Parameters
Name | Type | Description | Example |
---|
handle | resource | The file pointer resource returned by HomegearSerial::open() | |
---|
data | string | The data to be written; if you omit the new line character, it is automatically appended. | Hello world!\n |
---|
Return Value
Returns "true" on success
Errors
Code | Description |
---|
false | Error writing to device |
---|
Settings
Homegear::deleteFamilySetting
Signatures
void deleteFamilySetting(int $familyId, string $name)
Description
This method deletes a family setting from the database. The files for the family settings are not modified. If the setting does not exist, nothing happens.
Parameters
Name | Type | Description | Example |
---|
familyId | int | The family ID for which you want to delete the setting | 6 |
---|
name | string | The name of the setting you want to delete; use only lower-case characters here. | |
---|
Errors
Code | Description |
---|
-1 | Parameter error |
---|
-2 | Device family not found |
---|
Homegear::getFamilySetting
Signatures
mixed getFamilySetting(int $familyId, string $name)
Description
This method returns a family setting from the family settings file or the database. The database value is returned if the same setting exists in the database and in the settings file.
Parameters
Name | Type | Description | Example |
---|
familyId | int | The family ID you want to get the setting for | 6 |
---|
name | string | The name of the setting you want to return. Setting names from the configuration files are converted to lower-case characters. Therefore, to get "mySetting", you need to pass "mysetting" here. | |
---|
Return Value
This returns the setting. Possible types are integer, string, and binary.
Errors
Code | Description |
---|
-1 | Parameter error |
---|
-2 | Device family not found |
---|
-3 | Setting not found |
---|
Homegear::setFamilySetting
Signatures
void setFamilySetting(int $familyId, string $name, mixed $value)
Description
This method sets a family setting and stores it in the database. Database settings take precedence over the family's settings file.
Parameters
Name | Type | Description | Example |
---|
familyId | int | The family ID for which you want to make the setting | 6 |
---|
name | string | The name of the setting; use lower-case characters only. | |
---|
value | mixed | This is the value of the setting. Supported types are string, integer, and binary. | |
---|
Errors
Code | Description |
---|
-1 | Parameter error |
---|
-2 | Device family not found |
---|
-3 | Unsupported variable type |
---|
Users and Groups
Homegear::auth
Signatures
bool auth($username, $password)
Description
This method checks if a provided user name and password are correct.
Parameters
Name | Type | Description | Example |
---|
username | string | The name of the user | will |
---|
password | string | The password of the user | secret |
---|
Return Value
It returns "true" if the user name and password are correct; otherwise, it returns "false".
Exceptions
Exception | Description |
---|
HomegearException | |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->auth("homegear", "homegear"));'
Homegear::createGroup
Signatures
int createGroup($translations, $acl)
Description
This method creates a new group in Homegear. Each group as an Access Control List (ACL) assigned, which grants or denys a group permissions. The ACL is a struct with the following elements:
Key | Description |
---|
services | Grants or denies access to a service. Contains a struct with the service's name as key. Valid services are ui, admin-ui and node-blue. Allowed values are true to grant access and false to deny it. Wildcards: - Service key *: All services.
|
---|
variablesRead | Grants or denies read access to peer variables, peer metadata and system variables. Contains a struct with devices (key: peer ID), which again contains a struct with channels (key: channel number), which contains a struct with variables (key: variable name). Each variable entry can be set to true to grant access or to false to deny access. Wildcards and special values: - Device key 0: All devices
- Device key 0 and channel key -1: System variables
- Channel key -2: Metadata
- Channel key -3: All channels
- Variable key *: All variables
|
---|
variablesWrite | Grants or denies write access to peer variables, peer metadata and system variables. The structure is the same as for variablesRead. |
---|
devicesRead | Grants or denies read access to a peer. Contains a struct with the peer ID as key. Allowed values are true to grant access and false to deny it. Wildcards: - Device key 0: All devices
|
---|
devicesWrite | Grants or denies write access to a peer. The structure is the same as for devicesRead. |
---|
roomsRead | Grants or denies read access to a room. Contains a struct with the room ID as key. Allowed values are true to grant access and false to deny it. Special values: - Room key 0: Elements with no room set.
|
---|
roomsWrite | Grants or denies write access to a room. The structure is the same as for roomsRead. |
---|
categoriesRead | Grants or denies read access to a category. Contains a struct with the category ID as key. Allowed values are true to grant access and false to deny it. Special values: - Category key 0: Elements with no category set.
|
---|
categoriesWrite | Grants or denies write access to a category. The structure is the same as for categoriesRead. |
---|
methods | Grants or denies access to a RPC method. Contains a struct with the method's name as key. Allowed values are true to grant access and false to deny it. Wildcards: - Method key *: All RPC methods.
|
---|
eventServerMethods | Grants or denies access to RPC event server methods. The structure is the same as for methods. |
---|
methods and
eventServerMethods are always checked. For performance reasons all other ACL entries are only checked if defined. If undefined, access is granted. If access is specifically denied, the check returns immediately rejecting access even if access is granted somewhere else. If access is denied by a wildcard entry, a specific entry can still grant access (e. g. if access to all variables (
*) is denied, access to
TEMPERATURE still can be granted). If there are errors in the ACL structure, the method returns an error to avoid accidentally granting access due to a syntax error.
Parameters
Name | Type | Description | Example |
---|
translations | struct | The name of the group in different languages. The keys are the lower case ISO 639-1 language codes and the upper case ISO 3166-1 alpha-2 country codes seperated by a dash (e. g. en-US or fr-FR). The values are the group names in the different languages. | (Struct length=2)
{
[en-US]
{
(String) Guests
}
[de-DE]
{
(String) Gäste
}
} |
---|
acl | struct | The Access Control List (ACL) to assign to the group. | (Struct length=2)
{
[eventServerMethods]
{
(Struct length=1)
{
[*]
{
(Boolean) 1
}
}
}
[methods]
{
(Struct length=1)
{
[*]
{
(Boolean) 1
}
}
}
} |
---|
Return Value
Returns the ID of the new group on success
Exceptions
Exception | Description |
---|
HomegearException | Returned if parameters are invalid |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'print_v($hg->createGroup(array("en-US" => "Guests", "de-DE" => "Gäste"), array("variablesRead" => array(3 => array(1 => array("TEMPERATURE" => true, "HUMIDITY" => true)), 5 => array(1 => array("TEMPERATURE" => true))), "variablesWrite" => array(), "methods" => array("*" => true), "eventServerMethods" => array("*" => true))));'
Homegear::createUser
Signatures
bool createUser($username, $password, $groups)
bool createUser($username, $password, $groups, $metadata)
Description
This method creates a new user in Homegear.
Parameters
Name | Type | Description | Example |
---|
username | string | The alphanumeric name of the new user | will |
---|
password | string | The password of the new user | secret |
---|
groups | array | An array of group IDs the user should belong to | array(1, 7) |
---|
metadata | mixed | Metadata to store with the user | array("adminUi" => true) |
---|
Return Value
Returns "true" on success
Exceptions
Exception | Description |
---|
HomegearException | Returned if parameters are invalid |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'print_v($hg->createUser("foo", "foobar01", array(1)));'
Homegear::deleteGroup
Signatures
void deleteGroup($groupId)
Description
This method deletes an existing group.
Parameters
Exceptions
Exception | Description |
---|
HomegearException | Returned if parameters are invalid |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc '$hg->deleteGroup(100);'
Homegear::deleteUser
Signatures
bool deleteUser($username)
Description
This method deletes an existing user from Homegear.
Parameters
Name | Type | Description | Example |
---|
username | string | The name of the user to be deleted | will |
---|
Return Value
Returns "true" on success
Errors
Code | Description |
---|
false | An error has occurred (e. g. the user does not exist). |
---|
Exceptions
Exception | Description |
---|
HomegearException | Returned if parameters are invalid |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->deleteUser("foo"));'
Homegear::getGroup
Signatures
struct getGroup($groupId)
Description
This method returns the translations and the ACL of an existing group.
Parameters
Exceptions
Exception | Description |
---|
HomegearException | Returned if parameters are invalid |
---|
Example Output
Homegear::getGroup(1)
(Struct length=3)
{
[ACL]
{
(Struct length=2)
{
[eventServerMethods]
{
(Struct length=1)
{
[*]
{
(Boolean) 1
}
}
}
[methods]
{
(Struct length=1)
{
[*]
{
(Boolean) 1
}
}
}
}
}
[ID]
{
(Integer64) 1
}
[TRANSLATIONS]
{
(Struct length=2)
{
[de-DE]
{
(String) Administratoren
}
[en-US]
{
(String) Administrators
}
}
}
}
Homegear::getGroups
Signatures
array getGroups()
Description
This method returns the ID, translations and the ACL of all existing groups.
Parameters
This method has no parameters.
Return Value
Returns an array with one element for each group. Each element is a
struct with the keys
ID,
TRANSLATIONS and
ACL.
Exceptions
Exception | Description |
---|
HomegearException | Returned if parameters are invalid |
---|
Signatures
struct getUserMetadata($username)
Description
This method retrieves the metadata previously stored for a user.
Parameters
Name | Type | Description | Example |
---|
username | string | The name of the user | will |
---|
Return Value
Returns the metadata on success
Exceptions
Exception | Description |
---|
HomegearException | It is returned if parameters are invalid. |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'print_v($hg->getUserMetadata("foo"));'
Homegear::getUsersGroups
Signatures
array getUsersGroups($username)
Description
This method returns all IDs of the groups a user is assigned to.
Parameters
Name | Type | Description | Example |
---|
username | string | The name of the user | will |
---|
Return Value
Returns the group IDs as an array on success.
Exceptions
Exception | Description |
---|
HomegearException | It is returned if parameters are invalid. |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'print_v($hg->getUsersGroups("foo"));'
Homegear::groupExists
Signatures
bool groupExists($groupId)
Description
This method checks if the group with the given ID exists.
Parameters
Return Value
Returns
true if the group exists and
false otherwise.
Exceptions
Exception | Description |
---|
HomegearException | Returned if parameters are invalid |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->groupExists(100));'
Homegear::listUsers
Signatures
array listUsers()
Description
This method returns an array with all user names known to Homegear.
Parameters
This method has no parameters.
Return Value
Returns an array with all user names, their group IDs and their metadata. Each array element is a struct with four entries: "id" of type
int, "name" of type
string, "groups" of type
array<int> and "metadata" of type
struct.
Exceptions
Exception | Description |
---|
HomegearException | |
---|
Example Output
print_v($hg->listUsers())
(Array length=1)
{
(Struct length=4)
{
[groups]
{
(Array length=1)
{
(Integer64) 1
}
}
[id]
{
(Integer64) 1
}
[metadata]
{
(Struct length=0)
{
}
}
[name]
{
(String) homegear
}
}
}
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'print_v($hg->listUsers());'
Signatures
bool setUserMetadata($username, $metadata)
Description
This method adds arbitrary metadata to an existing user in Homegear.
Parameters
Name | Type | Description | Example |
---|
username | string | The name of the user | will |
---|
metadata | struct | The metadata to store | |
---|
Return Value
Returns "true" on success
Errors
Code | Description |
---|
false | Something has gone wrong (e. g. the user does not exist) |
---|
Exceptions
Exception | Description |
---|
HomegearException | It is returned if parameters are invalid. |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->setUserMetadata("foo", array("bar" => 12, "bar2" => "test")));'
Homegear::setUserPrivileges
Signatures
bool setUserPrivileges($username)
Description
This method drops script engine privileges to the specified user's. By default the script engine runs as system group 2. After executing this method, all Homegear method calls of the executing thread are executed with the privileges of the specified user.
Parameters
Name | Type | Description | Example |
---|
username | string | The alphanumeric name of the user | will |
---|
Return Value
Returns "true" on success
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'print_v($hg->setUserPrivileges("foo"));'
Homegear::updateGroup
Signatures
void updateGroup($groupId, $acl)
void updateGroup($groupId, $translations, $acl)
Description
This method updates the names or the ACL of an existing group.
Parameters
Name | Type | Description | Example |
---|
groupId | int | The ID of the group as returned by createGroup() or getGroups(). | 100 |
---|
translations | struct | The name of the group in different languages. The keys are the lower case ISO 639-1 language codes and the upper case ISO 3166-1 alpha-2 country codes seperated by a dash (e. g. en-US or fr-FR). The values are the group names in the different languages. | (Struct length=2)
{
[en-US]
{
(String) Guests
}
[de-DE]
{
(String) Gäste
}
} |
---|
acl | struct | The Access Control List (ACL) to assign to the group. See createGroup() for information about the ACL structure. | (Struct length=2)
{
[eventServerMethods]
{
(Struct length=1)
{
[*]
{
(Boolean) 1
}
}
}
[methods]
{
(Struct length=1)
{
[*]
{
(Boolean) 1
}
}
}
} |
---|
Exceptions
Exception | Description |
---|
HomegearException | Returned if parameters are invalid |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'print_v($hg->updateGroup(100, array("en-US" => "Guests", "de-DE" => "Gäste"), array("variablesRead" => array(3 => array(1 => array("TEMPERATURE" => true, "HUMIDITY" => true)), 5 => array(1 => array("TEMPERATURE" => true))), "variablesWrite" => array(), "methods" => array("*" => true), "eventServerMethods" => array("*" => true))));'
Homegear::updateUser
Signatures
bool updateUser($username, $password)
bool updateUser($username, $groups)
bool updateUser($username, $password, $groups)
Description
This method updates the password of an existing user in Homegear.
Parameters
Name | Type | Description | Example |
---|
username | string | The name of the user | will |
---|
password | string | The new password of the user | new_secret |
---|
groups | array | An array of group IDs the user should belong to | array(1, 7) |
---|
Return Value
Returns "true" on success
Errors
Code | Description |
---|
false | Something has gone wrong (e. g. the user does not exist) |
---|
Exceptions
Exception | Description |
---|
HomegearException | It is returned if parameters are invalid. |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->updateUser("foo", "foobar02"));'
Homegear::userExists
Signatures
bool userExists($username)
Description
This method checks if a user is known to Homegear.
Parameters
Name | Type | Description | Example |
---|
username | string | The name of the user to be checked | will |
---|
Return Value
It returns "true" if the user exists and "false" if not.
Exceptions
Exception | Description |
---|
HomegearException | Returned if parameters are invalid |
---|
Example
/**
* Execute this command in your terminal
*/
homegear -e rc 'var_dump($hg->userExists("homegear"));'