PHP Method Reference

List of Functions

CategoryMethodDescription
GeneralHomegear::configureGatewaySets the certificates on an unconfigured Homegear Gateway
GeneralHomegear::downloadDownloads a file from a web server
GeneralHomegear::getHttpContentsReturns the source of a web page
GeneralHomegear::getScriptIdReturns the ID and token of the current script
GeneralHomegear::listRpcClientsReturns information about all registered RPC event servers
GeneralHomegear::logWrites a message to the script engine log file
GeneralHomegear::mqttPublishDisables reception of events
GeneralHomegear::peerExistsChecks if a peers exists
GeneralHomegear::pollEventWaits for an event from Homegear
GeneralHomegear::raiseDeleteDeviceSends deleteDevices() to all RPC event servers
GeneralHomegear::registerThreadMakes a new thread known to Homegear
GeneralHomegear::setScriptLogLevelSets the log level for the current script
GeneralHomegear::shuttingDownChecks if Homegear is shuttingDown
GeneralHomegear::ssdpSearchSearches for SSDP devices on the network
GeneralHomegear::subscribePeerEnables reception of events for a device
GeneralHomegear::unsubscribePeerDisables reception of events
GenerallifetickChecks the state of all essential Homegear components.
Generalprint_vPrints human-readable information about a Homegear variable
GPIO OperationsHomegearGpio::closeCloses a GPIO
GPIO OperationsHomegearGpio::exportExports a GPIO
GPIO OperationsHomegearGpio::getGets the current state of a GPIO
GPIO OperationsHomegearGpio::openOpens a GPIO
GPIO OperationsHomegearGpio::pollWaits for a GPIO state change to occur
GPIO OperationsHomegearGpio::setSets the state of a GPIO
GPIO OperationsHomegearGpio::setDirectionSets the direction of a GPIO
GPIO OperationsHomegearGpio::setEdgeSets the edge of a GPIO for which interrupts are to be generated
I²C CommunicationHomegearI2c::closeCloses an I²C device
I²C CommunicationHomegearI2c::openOpens an I²C device
I²C CommunicationHomegearI2c::readReads data from an I²C device
I²C CommunicationHomegearI2c::writeWrites data to an I²C device
LicensingHomegear::checkLicenseChecks if a device or module is licensed or registers a new license key
LicensingHomegear::getLicenseStatesReturns license information
LicensingHomegear::removeLicenseRemoves a license key previously registered with checkLicense()
ModulesHomegear::listModulesLists all Homegear modules
ModulesHomegear::loadModuleLoads a Homegear module
ModulesHomegear::reloadModuleReloads a Homegear module
ModulesHomegear::unloadModuleUnloads a Homegear module
NodesHomegearNodeBase::frontendEventLogWrites a line to the Node-BLUE event log
NodesHomegearNodeBase::invokeIpcProcessMethodExecutes a RPC method of a specific process connected over IPC.
NodesHomegearNodeBase::invokeNodeMethodInvokes a node-specific RPC method
NodesHomegearNodeBase::logWrites a message to the flows log file
NodesHomegearNodeBase::nodeEventSends an event to the Node-BLUE frontend
NodesHomegearNodeBase::outputSends data to a node output
Serial Communication (TTY)HomegearSerial::closeCloses a serial device
Serial Communication (TTY)HomegearSerial::openOpens a serial device
Serial Communication (TTY)HomegearSerial::readReads a single character from a serial device
Serial Communication (TTY)HomegearSerial::readlineReads data from a serial device
Serial Communication (TTY)HomegearSerial::writeWrites data to a serial device
SettingsHomegear::deleteFamilySettingDeletes a family setting from the database
SettingsHomegear::getFamilySettingReturns a family setting
SettingsHomegear::setFamilySettingSets a family setting
Users and GroupsHomegear::authValidates a user name / password combination
Users and GroupsHomegear::createGroupCreates a new group
Users and GroupsHomegear::createUserCreates a new user
Users and GroupsHomegear::deleteGroupDeletes a group
Users and GroupsHomegear::deleteUserDeletes an existing user
Users and GroupsHomegear::getGroupReturns the translations and the ACL of a group
Users and GroupsHomegear::getGroupsReturns the ID, translations and the ACL of all groups
Users and GroupsHomegear::getUserMetadataRetrieves the metadata stored for a user
Users and GroupsHomegear::getUsersGroupsReturns the groups a user is assigned to
Users and GroupsHomegear::groupExistsChecks if a group exists
Users and GroupsHomegear::listUsersReturns all user names
Users and GroupsHomegear::setUserMetadataAdds arbitrary metadata to a user
Users and GroupsHomegear::setUserPrivilegesDrops script engine privileges to a users's
Users and GroupsHomegear::updateGroupCreates a new group
Users and GroupsHomegear::updateUserUpdates the password of an existing user
Users and GroupsHomegear::userExistsChecks if a user is known to Homegear

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

Homegear::configureGateway

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

NameTypeDescriptionExample
hoststringThe host name or IP address of the gateway to connect to.
192.168.178.104
portintThe port number the gateway service listens on. The default value is 2017.
2017
caCertstringThe Base64 encoded CA certificate.
gatewayCertstringThe Base64 encoded gateway certificate.
gatewayKeystringThe Base64 encoded gateway private key.
passwordstringThe password as specifed in gateway.conf of or printed on the gateway.
aJn10ymAkloiq28nKlOlf4QjsN

Return Value

Returns void on success.

Exceptions

ExceptionDescription
HomegearExceptionThrown 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

NameTypeDescriptionExample
hostnamestringThe hostname of the web server you want to get the source from
www.example.com
portintThe port number the web server listens on
443
pathstringThe path of the file to be returned
/path/to/file.dat
filenamestringThe filename to which you want to save the file
/local/path/to/file.dat
caFilestringThe path to the certificate file you want to use to verify the web server certificate
/path/to/my/ca-certificates.pem
verifyCertificateboolEnables 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

NameTypeDescriptionExample
hostnamestringThe hostname of the web server that you use to get the source
www.example.com
portintThe port number the web server listens on
443
pathstringThe path of the file to be returned
/path/to/file.html
caFilestringThe path to the certificate file that is used to check the web server certificate
/path/to/my/ca-certificates.pem
verifyCertificateboolIt 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

ExceptionDescription
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

NameTypeDescriptionExample
logLevelintThis 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
messagestringThis 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

CodeDescription
falseThe 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

NameTypeDescriptionExample
topicstringThe 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
payloadstringThe payload to publish. Empty payloads are not allowed.
{"value": 5}

Exceptions

ExceptionDescription
HomegearExceptionThrown 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

NameTypeDescriptionExample
peerIdintThe peer ID to be checked
43

Return Value

"true" if the peer exists, "false" if not

Exceptions

ExceptionDescription
HomegearExceptionOccurs 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

NameTypeDescriptionExample
timeoutintThe 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:
KeyValue
TYPEThe event method called ("event", "deleteDevices", "newDevices" or "updateDevice").
PEERIDThe ID of the peer raising the event. Set for "event" and "updateDevice".
CHANNELThe channel the event is raised for. Set for "event" and "updateDevice".
VARIABLEThe updated variable. Set for "event".
VALUEThe new value of the variable ("event"), an array of the type DeviceDescription ("newDevices"), or an array with information about the deleted devices ("deleteDevices")..
HINTSet for "updateDevice". 0: Device or channel configuration changed; 1: Device links changed; 2: Teams changed.

Errors

CodeDescription
falseReturned 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

NameTypeDescriptionExample
serialNumbersarrayList 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

NameTypeDescriptionExample
scriptIdstringThis 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

NameTypeDescriptionExample
logLevelintThe 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

CodeDescription
falseThe 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());'
 

Homegear::ssdpSearch

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

NameTypeDescriptionExample
stHeaderstringThe 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
timeoutintThe 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

CodeDescription
falseReturned 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

NameTypeDescriptionExample
peerIdintThe ID of the peer to get events for
32
channelintThe channel to get events for. If $channel and $variableName are ommitted, all events for that peer are received.
2
variableNamestringThe variable to get events for
2

Exceptions

ExceptionDescription
HomegearExceptionThis 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

NameTypeDescriptionExample
peerIdintThe ID of the peer to be unsubscribed
32
channelintThe channel to get events for. If $channel and $variableName are ommitted, all events for that peer are unsubscribed.
2
variableNamestringThe variable to get events for
2

Exceptions

ExceptionDescription
HomegearExceptionThis 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

NameTypeDescriptionExample
variablemixedThe variable to be printed
returnboolIf 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

NameTypeDescriptionExample
indexintThe 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

NameTypeDescriptionExample
indexintThe 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

NameTypeDescriptionExample
indexintThe 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

NameTypeDescriptionExample
indexintThe 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

NameTypeDescriptionExample
indexintThe index of the GPIO
18
timeoutintThe maximum time (in milliseconds) the system should wait for a state change
debounceboolWhen 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

CodeDescription
-1Error reading the GPIO
-2Timeout

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

NameTypeDescriptionExample
indexintThe index of the GPIO
18
valueboolThe 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

NameTypeDescriptionExample
indexintThe index of the GPIO
18
directionintThis 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

NameTypeDescriptionExample
indexintThe index of the GPIO
18
edgeintThis 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

NameTypeDescriptionExample
handleresourceThe file pointer resource returned by HomegearI2c::open()

Return Value

Returns "true" on success

Errors

CodeDescription
falseThe 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

NameTypeDescriptionExample
devicestringThe device to be opened
/dev/ttyAMA0
addressintThe I²C device address
0x28

Return Value

Returns the file pointer resource handle of the I²C device

Errors

CodeDescription
falseCould 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

NameTypeDescriptionExample
handleresourceThe file pointer resource returned by HomegearI2c::open()
lengthintThe number of bytes to read.
5
returnBinaryboolReturns 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

CodeDescription
falseError 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

NameTypeDescriptionExample
handleresourceThe file pointer resource returned by HomegearI2c::open()
datastringThe data as a hexadecimal string
8F727ACC3022
dataIsBinaryboolData is in raw binary format instead of a hexadecimal string
true

Return Value

Returns "true" on success

Errors

CodeDescription
falseError 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

NameTypeDescriptionExample
licenseModuleIdintThe ID of the license module to be used
0x7000
familyIdintThe ID of the family to be checked or for which you want to register a license key
12
deviceIdintThis 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
licenseKeystringThe 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

CodeDescription
-1Application error
-2License module not found
-3Communication error
-4Invalid data from activation server
-5License key is invalid
-6License key is valid but blocked
-7Activation key validation failed
-8Parameter license key is empty, and no activation data was found in the database
-9Parameter license key is empty, and activation key validation via database has failed

Exceptions

ExceptionDescription
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

NameTypeDescriptionExample
licenseModuleIdintThe 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

CodeDescription
falseLicense module not found

Exceptions

ExceptionDescription
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

NameTypeDescriptionExample
licenseModuleIdintThe ID of the license module to be used
0x7000
familyIdintThe ID of the family whose license key is to be removed
12
deviceIdintThe 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

CodeDescription
-1Application error
-2License module not found

Exceptions

ExceptionDescription
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

ExceptionDescription
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

NameTypeDescriptionExample
filenamestringThe 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

CodeDescription
-1Unknown error
-2A module with the provided filename does not exist.
-3Module was compiled for wrong base library version.
-4Device family initialization was not successful

Exceptions

ExceptionDescription
HomegearExceptionThrown 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

NameTypeDescriptionExample
filenamestringThe filename of the module to be reloaded
mod_insteon.so

Return Value

Returns "0" on success

Errors

CodeDescription
-1Unknown error
-2A module with the filename provided does not exist

Exceptions

ExceptionDescription
HomegearExceptionThrown 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

NameTypeDescriptionExample
filenamestringThe 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

CodeDescription
-1Unknown error
-2A module with the specified filename does not exist.

Exceptions

ExceptionDescription
HomegearExceptionThrown 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

NameTypeDescriptionExample
nodeIdstringThe ID of the node to call the method in.
"9062b368.e6068"
methodNamestringThe name of the method to call.
myMethod
parametersarrayAn indexed array with the parameters to pass to the method.
array(5, "param2")
waitWait 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

NameTypeDescriptionExample
logLevelintThis 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
messagestringThis 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

CodeDescription
falseThe 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

NameTypeDescriptionExample
topicstringThe topic directs the message to the correct entity in Node-BLUE.
"statusBottom/9062b368.e6068"
datamixedThe data to send to the entity defined by topic.
retainboolBy 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

NameTypeDescriptionExample
outputIndexintThe zero-based index of the output.
2
messagearrayThe 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

NameTypeDescriptionExample
handleresourceThe file pointer resource returned by HomegearSerial::open()

Return Value

Returns "true" on sucess

Errors

CodeDescription
falseDevice 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

NameTypeDescriptionExample
devicestringThe device to be opened
/dev/ttyAMA0
baudrateintThe baudrate to be used
19200
evenParityboolSet to "true" if the data contains an even parity bit
true
oddParityboolSet to "true" if the data contains an odd parity bit. "evenParity" and "oddParity" are mutually exclusive.
true
characterSizeintThe character size in bits. Valid values are 5, 6, 7 or 8.
7
twoStopBitsboolBy 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

CodeDescription
falseDevice 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

NameTypeDescriptionExample
handleresourceThe file pointer resource returned by HomegearSerial::open()
timeoutintThe maximum amount of time that the system waits for data (in milliseconds)
5000

Return Value

Returns the read character on success

Errors

CodeDescription
-1Error reading from device
-2Timeout
 

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

NameTypeDescriptionExample
handleresourceThe file pointer resource returned by HomegearSerial::open()
timeoutintThe 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

CodeDescription
-1Error reading from device
-2Timeout

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

NameTypeDescriptionExample
handleresourceThe file pointer resource returned by HomegearSerial::open()
datastringThe 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

CodeDescription
falseError 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

NameTypeDescriptionExample
familyIdintThe family ID for which you want to delete the setting
6
namestringThe name of the setting you want to delete; use only lower-case characters here.

Errors

CodeDescription
-1Parameter error
-2Device 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

NameTypeDescriptionExample
familyIdintThe family ID you want to get the setting for
6
namestringThe 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

CodeDescription
-1Parameter error
-2Device family not found
-3Setting 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

NameTypeDescriptionExample
familyIdintThe family ID for which you want to make the setting
6
namestringThe name of the setting; use lower-case characters only.
valuemixedThis is the value of the setting. Supported types are string, integer, and binary.

Errors

CodeDescription
-1Parameter error
-2Device family not found
-3Unsupported 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

NameTypeDescriptionExample
usernamestringThe name of the user
will
passwordstringThe password of the user
secret

Return Value

It returns "true" if the user name and password are correct; otherwise, it returns "false".

Exceptions

ExceptionDescription
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:

KeyDescription
servicesGrants 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.
variablesReadGrants 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
variablesWriteGrants or denies write access to peer variables, peer metadata and system variables. The structure is the same as for variablesRead.
devicesReadGrants 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
devicesWriteGrants or denies write access to a peer. The structure is the same as for devicesRead.
roomsReadGrants 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.
roomsWriteGrants or denies write access to a room. The structure is the same as for roomsRead.
categoriesReadGrants 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.
categoriesWriteGrants or denies write access to a category. The structure is the same as for categoriesRead.
methodsGrants 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.
eventServerMethodsGrants 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

NameTypeDescriptionExample
translationsstructThe 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
  }
}
aclstructThe 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

ExceptionDescription
HomegearExceptionReturned 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

NameTypeDescriptionExample
usernamestringThe alphanumeric name of the new user
will
passwordstringThe password of the new user
secret
groupsarrayAn array of group IDs the user should belong to
array(1, 7)
metadatamixedMetadata to store with the user
array("adminUi" => true)

Return Value

Returns "true" on success

Exceptions

ExceptionDescription
HomegearExceptionReturned 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

NameTypeDescriptionExample
groupIdintThe ID of the group as returned by createGroup() or getGroups().
100

Exceptions

ExceptionDescription
HomegearExceptionReturned 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

NameTypeDescriptionExample
usernamestringThe name of the user to be deleted
will

Return Value

Returns "true" on success

Errors

CodeDescription
falseAn error has occurred (e. g. the user does not exist).

Exceptions

ExceptionDescription
HomegearExceptionReturned 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

NameTypeDescriptionExample
groupIdintThe ID of the group as returned by createGroup() or getGroups().
100

Exceptions

ExceptionDescription
HomegearExceptionReturned 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

ExceptionDescription
HomegearExceptionReturned if parameters are invalid
 

Homegear::getUserMetadata

Signatures

struct getUserMetadata($username)

Description

This method retrieves the metadata previously stored for a user.

Parameters

NameTypeDescriptionExample
usernamestringThe name of the user
will

Return Value

Returns the metadata on success

Exceptions

ExceptionDescription
HomegearExceptionIt 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

NameTypeDescriptionExample
usernamestringThe name of the user
will

Return Value

Returns the group IDs as an array on success.

Exceptions

ExceptionDescription
HomegearExceptionIt 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

NameTypeDescriptionExample
groupIdintThe ID of the group as returned by createGroup() or getGroups().
100

Return Value

Returns true if the group exists and false otherwise.

Exceptions

ExceptionDescription
HomegearExceptionReturned 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

ExceptionDescription
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());'
 

Homegear::setUserMetadata

Signatures

bool setUserMetadata($username, $metadata)

Description

This method adds arbitrary metadata to an existing user in Homegear.

Parameters

NameTypeDescriptionExample
usernamestringThe name of the user
will
metadatastructThe metadata to store

Return Value

Returns "true" on success

Errors

CodeDescription
falseSomething has gone wrong (e. g. the user does not exist)

Exceptions

ExceptionDescription
HomegearExceptionIt 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

NameTypeDescriptionExample
usernamestringThe 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

NameTypeDescriptionExample
groupIdintThe ID of the group as returned by createGroup() or getGroups().
100
translationsstructThe 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
  }
}
aclstructThe 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

ExceptionDescription
HomegearExceptionReturned 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

NameTypeDescriptionExample
usernamestringThe name of the user
will
passwordstringThe new password of the user
new_secret
groupsarrayAn array of group IDs the user should belong to
array(1, 7)

Return Value

Returns "true" on success

Errors

CodeDescription
falseSomething has gone wrong (e. g. the user does not exist)

Exceptions

ExceptionDescription
HomegearExceptionIt 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

NameTypeDescriptionExample
usernamestringThe name of the user to be checked
will

Return Value

It returns "true" if the user exists and "false" if not.

Exceptions

ExceptionDescription
HomegearExceptionReturned if parameters are invalid

Example

/**
 * Execute this command in your terminal
 */
homegear -e rc 'var_dump($hg->userExists("homegear"));'