Introduction
PowerHome is an extremely powerful and flexible Windows based software package that will give you full control over your home's lighting, appliances, infrared devices, and security when used in conjunction with the appropriate control hardware.
With PowerHome's programmable interface, this control can be achieved via keyboard, mouse, web, Email, Insteon, UPB, X10, Z-Wave, MQTT, IOT, IR, Voice recognition, Socket communications, Windows Messaging, and even your internet enabled cell phone.
This user's manual is for version 2.2 of PowerHome. If this is your first time using PowerHome, Please take the time to familiarize yourself with the PowerHome Basics and PowerHome Explorer sections.


Features
  • Fully programmable interface via your choice of languages. You can use the internal Macro and formula scripting or any language supported by Windows Script Host (for example: VBScript, JScript, etc.)
  • Internal Web server for remote control and monitoring. Supports user defined dynamic content via PSP (PowerHome Server Pages)
  • Voice Recognition
  • Text to Speech
  • Ability to create your own custom "Control Center" screens
  • Touchscreen friendly interface
  • Customizable display allows you to show floorplan layouts and place controls over actual photos
  • Insteon control using either the PLC or the PLM (USB/Serial/Network/Insteon Hub). Full support for Insteon and I2CS including software link discovery and building as well as KeypadLinc support
  • UPB control using serial or USB PIMs (the Simply Automated USB PIM is not compatible since it doesnt create a virtual serial port). Complete support for UPB devices and links
  • ZWave support using a Razberry ZWave controller (the Razberry is a small daughtercard that is plugged into a Raspberry Pi)
  • X10 control via CM11A, CM17A firecracker, MR26A Mouse Remote, CPU-XA/Ocelot, W800, W800RF32, PowerLinc RS-232, PowerLinc USB, CM15A, Elk M1 Gold
  • Infrared control via CIR, Multi-CIR, RedRat2, RedRat3, CPU-XA/Ocelot, USB-UIRT, Global Cache, Slink-e
  • Digital Input, Digital Output, and Analog Input control with the CPU-XA/Ocelot and additional Adicon modules, Elk M1 Gold
  • 1-wire support using serial, USB, or parallel port controllers compatible with Maxim 1-wire drivers
  • Full DI/DO and AI/AO support for the Velleman K8000 controller
  • MQTT support both as a Controller and a Plugin
  • Support for Philips Hue devices through a Hue Bridge
  • Support for IOT devices: Wemo, TP-Link, and Tuya controllers. Also support for cloud based IOT site www.thingspeak.com
  • PowerHome allows you to use a virtually unlimited number of controllers. Use multiple X10, IR, and other controllers. Don't limit yourself to a single controller.
  • CD jukebox player control with playlists and autoprogramming
  • CD database with freedb support
  • Video database
  • Macros
  • Triggers
  • Timed Events
  • Full event and Web logging
  • Multi-X control allows a sequence of X10 commands for control (access 256 macros from your palm pad by pressing 2 buttons, 64 macros from your keychain remote by pressing 3 buttons.)
  • Sunrise, Sunset, and Civil Twilight calculations
  • Socket Server for remote control of PowerHome from other applications and machines
  • Windows Messaging Interface for additional remote control capabilities
  • Windows Script Host Interface
  • Plugin framework to extend PowerHome functionality using third party plugins or write your own


Technical Overview
  • PowerHome Home Automation Software is Written in Appeon PowerBuilder version 17.0
  • All code and data maintained in SAP/Sybase SQL Anywhere 11 Database system.
  • Custom DLL's written in C#.net, C++, C, Assembly, VB.net, and VB6.
  • Voice Recognition and Text to Speech components licensed from Microsoft (SAPI 4.0a and SAPI5).
  • Socket, HTTP, SMTP, and other internet protocol controls licensed from Catalyst.


System Requirements
  • Windows NT/2000/XP/Vista/7/8/10
  • Celeron equivalent with minimum 2GB of RAM
  • Unused Serial port/s (CM11A interface, CM17A firecracker, MR26A Mouse remote, RedRat2, CPU-XA/Ocelot, Slink-e, W800, W800RF32, PowerLinc RS-232, PowerLinc V2 Serial, Elk M1 Gold)
  • Unused Parallel port/s (Velleman K8000)
  • Unused USB port (RedRat3, USB-UIRT, PowerLinc USB, PowerLinc V2 USB)
  • Sound card (Text to Speech and Voice Recognition)
  • Ethernet connection (for remote Web Access and freedb support, Elk M1 Gold, Global Cache, Insteon Hub, ZWave Razberry, Wemo, TP-Link, Tuya, IOT)


Getting Started
Once you have successfully installed PowerHome, the first time you launch PowerHome you will be asked to enter a registration name. This name must be between 5 and 50 characters and will be used to generate your registration number. This registration number can be found under the menu Help->About. After the registration name has been entered, PowerHome will now be running. The first thing you should do is configure the system for your interface devices and personal preferences.
Most configuration and maintenance is done through a single screen called the PowerHome Explorer. Advanced Insteon configuration and maintenance must be done using the Insteon Explorer (explained further below) and Zwave configuration is done using the Zwave Explorer. You can access the PowerHome Explorer screen from the menu Maintenance->PowerHome Explorer or by clicking the magnifying glass icon in the main toolbar.
This screen functions similar to the Windows Explorer. The left pane will show your configurable options in a treeview and allows for easy navigation. The right pane displays the currently selected option and is where changes will be entered. Single-clicking items in the left pane will expand any available sub-items as well as bringing up the appropriate maintenance screen in the right pane. Right-clicking in the left pane will shrink the treeview and maximize your maintenance area in the right pane. Once minimized, you can right click again and restore the treeview to its standard size. Double-clicking in the left pane will have no effect. Single-clicking in the right pane will allow you to change focus between individual fields. Right-clicking will bring up a pop-up menu if available for the current screen. Double-clicking certain fields in the right-hand pane may open up additional configuration windows. Depending upon the screen, the rows in the right-hand pane may have sub-items. You can change to a sub-item screen by clicking on the button to the left of each row. When the PowerHome Explorer window is closed, any changes will be automatically saved.
Any changes made to the Setup area of PowerHome Explorer will not take effect until PowerHome is restarted or reinitialized. You must restart or reinitialize PowerHome if you make changes to the Setup area in order for these changes to be recognized.


Whats New version 2.2

Whats New PowerHome version 2.2
New Controllers:
  • Razberry ZWave
  • Insteon Hub
  • Milite Lights
  • ThingSpeak IOT
  • Wemo
  • ThingSpeak PH IOT server
  • Generic Serial (Arduino)
  • MQTT
  • TP-Link
  • Philips Hue
  • Tuya
Other Enhancements:
  • New ZWave Explorer window for management of ZWave devices
  • New webserver options (Catalyst socket, Catalyst Internet server, C# Internet Server)
  • C# regular expressions
  • Web based Device Status is now AJAX driven and updates in background
  • Web based Control Center now has a new "refresh" parameter which will use a background AJAX query to automatically reload the page if changes are detected
  • Support for Insteon FanLinc
  • User defined "Range of Values" for Analog IO and IOT device types
  • All timers now controlled by central timing object running in own thread
  • New tracing functions, stack trace, and debug functions
  • JSON, XML, and YAML functions
  • Natural language processing function
  • Proportional, Integral, Derivative (PID) control functions
  • New internal system variables available for Analog IO and Zwave calc formulas
  • New internal system variables available for all formulas
  • Database where used functionality rewritten to use dynamically created SQL
  • PowerHome Startup routines rewritten for greater stability
  • Data Retrieval Areas increased from 5 to 20. New functions added for enhanced functionality of Data Retrieval Areas
  • New color calculation and conversion functions
  • Many new function overloads for enhanced functionality
  • New PHSerial COM port control
  • FireTV control plugin via ADB
  • Fake SMTP Server plugin
  • MQTT plugin
  • Alexa (fake Wemo) plugin
  • Many new options for ph_geturl, ph_posturl, and ph_saveurl
  • New options to bring PowerHome data directly into Excel
  • Global Cache controller rewritten for better reliability and compatibility with iTach controllers
  • Expanded Custom Colors with more user defined colors and more default system colors
  • Enhanced functionality within the PowerHome Multi-Editor and Formula Editors including function tooltips and copy/paste in the results window
  • Enhanced logging capabilities including system variable values for macros, triggers, and formulas
  • Updated a number of functions and underlying code to use routines written in C# for increased speed
  • Can now fire a trigger on Critical Error
  • Added support for new Elk M1 commands. Fixed checksum routine error that caused some commands to not work


New Functions

PowerHome Formula Functions added in version 2.2
  • b2d
  • d2b
  • h2s
  • ph_colorcalc
  • ph_dbwhereused
  • ph_debuginfo
  • ph_deletedata
  • ph_exportdata
  • ph_extractval
  • ph_filterdata
  • ph_flattenjson
  • ph_flattenxml
  • ph_fromunixtime
  • ph_getsha1hash
  • ph_getsha256hash
  • ph_gettimezoneinfo
  • ph_getzwavecalcval
  • ph_getzwavedata
  • ph_getzwavedataraw
  • ph_getzwavedt
  • ph_getzwaverawval
  • ph_getzwaverawvalrt
  • ph_highestcontrast
  • ph_httprequest
  • ph_huerawcmd
  • ph_huergbtoxy
  • ph_huexytorgb
  • ph_importdata
  • ph_insertdata
  • ph_isnull
  • ph_isvalidip
  • ph_jsontoxml
  • ph_jsontoyaml
  • ph_latlongcalclat
  • ph_latlongcalclong
  • ph_latlongendbearing
  • ph_latlongmidlat
  • ph_latlongmidlong
  • ph_latlongstartbearing
  • ph_ldapquery
  • ph_luminance
  • ph_mqttpub (General)
  • ph_mqttpub (MQTT table)
  • ph_mqttsub
  • ph_mqttunsub
  • ph_n2b
  • ph_natlang
  • ph_pid
  • ph_pidclear
  • ph_processfromhandle
  • ph_regexsnap3
  • ph_replaceallregex3
  • ph_replaceregex3
  • ph_returnallvars
  • ph_rgb2milight
  • ph_run1
  • ph_runavg
  • ph_sendsmtpemailfile1
  • ph_setanalogoutraw
  • ph_setdata
  • ph_setzwavedisplay
  • ph_sortdata
  • ph_stacktrace
  • ph_texttojson
  • ph_tounixtime
  • ph_tracemsg
  • ph_traceoff
  • ph_traceon
  • ph_updatexml
  • ph_usererrmsg
  • ph_webdschg
  • ph_xmltojson
  • ph_yamltojson
  • ph_zwaveget
  • ph_zwavegetconfig
  • ph_zwaverawset
  • ph_zwaveset
  • ph_zwavesetcalc
  • ph_zwavesetconfig
  • s2h


Changed Functions

PowerHome Formula Functions changed in version 2.2
  • ph_base64decode
  • ph_base64encode
  • ph_ctlrcmd
  • ph_ctlrsq
  • ph_deletetimedevent
  • ph_disabletrigger
  • ph_enabletrigger
  • ph_extendmacrowait
  • ph_getanalogcalcstat
  • ph_getanalogstat
  • ph_getccobjbcolor
  • ph_getccobjborder
  • ph_getccobjfcolor
  • ph_getccobjgraphic
  • ph_getccobjheight
  • ph_getccobjtext
  • ph_getccobjwidth
  • ph_getccobjx
  • ph_getccobjy
  • ph_getmd5hash
  • ph_getsqlrows
  • ph_getteactive
  • ph_gettetime
  • ph_geturl1
  • ph_geturlviaproxy1
  • ph_getversion
  • ph_getwebparm
  • ph_ismacrowaiting
  • ph_killmacrowait
  • ph_modifytimedevent
  • ph_postexequeue
  • ph_posturl1
  • ph_posturlviaproxy1
  • ph_readfile
  • ph_saveurl1
  • ph_saveurlviaproxy1
  • ph_sendudp
  • ph_setanalogdisplay
  • ph_setanalogvalue
  • ph_setccobj
  • ph_setccobjbcolor
  • ph_setccobjborder
  • ph_setccobjfcolor
  • ph_setccobjgraphic
  • ph_setccobjheight
  • ph_setccobjtext
  • ph_setccobjwidth
  • ph_setccobjx
  • ph_setccobjy
  • ph_snapxml
  • ph_webml
  • ph_writefile


Deprecated Functions

PowerHome Formula Functions deprecated in version 2.2
  • ph_base64decode1
  • ph_getmd5hash1
  • ph_getmultistate
  • ph_getotheranalog
  • ph_getothercounter
  • ph_getotherdigital
  • ph_getothermultistate
  • ph_getothertimer
  • ph_getothervar
  • ph_setotheranalogout
  • ph_setothercounter
  • ph_setotherdigitalout
  • ph_setothertimer
  • ph_setothervar


ph_base64decode1

ph_base64decode1 PowerHome formula function (Deprecated)
Description
Decodes a base64 string returning the output as a string of decimal ASCII codes.
Syntax
ph_base64decode1 ( input )
Argument | Description
input | Base64 string to decode.
Return value
String. Returns the decoded base64 input as a concatenated list of ASCII values.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_base64decode1("VEVTVA== ") This call will return the string "084069083084". The actual ASCII characters (084 069 083 084) equate to the string of "TEST"


ph_getmd5hash1

ph_getmd5hash1 PowerHome formula (Deprecated) function
Description
Returns the standard MD5 hash for the specified string of data.
Syntax
ph_getmd5hash1 ( data, type )
Argument | Description
data | String. The data you'd like the MD5 calculated for.
type | Integer. Specifies how the data in the data parameter is to be interpreted for calculating MD5. See usage below.
Return value
String. Returns the MD5 hash as a string of hex digits.
Usage
Use this function to calculate general MD5 hashes including hashes for binary data.

Below is the list of valid values for the type parameter:
1 | Takes the value in the data parameter and interprets is as full unicode data.
2 | The value in the data parameter is interpreted as hexadecimal representations of binary characters.
3 | The value in the data parameter should point to a full path and filename of a file that will be read in and the MD5 calculated for it.
Any other value | Any other value for the type parameter will interpret the value in the data parameter as ANSI data.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_getmd5hash1("2020200D0A",2)
This example interprets the data parameter as a string of hex characters with every 2 characters representing a byte of data. Hex 20 is a space char, 0D is carriage return, and 0A is line feed. This example will return the following MD5 hash: 0C544100BE9EEE1C4FA2BACA5B51E3B2


ph_getmultistate

ph_getmultistate PowerHome formula function (Deprecated)
Description
Retrieves the value of a Multi-state input point defined in the Analog I/O screen.
Syntax
ph_getmultistate ( id )
Argument | Description
id | The ID of the multi-state input as defined within the Analog I/O screen.
Return value
Long. Returns the value associated with ID of the specified multi-state input. Returns - 100 if the ID cannot be found. When this function is executed, the controller, unit, and point is looked up within the Analog I/O table and these values are then passed to the controller. If these values are entered improperly in the Analog I/O screen, then the following errors may be returned: - 1 is returned if the controller is not available, - 3 is returned if the unit is out of range, - 4 is returned if the point is out of range.
Usage
Use this function to return the raw state of Elk multi-state inputs (0, 1, 2, or 3). Elk multi-state inputs are defined within the Analog I/O screen as "Elk Input". The multi-state input functions go direct to the controller to access the value stored there. Use the ph_getanalog and ph_getotheranalog functions to get the data stored within the PowerHome database for multi-state inputs.


ph_getotheranalog

ph_getotheranalog PowerHome formula function (Deprecated)
Description
Retrieves an Analog Input value.
Syntax
ph_getotheranalog ( controller, type, unit, point )
Argument | Description
controller | The ID of the controller.
type | The type of Analog point. Use 0 for inputs, 1 for outputs, 2 for Multi-State, 3 for Temperature, 4 for Arm Status, and 5 for Alarm State.
unit | The unit number.
point | The point you wish to get the analog value of.
Return value
Long. Returns the value of the analog input point you requested. -1 is returned if the controller is not available, -2 is returned if analog input is not supported by the controller, -3 is returned if the unit is out of range, -4 is returned if the point is out of range.
Usage
Currently only supported by the CPU-XA/Ocelot controller with either a SECU-16 or SECU-16I interface, the Velleman K8000 controller, and the Elk M1 Gold.

To use this function with the CPU-XA/Ocelot, specify the ID of the controller whose type is CPU-XA/Ocelot. The "unit" must be a number from 1 to 128 corresponding with the address of the SECU-16 or SECU-16I whose analog input you wish to retrieve. The "point" must be a number from 0 to 15 and corresponds to the specific point on the addressed SECU-16 or SECU-16I.

To use this function with the Velleman K8000, specify the ID of the controller whose type is K8000. To access the 6 bit analog outputs set the "unit" to 0 and use "point" values from 1 to 32. To access the 8 bit analog outputs set the "unit" to 1 and use "point" values from 1 to 4. To access the analog inputs set the "unit" to 2 and use "point" values from 1 to 64.

For use with the Elk M1 Gold, specify the ID of the Elk M1 controller. For the "Unit" and "Point" properties, the Elk M1 Gold supports two different numbering schemes. You can set the "unit" value to 0 and then set the "Point" value to the Elk logical point value. You can also set the "Unit" to the address of any external modules (use 0 for the on-board points) and the "Point" to the actual point value on the external board.


ph_getothercounter

ph_getothercounter PowerHome formula function (Deprecated)
Description
This function returns the value associated with a counter object within a controller
Syntax
ph_getothercounter ( ctlr, counter )
Argument | Description
ctlr | String. The ID of the controller whose counter you want to retrieve.
counter | Integer. The number of the counter within the specified controller that you wish to retrieve.
Return value
Long. Returns the requested counter value from the controller.
Usage
This function is currently only supported by the Elk M1 Gold controller. Counter numbers can be from 1 to 64. This function will cause the controller to retrieve the actual value from the controller vs retrieving a value from PowerHome memory.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_getothercounter("ELK",5)


ph_getotherdigital

ph_getotherdigital PowerHome formula function (Deprecated)
Description
Retrieves a Digital Input/Output value.
Syntax
ph_getotherdigital ( controller, type, unit, point )
Argument | Description
controller | The ID of the controller.
type | The type of the digitial point. Use 0 for Inputs, 1 for Outputs.
unit | The unit number.
point | The point you wish to get the digital value of.
Return value
Long. Returns the value of the digital input/output point you requested. A 0 means the input is off, a 1 means the input is on. -1 is returned if the controller is not available, -2 is returned if digital input/output is not supported by the controller, -3 is returned if the unit is out of range, -4 is returned if the point is out of range.
Usage
Currently only supported by the CPU-XA/Ocelot (with SECU-16, SECU-16I, or RLY-8 interface), the Velleman K8000 controller, and the Elk M1 Gold.

To use this function with the CPU-XA/Ocelot, specify the ID of the controller whose type is CPU-XA/Ocelot. The "unit" must be a number from 1 to 128 corresponding with the address of the SECU-16, SECU-16I, or RLY-8 whose digital I/O you wish to retrieve. The "point" must be a number from 0 to 15 and corresponds to the specific point on the addressed SECU-16, SECU-16I, or RLY-8.

To use this function with the Velleman K8000, specify the ID of the controller whose type is K8000. The "unit" value must be 0. The "point" value must be a number from 1 to 64 and corresponds to the specific point whose digital I/O you wish to retrieve the status of.

For use with the Elk M1 Gold, specify the ID of the Elk M1 controller. For the "Unit" and "Point" properties, the Elk M1 Gold supports two different numbering schemes. You can set the "unit" value to 0 and then set the "Point" value to the Elk logical point value. You can also set the "Unit" to the address of any external modules (use 0 for the on-board points) and the "Point" to the actual point value on the external board.


ph_getothermultistate

ph_getothermultistate PowerHome formula function (Deprecated)
Description
Retrieves the value of a Multi-state input point defined in the Analog I/O screen.
Syntax
ph_getothermultistate ( id, unit, point )
Argument | Description
id | The ID of the controller whiose multi-state input you wish to have returned.
unit | The Unit of multi-state input.
point | The Point of the multi-state input.
Return value
Long. Returns the value associated with the specified multi-state input. Returns - 1 if the specified ontroller ID cannot be found. - 3 is returned if the unit is out of range, - 4 is returned if the point is out of range.
Usage
Use this function to return the raw state of Elk multi-state inputs (0, 1, 2, or 3). Elk multi-state inputs are defined within the Analog I/O screen as "Elk Input". This function is similar to the ph_getmultistate function except that the multi-state input does not have to be defined within the Analog I/O screen. The multi-state input functions go direct to the controller to access the value stored there. Use the ph_getanalog and ph_getotheranalog functions to get the data stored within the PowerHome database for multi-state inputs.


ph_getothertimer

ph_getothertimer PowerHome formula function (Deprecated)
Description
Retrieves an internal timer value from a controller.
Syntax
ph_getothertimer ( controller, timer )
Argument | Description
controller | The ID of the controller.
timer | The number of the timer whose value you wish to retrieve.
Return value
Long. Returns the value of the timer you requested. -1 is returned if the controller is not available, -2 is returned if the controller does not support timers, -3 is returned if the timer is out of range.
Usage
Currently only supported by the CPU-XA/Ocelot controller. To use this function with the CPU-XA/Ocelot, specify the ID of the controller whose type is CPU-XA/Ocelot. The "timer" must be a number from 0 to 63 corresponding to the internal timer of the CPU-XA/Ocelot you wish to retrieve. Values will be in the range of 0 to 65535 for the CPU-XA/Ocelot.


ph_getothervar

ph_getothervar PowerHome formula function (Deprecated)
Description
Retrieves an internal variable value from a controller.
Syntax
ph_getothervar ( controller, var )
Argument | Description
controller | The ID of the controller.
var | The number of the internal variable whose value you wish to retrieve.
Return value
Long. Returns the value of the internal variable you requested. -1 is returned if the controller is not available, -2 is returned if the controller does not support internal variables, -3 is returned if the variable is out of range.
Usage
Currently only supported by the CPU-XA/Ocelot controller. To use this function with the CPU-XA/Ocelot, specify the ID of the controller whose type is CPU-XA/Ocelot. The "var" must be a number from 0 to 127 corresponding to the internal variable of the CPU-XA/Ocelot you wish to retrieve. Values will be in the range of 0 to 65535 for the CPU-XA/Ocelot.


ph_setotheranalogout

ph_setotheranalogout PowerHome formula function (Deprecated)
Description
Sets the value of an Analog Output
Syntax
ph_setotheranalogout ( controller, type, unit, point, value )
Argument | Description
controller | The ID of the controller.
type | The type of the Analog Point. Use 0 for inputs, 1 for outputs, 2 for Multi-State, 3 for Temperature, 4 for Arm Status, and 5 for Alarm State.
unit | The address of the unit.
point | The analog output point you wish to set the value of.
value | The value you wish to write to the analog output.
Return value
Integer. Returns a 0 if successful. - 1 is returned if the controller is not available, - 2 is returned if the controller does not support analog outputs, - 3 is returned if the unit is out of range, - 4 is returned if the point is out of range.
Usage
Currently only supported by the Velleman K8000 controller. To use this function with the Velleman K8000, specify the controller ID whose type is K8000. To set the output of the 6 bit analog outputs, specify a "unit" value of 0. The valid "point" values for the 6 bit AO's will be from 1 to 32. To set the Velleman precision analog outputs (8 bit AO), use a "unit" value of 1. The valid "point" values for the precision AO's will be from 1 to 4.


ph_setothercounter

ph_setothercounter PowerHome formula (Deprecated) function
Description
This function will set a specific value to a counter object within a controller
Syntax
ph_setothercounter ( ctlr, counter, value )
Argument | Description
ctlr | String. The ID of the controller whose counter you want to set.
counter | Integer. The number of the counter within the specified controller that you wish to set.
value | Long. The actual value you'd like to set the counter to.
Return value
Integer. Returns the result of the counter set operation. A 0 would indicate success. Any other value would be a failure.
Usage
This function is currently only supported by the Elk M1 Gold controller. Counter numbers can be from 1 to 64. This function will cause the controller to set the specified counter to the specified value.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_setothercounter("ELK",5,0)


ph_setotherdigitalout

ph_setotherdigitalout PowerHome formula function (Deprecated)
Description
Sets or clears a Digital Output
Syntax
ph_setotherdigitalout ( controller, type, unit, point, status )
Argument | Description
controller | The ID of the controller.
type | The type of the Digital point. Use 0 for Input and 1 for Output.
unit | The address of the unit.
point | The digital output point you wish to set or clear.
status | The status you wish to set. 1 will turn the relay on, 0 will turn the relay off
Return value
Integer. Returns a 0 if successful. - 1 is returned if the controller is not available, - 2 is returned if the controller does not support digital outputs, - 3 is returned if the unit is out of range, - 4 is returned if the point is out of range.
Usage
Currently only supported by the CPU-XA/Ocelot (with SECU-16, SECU-16I, or RLY-8 interface), the Velleman K8000 controller, and the Elk M1 Gold.

To use this function with the CPU-XA/Ocelot, specify the ID of the controller whose type is CPU-XA/Ocelot. The "unit" must be a number from 1 to 128 corresponding with the address of the SECU-16, SECU-16I, or RLY-8 whose digital output you wish to control. The "point" must be a number from 0 to 15 and corresponds to the specific point on the addressed SECU-16, SECU-16I, or RLY-8.

To use this function with the Velleman K8000, specify the ID of the controller whose type is K8000. The "unit" value must be 0. The "point" value must be a number from 1 to 64 and corresponds to the specific point whose digital output you wish to set or clear.

For use with the Elk M1 Gold, specify the ID of the Elk M1 controller. For the "Unit" and "Point" properties, the Elk M1 Gold supports two different numbering schemes. You can set the "unit" value to 0 and then set the "Point" value to the Elk logical point value. You can also set the "Unit" to the address of any external modules (use 0 for the on-board points) and the "Point" to the actual point value on the external board.


ph_setothertimer

ph_setothertimer PowerHome formula function (Deprecated)
Description
Sets an internal timer on the specified controller.
Syntax
ph_setothertimer ( controller, timer, value )
Argument | Description
controller | The ID of the controller.
timer | The number of the timer whose value you wish to set.
value | The value you wish to set the timer to.
Return value
Integer. Returns a 0 if successful. - 1 is returned if the controller is not available, - 2 is returned if the controller does not support timers, - 3 is returned if the timer is out of range, - 4 is returned if the value is out of range.
Usage
Currently only supported by the CPU-XA/Ocelot controller. To use this function with the CPU-XA/Ocelot, specify the ID of the controller whose type is CPU-XA/Ocelot. The "timer" must be a number from 0 to 63 corresponding to the internal timer of the CPU-XA/Ocelot you wish to set. The "Value" must be in the range of 0 to 65535 for the CPU-XA/Ocelot.


ph_setothervar

ph_setothervar PowerHome formula function (Deprecated)
Description
Sets the value of an internal variable on the specified controller.
Syntax
ph_setothervar ( controller, var, value )
Argument | Description
controller | The ID of the controller.
var | The number of the internal variable whose value you wish to set.
value | The value you wish to set the internal variable to.
Return value
Integer. Returns 0 if successful. - 1 is returned if the controller is not available, - 2 is returned if the controller does not support internal variables, - 3 is returned if the variable is out of range, - 4 is returned if the value is out of range.
Usage
Currently only supported by the CPU-XA/Ocelot controller. To use this function with the CPU-XA/Ocelot, specify the ID of the controller whose type is CPU-XA/Ocelot. The "var" must be a number from 0 to 127 corresponding to the internal variable of the CPU-XA/Ocelot you wish to set. The "value" must be in the range of 0 to 65535 for the CPU-XA/Ocelot.


PowerHome Basics
PowerHome is structured around a relational database management system. The database engine that is used is SAP/Sybase SQL Anywhere 11. This is a SQL based database that is accessible via ODBC from a number of programs including Microsoft Access and Excel. Advanced users who are knowledgeable with ODBC and SQL can make use of this feature to directly update the underlying PowerHome database structures. This is not required though as all database maintenance is fully supported from within PowerHome.
PowerHome is made up of multiple core sections. Understanding these core sections and how they interact with one another is essential to achieving maximum functionality from the PowerHome program. Each of these core sections are discussed in detail below:
  • ID's
  • Global Variables
  • System Variables
  • Macros
  • Formulas
  • Send Keys
  • Timed Events
  • Triggers
  • Windows Script Host
  • Execution Queue


ID's
Nearly every entity within the PowerHome database is identified by an element called an ID. The ID will usually be the leftmost column in most maintenance screens and is a required field. ID's must be unique within their particular maintenance screen and must consist of only letters, numbers, underscore, and the space character. ID's will be all uppercase and must be 25 characters or less. Within these restrictions, ID's can be anything you want but we recommend ID's be short but descriptive since ID's will be used throughout the PowerHome system. Most entities that require ID's will also have a Description field where you may type in a more verbose description of the entity.
Key takeaways:
  • ID's must be unique within a maintenance screen. It is ok to have a macro with an ID of TEST and a trigger with an ID of TEST
  • ID's must consist of only letters, numbers, underscores, and space characters
  • ID's are automatically uppercase and must be from 1 to 25 characters in length
  • Recommend that ID's be short but descriptive


Global Variables
Global variables are user defined storage areas. Users are able to declare a virtually unlimited number of global variables. Users define the global variable ID (up to 25 characters) and the content or value for the global variable (up to 1024 characters). Using variable substitution, Global variables can contain other global variables and can be "stacked" to achieve lengths greater than 1024. The content/value of a GV is stored in character format. This includes numeric data and date, time, or datetime data. If a global variable contains numeric data and is used in a numeric operation, its contents will be converted into the appropriate numeric value. The user does not need to concern themselves with this for the most part. Global variables are declared in the global variable section of the PowerHome Explorer. An initial value can also be assigned at this time. Global variables can have their contents changed from within macros and formulas. Global variable contents can be referenced from within formulas and macros where global variable substitution is performed. Global variables maintain their state even when PowerHome is shutdown as they are stored within the database.
Key takeaways:
  • A Global variable is a user defined storage object. Text, numbers, dates, times, etc. can be stored and dynamically read and updated
  • Global variables are stored within the PowerHome database and their value will persist between both PowerHome and machine restarts
  • All data (even numeric and date/time) are stored within a GV as a "string"


System Variables
System variables are system defined storage areas. They are different from global variables in that they are predefined and the user has no ability to create new ones or delete existing ones. System variables can be accessed similiarly to Global Variables. All system variables make their value available for reading and a large number of them can also be updated by the user. System variables are only stored within RAM and when PowerHome is shutdown they lose their values. The System Variables that are modifiable by the user have virtually no limit to the amount of data that may be stored within them (a little more than 4 gigabytes). Example system variables include X10 status, Sunrise, Sunset, local variables, temporary variables, and the Previous Incoming X10 buffer.
Key takeaways:
  • System variables are system defined. They can neither be created or deleted
  • System variables only exist within RAM. They are NOT stored in the database. Their values are lost and reset when PowerHome terminates
  • All System variables can have the values read. Some can have their values updated.
    • System variables that can be modified:
  • LOCAL1...LOCAL10 - General user defined storage with limited scope
  • TEMP1...TEMP10 - General user defined storage with limited scope but more scope than LOCAL vars
  • GLOBAL1...GLOBAL100 - General user defined storage available globally within PowerHome (not be confused with Global Variables)
  • INPUTRET - Stores the value to be passed back when an Input Box is closed
  • TIMEOUT - Stores the default timeout value for Message Box and Input Box commands
  • RAW - Stores the raw value of an Analog I/O device or Zwave device. Only has context within the Raw to Calc and Calc to Raw formulas
  • DATA - Same as the RAW System variable
  • CALC - Stores the calculated value of an Analog I/O device or Zwave device. Only has context within the Raw to Calc and Calc to Raw formulas
  • ORIGRAW - Stores the original raw value of an Analog I/O device or Zwave device before the value is updated by either PowerHome or the user.. Only has context within the Raw to Calc and Calc to Raw formulas
  • FORECOLOR - Stores the foreground color for an Analog I/O device or Zwave device. Only has context within the Raw to Calc and Calc to Raw formulas
  • BACKCOLOR - Stores the background color for an Analog I/O device or Zwave device. Only has context within the Raw to Calc and Calc to Raw formulas
  • EMAILNAME - A legacy SV and rarely used. Stores the email address to send email to using the PowerHome macro "Send Email" command
  • EMAILSUBJECT - A legacy SV and rarely used. Stores the email subject for the PowerHome macro "Send Email" command
  • DIALUPUSER - A legacy SV and rarely used. Stores the username for a dialup connection
  • DIALUPPASSWORD - A legacy SV and rarely used. Stores the password for a dialup connection
    • System variables that are Read Only:
  • SQLROWS1...SQLROWS20 - Contains the number of rows in a SQL Retrieval area
  • X10P1...X10P20 - Stores the most recent incoming X10 commands. X10P1 is the most recent and X10P20 is the oldest
  • X10P1TIME...X10P20TIME - Stores the time received of the matching incoming X10 command
  • SUNRISE - Stores the time that the sun rises for the current day and currently defined location
  • SUNSET - Stores the time that the sun will set for the current day and current location
  • DAWN - Stores the time for the start of civil twilight for the current day and current location
  • DUSK - Stores that time for the end of civil twilight for the current day and current location
  • MBRET - Stores the chosen value for the last displayed Message Box command.
  • PHDIR - Contains the filepath to the PowerHome directory
  • PHWEBDIR - Contains the filepath to the PowerHome Web directory
  • WINDIR - Contains the filepath to the Windows directory
  • SYS32DIR - Contains the filepath to the Windows System32 directory
  • MACRO - Contains the ID of the currently running macro. Only has context within formulas that are directly or indirectly executed from a macro
  • MACROLINE - Contains the current line of the currently running macro. Like the MACRO SV, only has context when accessed from within a macro
  • SUBMACROCNT - Contains the number of sub macro calls from the current macro. Only has context within a macro
  • PARENTMACRO - Contains the ID of the macro that called the current macro. Only has context within a macro
  • ROOTMACRO - Contains the top level root macro of the list of macros that called the current macro. Only has context within a macro
  • SUBMACROPATH - Contains the traversal path of sub macro calls. Only has context within a macro
  • TRIGGER - Contains the ID of the current trigger. Only has context within formulas that executed from a trigger
  • TIMEDEVENT - Contains the ID of the current Timed Event. Only has context within a formula executed from a timed event
  • FORMULA - Contains the ID of the current Formula. Only has context within a predefined formula
  • ANALOG - Contains the ID of the Analog I/O device. Only has context when accessed from the Raw to Calc and Calc to Raw formulas
  • ZWAVE - Contains the ID of the Zwave device. Only has context when accessed from the Raw to Calc and Calc to Raw formulas
  • CCTAB - Contains the ID of the Control Center tab from which a formula was initiated
  • CCBTN - Contains the ID of the Control Center object from which a formula was initiated
  • CCOBJ - Same as CCBTN
  • CCBTNX - Contains the X coordinate of a Control Center object that initiated a formula
  • CCOBJX - Same as CCBTNX
  • CCBTNY - Contains the Y coordinate of a Control Center object that initiated a formula
  • CCOBJY - Same as CCBTNY
  • X10STATA1...X10STATP16 - Stores the status for the specified X10 house and unit code
  • X10LEVELA1...X10LEVELP16 - Stores the level for the specified X10 house and unit code
  • DIALUPIP - A legacy SV that is typically no longer used. Stores the IP assigned to a dialup connection
  • SYSTEMRET - A legacy SV that is no longer used


Macros
Macros are the heart of the PowerHome program. It is here that most actions are defined and if-then logic is performed. Having well defined and thought out macros will enable you to maximize your use of the PowerHome Program. From within macros you can: control Insteon, UPB, and X10 devices, send infrared commands, call other macros, set global variables, set certain system variables, launch applications, switch to other applications, perform a Send Keys, initiate a dial-up connection, disconnect a dial-up connection, send Email, perform Text to Speech, create timed events, play a CD jukebox playlist, perform delays, trim the event log, get input, post a messagebox, perform direct SQL on the database, retrieve data from the database, clear the X10 history variables, and nearly any other function for automation control. The Formula language used within macros allows for sophisticated if-then-else logic and looping. Macros are defined within the Macro section of the PowerHome Explorer.
The available Macro commands are detailed below:
IR
This command allows you to send an infrared code that is already learned by the system. You will need to select the equipment and the infrared button.
X10 Raw
This command allows you send raw X10 commands via a connected X10 controller. You'll need to supply the Controller ID, the House code, and the Unit Code / Command. It will typically take 2 of these commands to perform any one X10 action (first selecting house/unit code and then sending a house/command). In the case of sending dim or bright commands, you will also need to input a formula which will evaluate to a number from 1 to 100 as the relative dim/bright percentage.
X10
The X10 command enables you to control X10 devices that have already been defined in the X10 Devices screen. Since the X10 device is predefined, you just need to select the X10 Device ID and the command you would like performed.
Macro
You can launch another macro from within this macro. When you do this, the current macros execution is either suspended and the new macro is executed or the new macro is posted to the execution queue to be executed sometime after the current macro completes. You will need to select the macro ID you would like to execute and whether or not to execute the macro immediately or have it posted. When you execute a macro using the "Macro" command, the new macro gets a copy of the current macro System variables with the [LOCAL?] variables blanked. Changes made to the System variables in the called macro will NOT be reflected in the original macro System variables when the called macro terminates. It should be noted that if a "Wait" command is executed from within a macro that is called using the "Macro" command, the macro that is waiting is effectively terminated meaning that control will be transferred back to the calling macro and execution will continue. If this is not the desired outcome and you want a called macro to Wait without control being returned to the calling macro, use the SubMacro command instead.
Set Global
You can set the value of a global variable. You will specify the ID of the global variable and a formula to be evaluated. The result of the formula will be assigned to the global variable. All values in global variables are stored in character format. More information on formulas can be found in the formula section.
Set System
You can set the value of certain system variables. You will specify the system variable and a formula whose result will be assigned to the system variable.
Launch App
You can launch another application on the computer. You will specify the full path and executable of the application to be launched as a formula. If the executable is known at design time and not determined dynamically, merely enclose the full path and executable name within single or double quotes.
Switch to App
You can switch to another currently running application and make it the foreground application. This is useful if you want PowerHome to send keystrokes to the application to control it. You will specify the type of application switching by selecting either Class Name or Window Name in the value field. Choosing Class Name means to use the class name of the running application for switching purposes. You would typically use this method on applications that do not have a constant window name such as Winamp. Winamp's window name will change based upon the current song playing, however the class name of an application will not change. To find the class name of an application you need to use a program such as spy. The class name for Winamp by the way is "Winamp v1.x" without the quotes and paying attention to the capitalization. For other applications whose window name remains the same (such as PowerHome), use Window Name for the value field. When you switch to an application from PowerHome and Send Keys to it, you will want to switch back to PowerHome when you are done. The window name for PowerHome is a single space followed by the word PowerHome followed by two spaces. The class name or window name must be entered as a formula within the Send Keys field.
Send Keys
You can simulate keystrokes with this command as if you were typing at the keyboard. Whatever is the current foreground application will receive the keystrokes. If you want to Send Keystrokes to an application other than PowerHome you must first launch it and switch to it. You also have the option to either have the keys sent immediately or be posted to the execution queue. If the Send Keys is posted to the execution queue, the entire formula is posted. After the Send Keys formula is serviced by the execution queue, the Send Keys formula will then be evaluated and the result sent to the Send Keys interpreter. It is important to note that the formula is NOT evaluated before going to the execution queue if you choose post. You will enter the Send Keys formula in the Send Keys field. An explanation of the valid Send Keys will be explained in the Send Keys section.
Dialup Connect
This command is obsolete in todays modern internet connected environment but can still be useful in legacy applications. With this command you can launch an already defined dialup connection. You must select either Continue or Wait in the value field. A value of Continue will launch the dialup connection in the background while the macro continues to run. A value of Wait will launch the dialup connection and force the macro to suspend execution until the connection is established. Enter a formula that evaluates to the exact name of the Dialup connection in the Send Keys field.
Disconnect Dialup
This command is the Disconnect command for a Dialup Connection is also obsolete but still available. This command enables you to disconnect a currently connected dialup session. You must select either Continue or Wait in the value field. A value of Continue will close the dialup connection in the background while the macro continues to run. A value of Wait will suspend execution of the macro until the dialup connection is disconnected.
Send Email
Allows for the sending of email through a default MAPI mail client. This command would not typically be used in todays environment as better alternatives exist for sending email such as using one of the ph_sendsmtpemail functions. In order to use this command you must first set the email system variables. This is accomplished by doing a Set System for [EMAILNAME] and a Set System for [EMAILSUBJECT]. Once these system variables are set, you can then do a Send Email. Remember, that system variables are reset everytime PowerHome starts so you will usually set these system variables every time just before you do the Send Email. With this command, you must enter a formula that evaluates to the text of the email message you would like to send in the Send Keys field. This can be as simple as the text that you would like sent surrounded by single or double quotes. This command uses standard MAPI mail calls. You must have a default MAPI mail client declared for this function to work. This will usually be your default mail client such as Microsoft Outlook. Check the options of your mail client and verify that you have a default MAPI client assigned.
Process Email
This command will use your default MAPI client to receive EMail. If you have enabled EMail control in the Setup area of the PowerHome Explorer, it will also process any EMail intended to control PowerHome. This command takes no arguments.
TTS
Allows you to send Text to Speech. If you have configured and enabled text to speech in the Setup section of PowerHome Explorer, you can have the PowerHome computer speak to you. You must enter a formula that evaluates to the message you would like to have spoken in the Send Keys field.
Create Timed Event
You can create timed events. The timed event will always have an action type of macro and will always have a frequency of one shot. Select the macro to be assigned to the timed event in the ID field and enter a formula that evaluates to the time the timed event will fire in the Send Keys field. This formula must evaluate to a valid timestamp in the form of yyyy-mm-dd hh:mm:ss or a number representing the number of minutes in the future from the current time. Since the time that this command was created, much more robust methods of creating Timed Events have become available via the ph_createtimedevent functions.
Jump
The jump command is a basic command that handles if-then-else type processing. Normally, a macro is executed starting at line 1 and every line is executed in order all the way to the last line. The jump command allows you change this normal execution order and jump to a different line within the current macro. The jump command expects a formula in the Send Keys field that evaluates to a positive or negative integer. If the formula evaluates to 2, the jump command will transfer execution down 2 lines, in effect skipping the line just below the jump command. A negative integer causes control to transfer above the jump line. If the formula does not return an integer, the jump will be ignored and control will transfer to the next line. This allows the user to create their own error handling by placing any error code on the line immediately after the jump. To exit the current macro immediately with no further processing, have the formula return a positive integer beyond the last line of the macro. The important thing to remember with the jump command is that the line jumped to is relative to the current jump line. You cannot jump to an absolute macro line. See the Label and Goto Label commands for additional flow control processing.
Playlist
This command is obsolete but still available. This command allows you to have a predefined playlist programmed into your CD jukebox. Select the playlist to be programmed in the ID field and either Normal or Randomize in the Value field. A value of Normal will cause the playlist to be programmed in the order of the playlist. A value of Randomize will first randomize the songs in the playlist and then send the infrared commands to the jukebox.
Clear X10 History
This command will clear the X10 history variable buffers. You can select whether to clear the Global Buffer, All Buffers, or a particular housecode buffer. When you clear a buffer, you can clear just the first entry which will place a string of five zeroes into the first multi-x entry or clear the entire buffer which will place zeros in the entire multi-x buffer. It will not blank out the times associated with these variables. Starting with version 1.00.1, PowerHome has expanded the global buffer to 20 entries and added a 20 entry buffer for each housecode. Version 1.01.1 has expanded the system variables to access all 20 of the global buffers commands and times. To access the housecode buffers, use the new functions ph_multix and ph_multixtime.
Delay
Delays macro execution for the specified number of milliseconds. Enter the number of milliseconds of delay you want as a formula in the Send Keys field. There are 1000 milliseconds in 1 second. For a delay of 2 seconds, enter 2000 in the Send Keys field. Delays should be used very sparingly as nothing else will execute while in a delay. If you want an effect such that a macro is launched when a motion sensor is triggered so that a light is turned on for 60 seconds and then back off, don't use a delay to achieve this. Instead, launch a macro to turn the light on and then either create a timed event for 60 seconds in the future to turn the light off or use the Wait command. This way other processing can continue while PowerHome is counting down to turn the light off.
Trim Event Log
This command is useful for keeping the event log a manageable size. Enter a formula resolving to the number of days you wish to keep in the log in the Send Keys field. A value of 1 in this field will erase all entries in the event and web log except for the entries dated from midnight forward of the current day. If you set this up to execute on a daily basis at 12:05 am and place a value of 2 in the Send Keys field, then you will only have entries for the previous day and all 5 minutes worth of the current day.
Direct SQL
This command should be used with GREAT CARE and only by those who are very familiar with SQL database programming. This command allows you to directly manipulate almost any table within the PowerHome database. Enter a formula that evaluates to a SQL statement (update, insert, delete) into the Send Keys field. The SQL statement is executed and any changes are commited immediately. There is NO chance of a rollback in case of errors.
Message Box
This command allows you to display information to someone who is monitoring the PowerHome program. You do not have to worry about using message boxes and hanging the system until you respond. A message box can optionally timeout by setting the [TIMEOUT] system variable to the number of seconds you wish the box to appear. If you set this value to zero, then the box will never timeout, however the system will still not be hung as the macro which launched the message box is terminated so other items in the execution queue will continue to be executed. Once the message box is closed, the macro that spawned the box will resume where it left off. Select whether or not you want the text displayed in the message box to also be sent to the Text to Speech engine. Select the buttons to appear on the message box in the value field. Next, enter a formula evaluating to the message you wish displayed (and optionally sent to TTS) in the Send Keys field. When the message box is acknowledged or times out, the system variable [MBRET] will contain the number of the button that was pressed or a zero in the case of a timeout. In the case of a button type of YESNOCANCEL, pressing the Yes button will place a 1 in the [MBRET] variable. Pressing No will return a 2, and pressing Cancel will return a 3 and a timeout will return a zero. The message box will have the window title the same as the macro ID.
Input Box
This command operates the same as the Message Box command in respect to time outs and the execution queue continuing to process events while a box is open. This box will obtain input from the user. You can enter a formula that evaluates to a brief message that will appear in the input box (and optionally sent to TTS) in the Send Keys field. Once the input box is opened, the user may enter up to 256 characters in the input field. Input is accepted and the box is closed once the user clicks OK. The user inputted text will then be available in the [INPUTRET] system variable. If any text is currently already in the [INPUTRET] variable when the input box is called, then this text will be pre-entered into the input field of the input box. Remember that system variables are reinitialized everytime PowerHome is started. If you want to have a default value in your input box, you should set the [INPUTRET] variable using the set system command prior to calling the input box command. The input box will have the window title the same as the macro ID.
Label
The label command works in conjunction with the Goto Label command and allows you to label sections of your macros with any name you want so that you can later transfer control to this label without having to use the jump function and count the number of lines between your jumps. You enter your label in the Send Keys field. This is not a formula and no substitution of any kind is performed. What you type is what you get for a label so you would NOT use single or double quotes for the label string. When a label command is encountered in normal macro processing, it is merely skipped.
Goto Label
The goto label command allows you to transfer control to a label within the current macro. This can be easier than keeping track of the number of lines between statements like you have to do when using the jump command. It should be noted however that the jump command is more efficient than the Goto Label command but the difference will be negligible. You enter a formula that evaluates to the label that you want to transfer control to in the Send Keys field. Since this field is a formula, you can use a case statement or similar to transfer control to multiple locations. Keep in mind if you have a line labeled abc, when you jump to it with a Goto Label command, you must use "abc" in quotes so that the formula in Goto Label is evaluated as a string. If the label is a number, then you don't have to place the number in quotes in the formula field of Goto Label. When a goto label command is encountered, execution continues at the line immediately following the matching label. If the label does not exist, control is just transferred to the line following the Goto Label command.
SQL Select
This command works in conjunction with the Destroy Select command and allows the user to directly query the PowerHome database on the fly. This command should only be used by individuals familiar with SQL programming and intimate with the structure of the PowerHome database. The PowerHome system includes 20 global database retrieval areas. You must select which of the 20 database retrieval areas your SQL Select command will retrieve to. If the database retrieval area is not initialized, it will automatically be created for you. If it already exists and has data, it will be overwritten with the new data. The database retrieval areas and its data utilize system memory and will persist until destroyed with a Destroy Select statement. There are 20 system variables associated with the database retrieval areas ([SQLROWS1] thru [SQLROWS20]) and contain the number of rows currently retrieved in the retrieval areas. There are also several formula functions (such as ph_getdata and ph_finddata) which allow you full manipulation of your retrieved data. When using this command you must select the data retrieval area number and then enter a formula that evaluates to a valid SQL select statement in the Send Keys field.
Destroy Select
This command is used to return memory to the system when you are done with the data in a data retrieval area that was previously retrieved with a SQL Select command. Enter the data retrieval area that you wish to have destroyed.
Wait
This command will suspend execution of the current macro but is different from the Delay command in that it will NOT stop the execution queue from processing waiting commands. The macro is actually terminated but the System Variables [LOCAL1] thru [LOCAL10], [TEMP1] thru [TEMP10], and others are stored and a timer started. When the timer is up, the macro is reinserted into the execution queue and will resume processing at the statement following the Wait command. Enter a formula that evaluates to the number of seconds you would like to wait in the Send Keys field. Remember that the Delay command works in milliseconds, the Wait command works in seconds.
User Message
This command will create a user message event within the event log if the logging of user messages is enabled within the PowerHome preferences. Enter a formula that evaluates to the text of the user message within the Send Keys Field.
Comment
This command allows you to add a comment to your macro. You may place the text of your comment within the Send Keys Field. This is not a formula and will not be evaluated. Comment commands are simply skipped during macro execution.
Formula
This command allows you to have a formula entered in the Send Keys field evaluated. The results of the formula are discarded. In this formula you can use any of the defined formula functions. The formula can either be evaluated immediately or posted to the end of the execution queue.
Slot
This command is obsolete and is a holdover from the time when PowerHome did not have formula functions. This command is used to control a CD jukebox player via Infrared commands and is intended to move the player to a particular CD slot. This command expects that the IR commands to control CD player have already been defined in the IR section of PowerHome Explorer and the CD screen in the Setup section of PowerHome Explorer has been configured. The ID column is set to the ID of the defined IR device. The Send Keys field should contain the "offset" to the number 0 in the IR device for controlling the CD changer. Before calling this command, you must first set [LOCAL1] to the slot number you wish to be sent to the CD player. This command is easily replaced by using a formula containing the ph_irnumseq( ) function.
Track
This command is obsolete and is a holdover from the time when PowerHome did not have formula functions. This command is used to control a CD jukebox player via Infrared commands and is intended to tell the player to load a particular CD track in the current slot. This command expects that the IR commands to control CD player have already been defined in the IR section of PowerHome Explorer and the CD screen in the Setup section of PowerHome Explorer has been configured. The ID column is set to the ID of the defined IR device. The Send Keys field should contain the "offset" to the number 0 in the IR device for controlling the CD changer. Before calling this command, you must first set [LOCAL1] to the track number you wish to be sent to the CD player. This command is easily replaced by using a formula containing the ph_irnumseq( ) function.
Start Playlist Loop
Another obsolete command related to the programming of Playlists into a CD jukebox changer. This command is used in conjunction with the Slot and Track commands to program a playlist defined in the Playlists section of PowerHome Explorer. Before calling this command, [LOCAL3] is expected to contain the ID of the Playlist to be programmed. When this command is first encountered, it queries the database for the Playlist ID in [LOCAL3] and loads the slot number for the first entry in [LOCAL1] and the track number in [LOCAL2]. Between the "Start Playlist Loop" command and the "End Playlist Loop" command is expected to be commands to "Slot" and "Track" to program the values in [LOCAL1] and [LOCAL2].
End Playlist Loop
This command is the second half of the "Start Playlist Loop" command is obsolete. When this command is encountered, control is sent back to the "Start Playlist Loop" command and the next entry in the Playlist is retrieved with the Slot and Track values loaded into [LOCAL1] and [LOCAL2]. The macro will loop until the complete Playlist is programmed or until the maximum songs in a playlist value is reached.
End Macro
This command allows you to prematurely end execution of the current macro and is useful for Jump and Goto Label commands to terminate a loop and the macro running it when user defined conditions are met. Equivalent to a Jump command to a line beyond the end of the macro.
SubMacro
This command allows you to execute another macro as an "extension" of the current macro. The entire System variable structure of the calling macro is available from within the SubMacro. Changes made to the System variables within the SubMacro will be reflected in the System variables of the calling macro. This is different from executing the "Macro" command where the new macro gets a copy of the current macro System variables minus the [LOCAL?] variables ([LOCAL1] thru [LOCAL10] are set to blank for the new macro). When the macro called by the "Macro" command terminates, control is transferred back to the calling macro which will have the same System variable values it had (including the [LOCAL?] values) before calling the new macro (changes made to System variables in the new macro will NOT be available to the calling macro). Unlike a macro executed using the "Macro" command, a "Wait" command will NOT cause control to be transferred back to the calling macro. For all intents and purposes, a SubMacro is treated as a part of the macro that is calling it.
Formula Button
This command allows you to execute a formula that has been predefined in the "Formulas" section of the PowerHome Explorer. All of the System variables in the current macro will be available to the formula called by this command. Select the ID of the predefined formula in the ID column.
Insteon
Allows you to control a predefined Insteon device that has been created on the "Devices" tab of the Insteon Explorer.
Insteon Group
Allows you to control a predefined Insteon group that has been declared in the "PLC/PLM Groups" tab of the Insteon Explorer.
Insteon Raw Group
This command allows you to control an Insteon group even if it hasnt been already defined in the Insteon Explorer. You'll enter the Insteon controller ID, the group number and the command you wish to be sent.
Device Control
This command allows you to execute a Device Control string. These strings provide an easy way to control a multitude of devices that have already been defined within PowerHome. Doubleclick the Send Keys column or right-click the Send Keys column and select "Device Control" to open a window that allows you build these strings.
Play Sound
Allows you playback a specified WAV file.
UPB
Allows you to control a predefined UPB device that has been declared in the UPB section under Devices in the PowerHome Explorer.
UPB Link
Allows you to control a predefined UPB link that has been declared in the UPB Links section under Devices in the PowerHome Explorer.


Formulas
Formulas are where most of your automation power is derived. Formulas are used throughout PowerHome and are an essential component of Macros, Triggers, Timed Events, Analog IO device, PSP (PowerHome Server Pages), and others. Formulas can return text, numeric, date, time, and datetime values. Before a formula is evaluated, variable substitution is performed upon it. Once variable substitution is complete, the formula is passed to the formula evaluator. The results of the formula are then passed back. Formulas themselves can contain a number of functions. You can achieve most PowerHome tasks by calling a series of formula functions. The available Formula Functions are documented within the Formulas section.
The key thing to remember with formulas is that it's basically a math equation. You can add, subtract, multiply, and divide numerics ( + - / * ). You can also add strings. Functions can return either numeric, string, date, time, or datetime values. You can use parenthesis to force a particular order of evaluation. Strings can be delimited by either single quotes or double quotes. If you need an embedded double quote, delimit your string with single quotes and vice versa. Within a formula, all operands must be of the same type. It is best to separate operators from operands/function with a space character. When using subtraction (the - sign), you MUST have a space precede the - sign or sometimes your formula can fail.
The simplest formula would be just the number one like this:
1
From there, you can do some simple math such as 1 + 1. Another formula is just a simple string. You can have:
"Test"
and then add strings together to get a combined string:
"This is" + char(32) + "a test"
The char() function returns a string so were adding 3 string operands.
A formula can also evaluate to a boolean (true/false) value so this is also a valid formula:
2 < 3
This will evaluate to true.
One thing you cant do is assignment (like you can in most programming languages). You must use either a function or a macro command to perform an assignment. If you have a global variable with an ID of TEST, you can't do this:
TEST = "This is" + char(32) + "a test"
To do the assignment, you would have to do this:
ph_setglobal_s("TEST","This is" + char(32) + "a test")
In addtion to the standard operators ( + - / * ) all of the standard comparison operators are also available: <, >, <= , >= , <>, etc.
When creating formulas, it is a good idea to always "check" them for proper functionality. If a formula has a syntax error, it will return the following string: "-=*SYNTAX ERROR*=-". It should be noted that a particular formula evaluation may result in a syntax error even though the function is syntactically correct. This often happens when using Variable Substitution. Consider the following formula:
[LOCAL1] * [LOCAL2]
If LOCAL1 and LOCAL2 do NOT contain numeric values, you will get a syntax error. If both LOCAL1 and LOCAL2 contain numbers, then you get a successful return. This is why it is recommended to instead use the ph_getvar_?( ) functions as these functions will ALWAYS return the correct datatype. Consider the equivalent formula below:
ph_getvar_n(1,1) * ph_getvar_n(1,2)
In the above formula, you will ALWAYS get a valid value returned no matter what data might actually be in the LOCAL1 and LOCAL2 variables.


Send Keys
Send Keys start out as a PowerHome formula. This formula may be as simple as a sequence of keystrokes to be sent to the current window surrounded by single or double quotes so that the formula will evaluate properly. After the formula goes through variable substitution and evaluation, the result is passed to the Send Keys interpreter. The interpreter will then parse the result and simulate keystrokes.
To simulate someone pressing the 'A' key, the Send Keys formula would be the letter 'a' in lower case surrounded by single or double quotes. This string would be passed to the variable substitution routine where it would return unchanged. Next the formula evaluator will evaluate the formula and return the lower case 'a' without the surrounding quotes. The Send Keys interpreter would then create a Windows message telling the currently active application that the 'a' key was pressed. If you wanted to simulate someone pressing the shift key and the 'A' key, the command would be the letter 'A' in upper case surrounded by single or double quotes. This is the technique used for sending the standard typeable letters, numbers and special characters. If a key sequence does not have a standard sequence such as the tab key, you would use the special character syntax of '{tab}'. The curly braces denote a special character sequence. To simulate an alt + tab key combination, the syntax is '{alt+tab}'. Notice there are no spaces in this sequence. Having a space in a Send Keys sequence will simulate the space key being pressed. Also note that all the letters are lower case. This is important. Upper case letters in a special character sequence are only used in certain situations. The + symbol is used to separate items in a special character sequence. To simulate a function key such as F1, the syntax is '{F1}'. Note that the F is capitalized. This is the only time capitalization should be used in a special character sequence. The special character sequences available for Send Keys are listed below:
{shift}
{ctrl}
{alt}
{backspace}
{tab}
{enter}
{pause}
{capslock}
{esc}
{pageup}
{pagedown}
{end}
{home}
{leftarrow}
{rightarrow}
{uparrow}
{downarrow}
{printscreen}
{insert}
{delete}
{multiply}
{plus}
{minus}
{point}
{divide}
{numlock}
{scrolllock}
To simulate the numbers on the numpad keys such as the 1 key, use the syntax '{numpad+1}'. In the above example where we wanted to simulate the shift and 'A' key being pressed, we merely had to enter a capital 'A'. We could also use the syntax '{shift+a}' to accomplish the same. If you want to simulate a key sequence such as the control key, the shift key and the 'A' key, your syntax would be either '{shift+ctrl+a}' or '{ctrl+shift+a}'. Remember, when building Send Keys formulas, do not separate special character sequences or groups of characters by spaces unless you want the space key to be pressed. To simulate a sequence of keys pressed one after the other, string the appropriate Send Keys syntax together one after another. Control A followed by the letter b followed by the enter key followed by the F1 key followed by an alt + tab sequence would be entered into a Send Keys formula as: '{ctrl+a}b{enter}{F1}{alt+tab}'. A '{}' sequence (curly braces with nothing in between) has no effect and is ignored.
Remember that all Send Keys are first a formula. You can achieve a dynamic Send Keys sequence by having this formula evaluate to a sequence of keystrokes that will then be passed to the Send Keys interpreter.
NOTE: Case is extremely important when working with Send Keys commands. If you are not careful concerning case, your Send Keys will not be interpreted properly.


Timed Events
Timed Events are simply actions that are solely based on the system clock. Timed Events are declared in the Timed Events section of the PowerHome Explorer. Timed Events can also be created from within macros and formulas. When a timed event is executed, its action is either a Macro, Send Keys, Raw Formula, or a Device Control string. Timed Events are based upon a timestamp (specific time and date) and can have either a recurring frequency (executes and automatically creates a copy of itself a specified interval in the future) or be a one shot (executes one time and then is destroyed).
When you view your Timed Events from the PowerHome Explorer, they will be sorted in the order they would be executed. To create a new timed event, right click on the detail area of the Timed Events section of PowerHome Explorer and press insert. You will have a new blank timed event row inserted where you clicked. Once you enter an ID, reference time, and the rest of the timed event parameters and save your changes, your timed event will be sorted according to when it will be executed. In your blank timed event, enter the date and time in 24 hour format that you wish to have your action performed in the "Reference Time" column. The "Start TIme" column is read only and reflects the actual time the Timed Event will execute based upon the Reference Time and the Timing, Offset, and Offset Amt fields. The "Frequency" column determines how often the Timed Event will be executed. The standard choices are One Shot, Hourly, Daily, and Weekly, but you can enter a number in this field that corresponds to the frequency in minutes. For example, if you enter a 5 in this field, the timed event will execute every 5 minutes. Enter a 0 if you want your timed event to execute only 1 time and then be deleted. This is equivalent to the One Shot option. Similarly, the Hourly option equates to 60, the Daily equates to 1440 and the Weekly equates to 10080.
In situations where you want an action performed at a certain time but based on other conditions being satisfied, you would still use a timed event. There are a couple of ways to handle the "other conditions". You could make the action a Macro and from within the macro determine if the other conditions are met before executing the rest of the action. A better way would be to use the "Boolean" column. This column contains a formula that must evaluate to either logical TRUE or FALSE or a numeric value with a value of 0 equating to logical FALSE and any other number equating to logical TRUE. If the Boolean formula is TRUE or a number other than 0, the Timed Event action is executed. If the Boolean formula is FALSE or 0, then the Timed Event action IS NOT executed and the Timed Event is updated to run at it's next Start Time based upon the frequency. You can use the Boolean formula to evaluate your other conditions to determine if the Timed Event should be executed. The default value for this column is the number 1 which means the Timed Event action will be executed.


Triggers
Triggers are based upon external actions. Triggers can be declared for a number of external events including the sending and receiving of Insteon, UPB, X10, and Infrared signals, by plugins, by Windows messages, incoming Socket connections, global variable changes, etc. Anytime you want to perform an action based upon some other action occurring, you'll probably want to define a trigger. Triggers also include a Boolean formula which is checked whenever a trigger fires. If the formula is true then the trigger's action is performed. Actions can be either a Macro, Send Keys, Raw formula, or a Device Control string. Triggers are declared from within the Triggers section of the PowerHome Explorer.


Windows Script Host

PowerHome includes the ability to execute Windows Scripts in any language for which you've installed the appropriate engine using the Windows Script Host components. WSH is not part of the PowerHome installation and will have to be downloaded directly from Microsoft and installed separately if your system does not already have them and you desire this capability. WSH will default install the engines for both VBScript and JScript. Additional engines are available on the web. In addition to having the full capabilities of the Script language at your disposal, PowerHome also extends this functionality with an OLE component containing functions that directly control and retrieve information from the PowerHome program. With this facility, you will no longer be confined to the functionality contained within the internal PowerHome macro and formula scripting.

WSH scripts are stored in normal text files on the PowerHome machine and are not a part of the PowerHome database. You can execute a script by calling one of the six formula functions ph_runscript_0 through ph_runscript_5. A script must consist of functions and/or subroutines. You can have multiple functions and/or subroutines in a single script file. Each of these functions or subroutines can call other functions or subroutines in the same script file. When you call one of the six runscript formula functions, you can begin execution at any function or procedure contained within the script file and pass parameters to the formula or procedure in the case of the ph_runscript_1 through ph_runscript_5 functions. See the appropriate section under formula functions for a detailed description on the runscript functions. Windows Script Host functions contains a list of the OLE functions available to WSH scripts for directly interfacing with PowerHome. They are almost exact duplicates of the "ph_" formula functions used within PowerHome.

PowerHome also includes a limited script editor. You can access this editor from the Maintenance menu. You can open, edit, and save scripts. You can also perform a syntax check and execute scripts from within this screen to check for runtime errors. More powerful editors are available and you can use any editing environment you are comfortable with.

For more information on WSH and scripting in general, please visit the Microsoft website.


Execution Queue

The execution queue is what makes things happen in PowerHome. When you press a button on the Control Center, or a menu hotkey to launch a macro, or when a trigger or timed event causes an action to be taken, the request is sent to the execution queue. PowerHome was specifically designed to take this myriad of tasks and force them all to be executed one at a time, in the order they were received. This process ensures that nothing happens out of order and keeps the system synchronized. Exceptions have been programmed in however to allow you to override the execution queue and execute an action immediately. This can be seen in the triggers and timed events screen where you have the Boolean field. When a trigger is checked or a Timed Event is fired, the formula in the Boolean field will be executed immediately, ahead of any actions currently in the Execution Queue. Use this functionality with great care so as not to cause problems within PowerHome. You should NEVER execute a function from the Boolean formula that interacts with a controller.

Normally, the execution queue is a first in, first out (FIFO) construct. You can override the FIFO behavior by using the ph_postexequeue( ) function. This function is safe to run from the Boolean field (Boolean formulas are never sent to the execution queue and are evaluated immediately). The execution queue has a couple of logical sections. The first being the priority queue and the other being the normal queue. Priority queue items are executed before any normal queue items. Using the ph_postexequeue( ) function you can place a Macro, Formula, Send Keys, or Device Control string at the very top of the queue (next item to be executed), to the bottom of the priority queue, or to the bottom of the normal queue.


PowerHome Explorer
The PowerHome Explorer is where most maintenance to the PowerHome system is performed. This single window allows you to jump section to section with ease and provides a standard interface similar to the Windows Explorer. The PowerHome Explorer can be launched from the toolbar or from the menu under Maintenance / PowerHome Explorer. The Explorer consists of two panes, a left pane which is a hierarchical treeview control that allows for easy navigation to all the PowerHome elements and a right pane where actual changes and maintenance is performed.
You can set the color scheme for the Explorer in the Explorers Setup -> Preferences section. The left hand pane supports single left-clicking and single right-clicking. By left-clicking on the text of a section, that section's maintenance screen will appear in the right hand pane and any children under the section will be expanded and visible. By left-clicking on a plus to the left of the section text, the section will be expanded showing its children without changing the maintenance screen in the right pane. Right-clicking anywhere within the left pane will minimize the left pane or restore it to its default size if already minimized. The Explorer also has a toolbar associated with its functions. Hovering the mouse over any of the toolbar buttons will reveal the tool tip associated with the button as well as the hotkey to directly fire the action. The far left button is the 'Back' button and can be activated by pressing the 'F2' key. The Explorer window maintains a history of each maintenance screen referenced. As you change from screen to screen, this history is built up. Pressing the 'Back' button will step you back through the Explorer's history to the previous screens. The next button is the 'Forward' button and can be activated by pressing the 'F3' key. You can only move forward after you have built some history and moved back with the 'Back' button. Toggling between the 'Back' and 'Forward' buttons will allow you to quickly move between maintenance screens. The next button is the 'Up' button and can also be referenced by pressing the 'F4' key. The 'Up' button may appear similar to the 'Back' button but instead of stepping through history, it will move you from a child to its parent. The next button is the 'Refresh' button and can also be referenced by pressing the 'F5' key. This key will save any changes to the maintenance screen immediately, refresh the left hand pane with any updated information, and re-retrieve all rows within the right hand pane. The button to the right of the 'Refresh' button is the 'Database button and can be referenced by pressing the 'F7' key. This button will allow you to open a different database other than the currently connected one such as the sample database. The next couple of buttons are the 'Undo' and 'Redo' buttons. If you have made changes to the right-hand pane of the Explorer and have not yet saved those changes to the database, you can undo individual changes by pressing the 'Undo' button or the 'Ctrl-Z' key combination. If you undo more changes than you like, you can redo them by pressing the 'Redo' button or the 'Ctrl-Y' key combination. Keep in mind that once changes are saved to the database, they cannot be changed using the 'Undo' and 'Redo' buttons. The last toolbar button is the 'Undo All' button and can be also be accessed with the 'F10' key. This button will undo ALL the changes made since the last database save and cannot be recovered using the 'Redo' button.
As you navigate from screen to screen, any changes you make are automatically saved. If you exit the Explorer, or PowerHome, any changes will also be saved. Pressing the 'Refresh' toolbar button or the 'F5' key will also save any changes you've made.
The right hand pane supports single left-clicking, double left-clicking for certain screens/columns, and single right-clicking. This is where edits to the database are actually performed. Some windows in the right hand pane do not support changes and can only be used for navigation. These windows will typically be all gray. Left-clicking in the right hand pane will allow you to change rows and fields if you click within an editable field. Right-clicking will bring up a context sensitive pop-up menu with actions that can be performed. For example, if you were in the Macro Header maintenance screen and right-clicked the third row down, a pop-up menu would appear giving you the option to 'Insert', 'Delete', 'Play', 'Duplicate', 'Export', 'Create Button', 'Cut', 'Copy', or 'Paste'. By clicking 'Insert' you will insert a new blank third row and the original third row will now be the fourth row. If you had clicked 'Delete', the third row would have been deleted. By clicking 'Play', you could play that macro. Clicking 'Duplicate' would have created a new row at the bottom of all the rows with a copy of the third row macro including all of its children rows (the macro detail). You could then click the ID column of this newly created row and type over the highlighted text, renaming the macro to whatever you wanted. Clicking 'Export' will allow you to export the macro header record along with its detail children to a file in SQL format. This file could then be modified and/or emailed to another user and imported into the database using the PowerHome Multi-Editor in SQL mode.
To add rows into the maintenance screen, you would typically right-click and choose 'Insert' from the pop-up menu. When editing a completely blank maintenance screen, the first row is automatically created for you. When you 'Insert' a row, where you click determines where the row will be inserted. If you right-click on the fifth row, then the row will be inserted as the fifth row moving the original fifth row and all others below it down one. If you right-click below all rows, then the new row will be the last row. But there is an easier way to add rows if you are entering one row after another. As you fill out a row and navigate between fields using the 'tab' key, when you fill out the last field and then tab, a new row is created automatically for you. This only happens when the row you are on is the last row (or the only row) and you press the 'tab' key when you are in the last field. This allows for rapid data entry especially when writing macro details.
Another feature of the PowerHome Explorer window are the resizeable panes. If you hover your mouse in the gray area between the left and right panes, you will see that your cursor will change from an arrow to a double left and right arrow. When the cursor looks like this, you can left click and drag the left pane larger or smaller. When you release the mouse the left pane will adjust to the size you selected and the right pane will fill any gaps. Both panes include horizontal and vertical scroll bars when necessary. The right hand pane also includes a split-scroll window. At the botton of the right hand pane, just to the left of the horizontal scrollbar's left arrow button is a black area. When the mouse is hovered over this area, the cursor will change to a double left and right arrow with two vertical lines between them. You can click and drag this to the right and you will be effectively splitting the right hand pane into two pieces, each with its own independent horizontal scrollbar. This is useful when working on long maintenance rows where you might be scrolled far to the right and can no longer see the ID of the rows you are working on.


Setup
The first area that should be configured is the Setup area. Contained within this section are the configuration screens for hardware controllers and plugins. This section also contains basic preferences, operating options, and web server configuration. Navigate to this area by single-clicking Setup in the left pane or by clicking on the button to the left of Setup. You will then see the available areas to be configured under Setup.


Preferences
Web Center
The Web Center is an internally controlled version of Internet Explorer. It is essentially a web browser within a PowerHome window. You may set the startup webpage to be any URL you like, either internal or external to PowerHome. This parameter controls whether the Web Center will appear within PowerHome as a normal window or will appear as a background. If a screen is a window, it can be resized, moved, minimized, or closed. A background does not have a title bar and cannot be closed or moved. However, windows or other backgrounds may appear on top of a background, thereby obscuring it. Choose whether you want the Web Center to be Windowed or Background.
Startup Window
When PowerHome is launched or reinitialized, you can have it default open one of several windows. Choose the window you want PowerHome to automatically launch from this dropdown. You may also create a trigger on Startup or ReInit and call functions to launch additional windows or windows not in the dropdown.
Auto Window Timeout
PowerHome may occasionally pop-up informational or selection type windows. These windows all have a countdown timer in which the window will automatically close or choose the default selection and automatically close. This value controls how long that countdown timer is. The default value is 5.
Drop Down Lines
The Drop Down Line parameter is default set to 0 and this is fine as the functionality for this has not been fully implemented yet. The only place that it currently has an effect is on the drop down for the Macro Player on the main PowerHome frame.
Quiet Start
When PowerHome starts, it will normally pop-up two selection windows. The first window will ask if you want to automatically turn Timed Events on. If the answer is yes (the default), the next selection window will ask if you want to Execute Past Due Timed Events (the default is yes). Both of these windows are determined by other parameters below. If Quiet Start is checked, both of these windows are suppressed with their default values being automatically executed (assuming the parameters below are set to normally cause these windows to be displayed).
Minimize to System Tray
Checking this option will cause PowerHome to minimize to the system tray when the main PowerHome frame is minimized. If this option is not checked, PowerHome will minimize to the Start bar like most Windows applications.
Confirm Shutdown
Checking this parameter will cause PowerHome to display a messagebox before it shuts down confirming that you indeed would like to shutdown.
Export Append
Checking this parameter will cause PowerHome to append any exports made from the PowerHome Explorer to an already existing file rather than overwriting the file if it already exists.
Single Explorer Window
Within PowerHome, some windows are only allowed a single instance to be opened. The Control Center, the Web Center, Device Status, etc. are examples of windows that can only be opened a single time. The PowerHome Explorer window however may be opened multiple times with a different set of data displayed within each window. Checking this option will override the normal operation and allow only a single PowerHome Explorer window to be opened.
Explorer Color Scheme
This section allows you to customize the color scheme used in the PowerHome Explorer. You can set the foreground and background colors for the left hand pane (the tree) and the foreground and background colors for both even and odd rows in the right hand pane maintenance screens.
Activate Timed Events at Startup
Checking this option will cause PowerHome to automatically start the Timed Event timer upon startup. If "Quiet Start" is not checked, a selection window will be displayed with a countdown timer asking if you want to start the Timed Event timer. The default value will be "yes".
Execute Past Timed Events at Startup
If "Activate Timed Events at Startup" is checked (and the default of yes is selected), PowerHome will next pop-up a selection window asking if past timed events should be executed (the default is yes). This means that any events that should have been executed in the past will all be executed.
If you don't Execute Past Timed Events at Startup, then PowerHome will automatically calculate the appropriate time for the Timed Event to next be run. If it has been a long time since PowerHome was last run with a lot of past due Timed Events, it could take an extremely long time for PowerHome to catch up. In this case, it would be best to let Timed Events automatically start, but not execute past due events.
Resume Waiting Macros
When a macro is made to wait with the "Wait" command, its state is written to the database. If PowerHome were to be shutdown and restarted (manual or power failure), checking this box would cause any macros which were waiting prior to the shutdown or reinit to resume and execute.
Load Controllers
Checking this parameter will cause PowerHome to automatically start any controllers defined in the "Controllers" section of the PowerHome Explorer Setup. Normally you would want to start controllers when PowerHome is launched, but if there is a problem with a controller causing PowerHome to hang or error out, you can uncheck this box allowing PowerHome to start without an error so that the problem can be fixed.
Load Plugins
Checking this parameter will cause any defined Plugins to automatically be started when PowerHome starts. However, you may want to temporarily disable the loading of plugins for reasons similar to those listed in the "Load Controllers" section.
Event Logging
The next parameter controls what events are logged in the Event Log. You can select to log only the events that you are interested in tracking. I recommend that you initially log every event until you are comfortable with PowerHome as the log is extremely useful in troubleshooting any problems you may be having.
Proxy Server
If you only have access to the internet via a proxy server, this section allows you to define the parameters so that PowerHome can access the internet for freedb access on the formula function ph_geturl.


Controllers
PowerHome allows for virtually an unlimited number of hardware controllers to be defined. Within this section of the PowerHome Explorer, you can declare the various hardware interfaces you've connected to the PowerHome computer. This is where you would declare your Insteon, UPB, X10, and IR controllers. Each controller must have a unique ID within this section. This screen also has a column named "Load Order". Controllers will be loaded sequentially in the order determined by this column. After giving the controller a unique ID, select the Controller Type from the dropdown list. Pay particular attention to controllers that support both serial, USB, or Ethernet interfaces since these will usually be listed as different controller types. The "Active" column determines if a particular controller will be loaded or not. You may define a controller within this screen and not have it loaded when PowerHome starts by unchecking this column. The last step to defining a controller is the "Settings" button. You MUST click on this button for each controller when you initially declare it in order for its additional unique parameters to be created. Oftentimes, the default values are sufficient, but you must at least open the "Settings" window for the default values to be created. If you have a problem with the settings parameters and need to have the default values recreated, just change the Controller Type from the current value to any other value and then back again. This will erase your old values. When you click on the "Settings" button after having changed the Controller Type, you'll get a new set of default values generated.
Each controller type will have its own unique "Settings" screen dependant upon the controller type. However, some of these parameters may appear on more than one controller. Some of these common parameters are detailed below:


Plugins
PowerHome has support for externally developed modules called plugins. These plugins extend standard PowerHome functionality by providing features that are not a part of the core PowerHome set. Some plugins were automatically installed when PowerHome was installed and may be declared and configured within this screen. For further information on plugins in general, see the plugins section within this document.
The Setup Plugins screen is similar to the Setup Controllers screen in that a "Load Order" column exists. Like controllers, plugins will be loaded sequentially in the order specified by this column. Plugins also require a unique (within this screen) ID. Plugin Type (at this time) will always be "ActiveX" and cannot be changed. The "Launch Data" field requires you to type in the class identifier for plugin activex control. You can find a list of these identifiers for the included plugins installed with PowerHome in the Plugins section of this manual. The next column is the "Initialization Data" field and will contain any initialization data required to setup the plugin. Since this is a single column and some plugins require more than a single value for init data, this field is commonly used to point to an INI file for the plugin for all of its configuration settings. However, whatever value is required here will be determined by the plugin itself and the documentation accompanying the plugin should detail what is required in this field. The last field is the "Active" field and if checked, will cause the plugin to be loaded whenever PowerHome is started or reinitialized.


Broadcasts
PowerHome includes a UDP Broadcast server that will send UDP Ethernet packets to an internal network whenever certain activities occur within the PowerHome program. This server is used by the PowerHome Remote Clients as well as by other third party programs to monitor PowerHome internal activities and is a powerful means for communicating with other machines and applications running on your internal network. The UDP broadcast server runs in a separate thread from the main PowerHome program thereby offloading the broadcast activity so that PowerHome is not burdened with this activity.
PowerHome sends four different types of broadcast messages with each message type being sent on a different port and to a different IP address.You can optionally set the values on this screen so that all four messges are sent to the same port if so desired. Usually the default values are sufficient for this screen (most third party software is designed with these defaults in mind) but you may set the values however you like.


X10 Settings
Previous X10 Incoming Timeout (sec)
This parameter is used primarily for multi-x operations and controls what is the maximum time between incoming X10 signals before it is not considered part of a multi-x operation.
Clear X10 Status on Startup
Sets the X10 status variables to 'Unknown' whenever PowerHome is started. If cleared, PowerHome will use the last known status.
Set X10 Status to Unknown on Status Request
Enabling this parameter will cause the internal X10 status variables and Device Status screen to display 'Unknown' for status whenever a status request command is issued to an X10 device that supports status request.


IR Settings
Button Delay
Controls the amount of delay that is automatically inserted before sending infrared commands. The default value of 200 milliseconds should be adequate and keep any infrared commands from becoming garbled.


Logs
This section allows you to select what types of events you would like to have logged. The default is all.


Device Status
This section allows you to select how the Device Status screen will appear. You can choose the default color scheme and whether the Device Status window appears as a background or a window.


Control Center
This screen allows you to set the appearance of the internal Control Center window. The internal Control Center can be either windowed or background. You can also select if you want the tab control to be visible or not and if visible, how the tabs will appear. The two settings that may require an explanation are below:
Click on Mouse Up
This parameter controls how the Control Center responds when clicking on Control Center buttons with the mouse. If this parameter is checked, then the action associated with the Control Center object will not be added to the execution queue until the mouse actually clicks up. When the mouse clicks up, you MUST be on the Control Center object whose action you want to perform. If this parameter is unchecked, then the action associated with a Control Center object is sent to the execution queue immediately down clicking the mouse.
Auto Clear Changes
The Control Center has a table called ccbuttonstemp that is a mirror of the ccbuttons table (where the Control Center object details are stored when editing the Control Center from the PowerHome Explorer). When a Control Center screen is rendered, the values are read from the ccbuttonstemp table rather than the ccbuttons table. Since details of Control Center objects can be dynamically updated via PowerHome functions, the updates are done to the ccbuttonstemp table and not the ccbuttons table. This parameter controls how often the dynamic changes made to the ccbuttonstemp table are discarded (the ccbuttons table is copied to the ccbuttonstemp table).


Proxy
This screen allows you setup a proxy server if one is required in your particular setup. Proxy servers are rarely encountered within the home environment and would typically be found only in commercial environments. In a typical home setup, you should leave this screen at its default blank settings. If you do have a proxy server, enter the appropriate values in the fields.


Script
Global Variable Max Substitutions
This field determines the maximum global variable substitutions that can occur before an error occurs. This is mainly to prevent an infinite loop situation from occurring. When a global variable is used within a formula or other situations, its actual value is looked up and substituted for the global variable. Since a global variable can contain other global variables that can also contain global variables, this value places a limit on the maximum number of substitutions. An infinite loop situation would occur if global variable {ABC} contained an actual value of {XYZ} which is another global variable. If global variable {XYZ} contains {ABC}, then the substitution algorithm would continue forever and the PowerHome program would be hung. The default value for this field is 25.
Maximum Number of Recursive Calls
This field is similar to the Maximum Global Variable Substitutions field in that its purpose is to prevent infinite loop situations. This value comes into effect when a macro calls another macro that calls another macro, ad infinitum. If a situation where macro A calls macro B which calls macro C which calls macro A were to occur, this value would prevent the PowerHome program from hanging within an infinite loop. The default value for this field is 25.
Macro Jump Limit
This field will allow you to limit the number of times a macro may transfer control to another line within the same macro. Useful in preventing infinite loop situations but could also limit a legitimate macro from looping properly if set to low. Set this value to 0 to disable this feature.
Use Proxy Server in ph_geturl function
Specifies whether the ph_geturl function should use the proxy server values defined under Proxy screen.


Sun
This Setup area allows you to define your latitude and longitude which is used in the sunrise, sunset, and civil twilight calculations. You can select your state and city, or manually enter your latitude and longitude. You must also manually select whether or not you observe daylight savings time in your area.


CD
The Setup CD section is primarily for defining parameters for a CD jukebox and for the programming of playlists. Most CD jukeboxes allow a sequence of tracks to be programmed into it that it will later playback.
Maximum Songs in a Playlist
This parameter should be set to the maximum number of tracks that your jukebox will support being programmed at a time. This is typically around 30.
Maximum Number of Jukebox Slots
This is the number of slots that your jukebox has. In the case of Pioneer, many of their players have an extra slot for quick playing of a single CD. You would not include this extra slot in the total.
Number of Digits when Programming Discs
This refers to the minimum number of digits to use when programming a playlist into your jukebox. When programming a playlist into your jukebox, some manufacturers only require the necessary digits for a disc. In this case, set this parameter to 0. Other manufacturers may require a minimum of 2 digits. An example would be programming disc number 8. Some jukeboxes may require the disc to be programmed as 0 then 8. Set the parameter to 2 in this case.
Number of Digits when Programming Tracks
This works the same way as Number of Digits when Programming Discs but sets the requirements for tracks instead of discs.
PlaySlotTrack Macro
This field allows you to set the ID of the default macro that is to be used for telling a CD jukebox to play a particular slot and track.
PlayPlayList Macro
This field allows you to set the ID of the default macro that is to be used for telling a CD jukebox to program a playlist into the player.


freedb
This section is for setting up freedb. freedb is an online database of CD's and allows you to place CD's into your computers CD player, generate a unique serial number, look that number up online in the freedb database, and save the disc and track information into the Discs section of your PowerHome database. You can select the freedb server you wish to connect to but the default server freedb.freedb.com should be fine. You will need to enter your email address for proper freedb queries to be built. You should also check the Use Proxy Server box if you must use a proxy server to access the internet. The proxy server values are defined in the Proxy section.


Socket Server
PowerHome includes a Socket Server Interface that is useful for remote interfacing with PowerHome. Some third party applications and the PowerHome Remote Clients (Remote Control Center and Remote Device Status) require the Socket Server to be enabled. You can also fire triggers in response to socket communications. The Socket Server protocol is loosely based upon the HTTP 1.0 specification.
a. Enable Socket Server
Check this box if you wish to enable the Socket Server.
b. Socket Server Port
Set the port that the Socket Server should listen to. The default is 8500.
c. UserID and Password
Set the userid and password to appropriate values. The socket server uses standard Base64 encoding.
d. Restricted IP's
If you want to restrict access to the Socket Server to only certain IP's, you must enter them in the Restricted IP's field. If you declare any restricted IP masks, then the socket server may only be accessed if the remote IP matches one of the declared IP masks. If you want the socket server to be accessible by any IP, leave the Restricted IP's field blank. Whether you use restricted IP's or not, the socket server always requires a valid userid and password. The masks may contain exact IP's or end with an asterisk (wildcard character) to match multiple IP's. When entering multiple restricted IP's, you must separate them with a ; (semicolon).


Web
PowerHome includes an internal web server allowing for remote web based control and monitoring of your system. You can use the system generated web pages which provide most of the support you would ever need and/or you can create your own dynamic content using PSP (PowerHome Server Pages). With this formula language, you can totally customize the web interface that you are presented with for PowerHome control.
Enable Web Server
Check this box if you want to make the internal web server available.
Allow Guest on Internal Pages
If the web server is enabled, you may also choose whether to allow the guest login to access the internal web pages. The guest account is userid guest with a password of guest. The guest account cannot make changes to your system with the internal web pages and is limited in what it can see. You may still have sensitive information contained within certain areas of your setup that you don't want the guest account to see. Unless you have a good reason, you should leave the guest account disabled.
Web Server Directory
The web server directory should be set to where PowerHome installed its web files. This directory should be default located in C:\Program Files\PowerHome\Web. If you are creating custom HTML or PSP pages to be served up by the internal web server, you should place them in this directory or a subdirectory of it.
Web Server Port
Set the web server port to the port that you would like to use. If this is your only web server, you should set this to 80 as that is the default port generally used by web servers. You can set this to a different value, but you will have to enter the port number in the address line of your browser to access PowerHome.
Enable Smart NextURL
This parameter controls how PowerHome processes the next URL for internal PH web addresses. If this value is unchecked or the next URL is not an internal address, PowerHome uses a redirect to cause the browser to load the next URL. If this parameter is checked (and the next URL is an internal PH URL), the PowerHome webserver will automatically execute the appropriate next URL code and return it's HTML rather than forcing a redirect first.
Master UserID and Password
Set the userid and password to appropriate values for you to access the system. The password is hidden on this screen.
Access
Within this section you can set the authorization level for each type of external web page that can be served by the PowerHome web server. If you set the PSP pages as 'Any', you can use internal PSP functions for a finer level of control over user access.
Blacklisted IP's
You may enter any number of blacklisted IP masks within this section. A blacklisted IP is not allowed access to the PowerHome webserver under any circumstances. When a request is made to the webserver, the referrers IP is checked to see if it is blacklisted. If not, it is then checked to see if it's trusted. If not, it is then checked for an appropriate userid and password. You may declare the masks as an exact IP or include an asterisk character as a wildcard. When entering multiple trusted IP's, separate them with a ; (semicolon).
Trusted IP's
You may enter any number of trusted IP masks within this section. A trusted IP is not required to enter a userid / password and will have the same authorization as the master user. You may declare the masks as an exact IP or include an asterisk character as a wildcard. If you were running an internal network at home and wanted all of your internal IP's to be trusted, you could enter an IP mask of 192.168.0.*. When entering multiple trusted IP's, separate them with a ; (semicolon).
Main Page
This section allows you to declare the default main page for the PowerHome webserver. Unless you're using PSP to write your own webpages and wish to use your own main page, you should leave these values at their default. The main page is the URL that is loaded when accessing built in secondary pages and the menu option shows "Main".
Menu
This section allows you define the URL's that appear on the default main page menu. All of the default internal pages will initially appear in the menu. You can remove pages if you desire (use the "Default Menu" button to restore these if you like) or add additional entries if you've created your own custom pages.


Email
This section controls whether or not PowerHome will process control Email with embedded Send Keys, Formulas, or Macros. PowerHome has the ability to retrieve Email at intervals you specify and process any that are intended to control the system.
Enable Control via Email
Check this box to enable this feature. You will still have to program PowerHome to periodically check the email either through the macro command Process Email or the formula function ph_processemail.
Restrict Email Control to Address
If you've enabled the Control via Email option, you can restrict processing of control Email to only the addresses that you specify. If you choose this option, enter the Email addresses you will process Email from in the Restricted Email Control Addresses field..
Restricted Email Control Addresses
Enter as many email addresses as you like that you will accept Control Email from. Separate multiple email addresses with a , (comma).
Delete Processed Control Email
Once you've processed a Control Email, you can have the system delete it.
MAPI Client Login
If your MAPI client requires a logon then use this field and the password field to enter your credentials.
MAPI Client Password
Enter the password for your default MAPI client if one is required.
End of Message String
When sending control email, you don't want extra characters within the body of the email to be interpreted as control characters. Many free email accounts or email sent via cellphones add additional text to the email body. Use this field to enter a string of characters that you will add to your control email to signify the end of the control email body.
PowerHome uses MAPI for its Email processing and you must have a MAPI compliant Email client properly setup. Any Email that is not intended for PowerHome will be retrieved but left unaltered in the inbox of your MAPI compliant client.


VR
This area is for the Voice Recognition abilities of PowerHome. PowerHome uses the Microsoft SAPI 4 modules for its voice recognition and text to speech. PowerHome also provides support for SAPI 5 text to speech.
Enable Voice Recognition
Choose whether to enable Voice Recognition or not.
Voice Recognition Autostart
If VR is enabled, you can choose whether the engine should automatically start when PowerHome is launched.
Voice Recognition Autouser and Grammar
If VR is automatically launched at startup, set the user and grammar that it will automatically start with. The Microsoft SAPI allows you to individually train the VR engine on a per user basis.
The Automatic Gain, Complete Timeout, and Incomplete Timeout parameters directly affect the Microsoft SAPI engine. You should not change the default settings unless you are familiar with the engine and the parameters. See the VR Setup section in the Voice chapter.


TTS
This allows you to select whether or not you would like to have Text to Speech enabled and the engine you would like to use. If you would like TTS enabled, you should try to use the Direct SS engine as it is more efficient. Some systems may have problems with this engine so if it doesn't work, you can try the TTS Class engine instead. If you have SAPI 5 installed, you may also use the SAPI 5 selection.


Control Center
The Control Center is the main PowerHome window. This window can be set from within Preferences to behave as a normal window with minimize and maximize buttons or can be set to appear as a background for other windows. You can also have the Control Center available on remote machines via the PowerHome Remote Clients. The Control Center is fully user definable with the number of tabs that it contains, what appears on each tab, as well as the actions that any buttons on the tab may perform. You can place background bitmaps on any tab which could contain a floormap or an actual picture of an Infrared remote control in which you place hotspots which can be clicked to perform the desired actions. The buttons that you place on the Control Center can be X10 commands, IR commands, Macros, or Send Keys. You can assign virtually any keystroke combination to these buttons as well as using the mouse to activate them or using a touch screen.
There can only be one Control Center open. It can be opened from the toolbar, from the menu Control / Control Center, or by pressing the hotkey 'Alt-F1'. This hotkey combination works anywhere from within PowerHome and will instantly bring up the Control Center. This is useful if you are trying to use an infrared or RF keyboard without a monitor handy as a super wireless remote. Once the control center is active, you can select the current tab by either clicking on it or pressing a hotkey combination 'F1' thru 'F12' and 'Shift-F1' thru 'Shift-F12'. The far left tab will always be 'F1'. The tab to the right of this will be 'F2', etc. If you have more than 12 tabs, then the 13th tab will be 'Shift-F1', etc. You cannot hotkey to tabs above 24 but you can still mouse to them. You create tabs for the Control Center from the Tabs section of the PowerHome Explorer. You can also set the tabs order from within this maintenance area also.
Below are some examples of Control Center screens:


Title

Design View
When you declare buttons for the control center, you can set their location, height, width, text color, background color, and a hotkey for them. You can do this from within the PowerHome Explorer, but it's far easier from within the Control Center Design View. Anytime you declare a button or make a change to a button from the PowerHome Explorer, those changes will not be visible until you close and reopen the Control Center (if windowed. If the Control Center is set in preferences as a background you must either restart PowerHome or Reinitialize from the file menu). When you declare buttons in the PowerHome Explorer, they will all default to the same location and same size. Its difficult to design your Control Center layouts from here, so just let everything go to default. Once you are done defining buttons, close and reopen the Control Center so that the newly defined buttons will appear. Next go into Design View by right-clicking on the Control Center whose tab you wish to edit and select Open Design View from the pop-up menu. You will only get the popup menu if buttons have been defined to appear on the tab. An empty tab cannot be designed upon. A new window will open with a copy of the Control Center tab displayed within it. The Design View window will show you approximate screen resolution bars. This design view window also has a toolbar associated with it. There are a number of functions on this toolbar allowing you to design your button layouts graphically.

Design View Toolbar
a. Reselect F1
Reselects the last group of buttons which were selected.
b. Deselect F2
Deselects any buttons which are currently selected.
c. Select Shift-F8
Selects all buttons.
d. Set XY F3
Allows you to set the X and Y coordinates to a specific value or adjust them by an offset for all currently selected buttons.
e. Set HW F4
Allows you to set the Height and Width to a specific value or adjust them by an offset for all currently selected buttons.
f. Align L F5
Align all selected buttons so that their left hand edges are in line. The first selected button is the edge all other buttons will align to.
g. Align VC F6
Align all selected buttons so that their vertical centers are in line. The first selected button is the vertical center all other buttons will align to.
h. Align R F7
Align all selected buttons so that their right hand edges are in line. The first selected button is the edge all other buttons will align to.
i. Align T F8
Align all selected buttons so that their top edges are in line. The first selected button is the edge all other buttons will align to.
j. Align HC F9
Align all selected buttons so that their horizontal centers are in line. The first selected button is the horizontal center all other buttons will align to.
k. Align B F10
Align all selected buttons so that their bottom edges are in line. The first selected button is the edge all other buttons will align to.
l. Size V Shift-F1
Size all selected buttons so that they are the same height. The first selected button is the height all other buttons will size to.
m. Size H Shift-F2
Size all selected buttons so that they are the same width. The first selected button is the width all other buttons will size to.
n. Size B Shift-F3
Size all selected buttons so that both their height and width are the same. The first selected button is the height and width all other buttons will size to.
o. Spce V Shift-F4
Space all selected buttons equidistant vertically. The distance between the first selected button and the second selected button is the distance that is used for all buttons.
p. Spce H Shift-F5
Space all selected buttons equidistant horizontally. The distance between the first selected button and second selected button is the distance that is used for all buttons.
q. T Color F11
Allows you to select the text color for all selected buttons.
r. B Color F12
Allows you to select the background color for all selected buttons.
s. Default Shift-F11
Takes all buttons and sizes them to a default size and then spaces them out in a grid format so that they can be easily manipulated. Useful for when you've just added a number of buttons to a blank tab and they are all default stacked one on top of another. You can only choose this option if no buttons are selected.
t. D / D Shift-F10
Enables Drag and Drop mode. Any selected buttons will be deselected and you can size or move a single button at a time by clicking and dragging.
u. Save Shift-F12
Save any design changes made to the database.

When working within Design View, you can select a button by clicking upon it. The button will display as selected by appearing depressed. Multiple buttons may be selected so that toolbar operations can be performed on all selected buttons. Some toolbar items are only available when two or more buttons are selected (the size functions) and some toolbar items are only available when three or more buttons are selected (the space functions). Whenever a toolbar operation is performed, all selected buttons will be deselected. You can quickly re-select the buttons by pressing the Reselect toolbar item or pressing the F1 key. When buttons are selected, they can also be manipulated by pressing the arrow keys to nudge all selected buttons in a specific direction. If you press the Shift key along with an arrow key, you will adjust the size of all selected buttons. You can also right-click on an area in the Design View and relocate all selected buttons to where you right-clicked. The buttons will be moved in the same layout that they currently are with the first selected button's upper left hand corner moving to the spot that was right clicked and all other buttons moving relative to it.

After saving any changes and closing the Design View window, close and reopen the Control Center (or reinitialize if running in background mode) so that the new design changes will be visible.


Elk M1 Gold

Elk M1 Gold as a PowerHome Controller
You must first set the Elk up as a PowerHome controller. This can be done from the PowerHome Explorer under PowerHome|Setup|Controllers. You may connect to the Elk directly using a serial connection or via ethernet if you have an M1XEP.
After creating the Elk controller, click the "Settings" button to define the COM port (or IP address and Port) and the Analog Poll Interval. The Analog Poll Interval determines in seconds, how often PowerHome will query the Elk for the current value of any input points defined as analog inputs. You must also use the Elk RM utility to configure the Elk serial port for 115200 bps or properly configure the ethernet settings.
PowerHome provides support for all aspects of the Elk M1 Gold. The Elks lighting devices (X10, Insteon, etc.) are available as X10 devices in PowerHome. The digital (16 multiple-state) inputs on the Elk and external boards are available as Multi-State Inputs in the Analog I/O screen. Alternatively, if you're only interested in the open/close status of the multi-state inputs, you can define these points as Digital Inputs in the Digital I/O screen. The Elk digital outputs are available within PowerHome as Digital Outputs in the Digital I/O screen. Inputs on the Elk setup as analog inputs are available within PowerHome as analog inputs in the Analog I/O screen. Elk temperature inputs can be declared as "Temperature" in the Analog I/O screen. The Elk digital inputs, if defined as Multi-State Inputs on the analog I/O screen, have a built in formula that will display appropriate values automatically. You can however override these built in formulas by declaring your own. All analog inputs, digital inputs, digital outputs, and lighting devices are automatically available within the PowerHome Device status screen. Manipulation and reading of these control points are also available using appropriate PowerHome functions and macro commands. PowerHome also supports defining inputs (and triggers) for the Elk "Arm Status", "Arm State", and "Alarm State". The definition for these points are all done in the Analog I/O screen.
When defining digital outputs, digital inputs, and analog inputs, the controller will be the ID of the Elk controller, the unit will be the board number from 1 to 13 (1 is used for the controls onboard the Elk), and the point will be the individual device number on the board from 1 to 16. Temperature inputs will have a unit of 1 for temperature probes, 2 for keypads, and 3 for thermostats. The point value for temperature inputs will be from 1 to 16 corresponding with the available units in each category. There is also an alternative numbering scheme that is allowed that matches the Elk RM numbering scheme rather than the unit number / point number method. Using this method, set the Unit to 0. The Point will then be a value starting at 1. For example, if you are declaring the 5th input on expansion board 3, you can use either Unit 3, Point 5 or Unit 0, Point 37.
In order for PowerHome to work properly with the above Elk controls, you MUST also use the Elk RM configuration software to setup each control appropriately. This cannot be done from within PowerHome since the protocol for this configuration is proprietary and is not made available to developers. This is less painless if using the ethernet interface since both PowerHome and the Elk RM software will be able to connect simultaneously rather than just one software at a time.
PowerHome also supports standard triggers for the above Elk control types. When a digital output changes state either from programming internal to the Elk or from PowerHome control, a digital output trigger will be fired. Similarly, when an Elk input changes state, a PowerHome Multi-State Input trigger or Digital Input trigger will automatically be fired. When an analog input changes, a PowerHome Analog Input trigger will be fired. For Elk Temperature devices (Temp Probe, Keypad, Thermostat), a Temperature trigger will be fired. For lighting devices, the appropriate X10 In and X10 Out triggers will be fired.
The standard functions ph_getothervar, ph_setothervar, ph_getothertimer, and ph_setothertimer may be used to access and update the Elk Custom values. These values are numbered from 1 to 20. Use the ph_getothervar and ph_setothervar to access and update custom values that are either numbers or timers. Use ph_getothertimer and ph_setothertimer to access custom values that are configured as time of day. For time of day custom values, pass the data as an integer representing the time. For example, to pass 9:40 pm, the value should be set to 2140.
PowerHome also supports all of the additional control features within the Elk. In addition to the standard triggers defined above, PowerHome will also fire the Generic Controller Trigger for certain Elk specific functions. These are detailed below:
  • System Log Data Update: If Elk Global Programming Location 35 is enabled, PowerHome will fire the Generic Controller Trigger with a trigger number of 1 and a trigger value of 1. All of the data contained within the command will be available in the [TEMP] variables.
  • Tasks Change Update: If Elk Global Programming Location 38 is enabled, the Generic Controller Trigger will be fired with a trigger number of 2 and a trigger value matching the task number (1 to 32).
  • Keypad KeyChange Update: If Elk Global Programming Location 40 is enabled, the GCT will be fired with a trigger number of 3 and a trigger value of 1.
  • Send Valid User Number and Invalid User Code: The GCT trigger will be fired with a trigger number of 4 and a trigger value of 1.
  • Reply Arming Status Report Data: If Elk Global Programming Location 40 (transmit Keypad keys) is enabled, then the GCT trigger will be fired with a trigger number of 5 and a trigger value of 1.
Support for the Elk specific control commands is available using the ph_ctlrcmd and ph_ctlrcmd1 functions. The specific controller command values and parameters are detailed below. To send an "Arming Status Request" command, the function would look like: ph_ctlrcmd1("ELKID",120,0,0,"","",1)
  • Arming Status Request - 120. No parms. Seconds returned in ret1. Data returned in ret3.
  • Alarm by Zone Request - 240. No parms. Data returned in ret3.
  • Zone Partition Request - 250. No parms. Data returned in ret3.
  • Zone Bypass Request - 260. Zone in parm1, Area in parm2, PIN in parm3. Data returned in ret1.
  • Request Keypad FUnction Key Illumination Status - 270. Keypad in parm1. Code Req returned in ret1, Illum returned in ret3, Beep returned in ret4.
  • Request PLC Status - 280. Bank in parm1. Data returned in ret3.
  • Request ASCII String Text Descriptions - 290. Type in parm1, Textnum in parm2. Data returned in ret3.
  • Request Thermostat Data - 300. Thermostat in parm1. Temp returned in ret1, Flags returned in ret2, CoolSP in ret3, HeatSP in ret4.
  • Request Temperature Format - 310. Type in parm1, Device in parm2. Temp returned in ret1.
  • Request Temperature Data - 312. No parms. Data returned in ret3.
  • Request Valid User Code Areas - 320. Usercode in parm3. Areamask returned in ret1, type in ret2, diagnostic in ret3, and digitstemp in ret4.
  • Request Keypad Area Assignment - 330. No parms. Data returned in ret3.
  • Request Keypad Function Keypress - 340. Keypad in parm1, Keynum in parm2. Data returned in ret3.
  • Request Zone Definition - 350. No parms. Data returned in ret3.
  • Request Change User Code - 360. Codenum in parm1, areamask in parm2, oldcode in parm3, newcode in parm4. Return data in ret1.
  • Manual Refresh of Elk statuses - 1000. 0 in parm1 will retrieve all statuses, 1 in parm1 will get input zone status, 2 in parm1 will get output status, 3 in parm1 will get analog status, 4 in parm1 will get temperature status, 5 in parm1 will get arm status, 6 in parm1 will get variables, 7 in parm1 will get counters. 0 in parm2 will fire triggers as a result of any differences, values > 0 in parm2 will cause triggers to NOT be fired.
In addition to the above Controller commands supported by the Elk, there are a number of "Queued" commands that are also available for the Elk. "Queued" commands are normal tasks supported by controllers such as Send X10, Play IR, and Set Digital. The standard "Queued" commands such as the ones just listed are available by using the appropriate PowerHome functions or macro commands (such as ph_x10, ph_ir, etc). To access the non-standard queued commands supported by the Elk, use the PowerHome ph_ctlrsq function. An example of arm to away in area 1 with a usercode of 1234 would be: ph_ctlrsq("ELKCTLRID",121,"1234",1,1). Details on the Elk specific queued commands are below:
  • Arm and Disarm commands - 121. User Code in parm1, level in parm2, and area in parm3.
  • Speak Word at Voice Siren Output - 211. Word index in parm2.
  • Speak Phrase at Voice Siren Output - 212. Phrase index in parm2.
  • Task Activation - 221. Task index in parm2.
  • Display Text on LCD Screen - 231. Text in parm1, Flags in parm2, timeout in parm3.
  • Set Thermostat Data - 301. Value in parm1, Tstat in parm2, element in parm3.


Generic Serial/Arduino

Generic Serial/Arduino Controller

The PowerHome Generic Serial / Arduino controller is intended for DIY home automation hardware primarily based upon the Arduino platform but can be utilized with any serial port controlled device provided that it can be programmed to support the protocol. The protocol that this controller uses is a simple, lightweight, two-way query and control protocol detailed below.

Configuration of the controller within the Setup section of the PH Explorer is quite simple. Pressing the "Settings" button for the controller opens a window requiring only 2 fields. The COM port that the hardware is connected to on the PowerHome machine and the COM settings for the hardware, typically "19200,N,8,1" for 19200 BPS, No parity, 8 data bits, and 1 stop bit.

The controller supports a number of devices within PowerHome. On the Digital IO screen: Input, Output, IOT Input, and IOT Output device types are all supported. On the Analog IO screen: Input, Output, IOT Input, and IOT Output device types are also supported. For both the Digital IO and Analog IO screens, the Unit column must be set to 0 and the Point column can be set to any number between 0 and 512 inclusive.

The controller protocol consists of 4 basic command types depending upon the Digital or Analog IO device type that you're controlling or querying. These basic command types are:

  • DI - Digital Input
  • DO - Digital Output
  • AI - Analog Input
  • AO - Analog Output
The DI command is used when controlling/querying Input and IOT Input device types on the Digital IO screen. The DO command is used for Output and IOT Output on the Digital IO screen. The AI command is used for controlling/querying Input and IOT Input devices on the Analog IO screen and the AO command handles the Output and IOT Output devices on the Analog IO screen.

The commands sent from PowerHome to the connected controller use the 4 basic commands above with either an "R" or a "W" appended to them to specify whether the command is a "Read" (query the controller for current status) or a "Write" (command the controller to change the status). The controller will respond as appropriate with an echo of the command without the "R" or "W". Any command that is initiated by PowerHome is expected to be acknowledged by the controller. It is this acknowledgement that updates the actual device status within PowerHome. Every command (in both directions) starts with an asterisk "*" character and ends with a carriage return / linefeed combination. After the "*" character comes the basic command. If PowerHome is sending the command, then either an "R" or "W" will also be appended. After the command comes a colon ":" followed by the "Point" number that you defined within PowerHome. If the command is a read command (DIR, DOR, AIR, or AOR) from PowerHome, nothing more is needed and the command is terminated with cr/lf. If the command is a write command from PowerHome (DIW, DOW, AIW, or AOW), then the point value is followed by a comma followed by the actual data you wish to write. Commands sent from the controller to PowerHome start with an "*" followed by the command (DI, DO, AI, and AO), followed by a ":", followed by the point value, followed by a comma, followed by the status of the device and ending with the cr/lf pair. Sample commands can be seen below:

  • *DIR:5~r~n - This is a read command initiated by PowerHome requesting the status the Digital Input device identified by Point 5
  • *DI:5,1~r~n - This command is a response from the controller to PowerHome for the previous command. The number 1 is the actual status of the digital input
  • *AOR:3~r~n - This a read command from PowerHome requesting the status of Analog Output identifed by Point 3
  • *AO:3,745~r~n - This is a response from the controller for the previous command with the value 745 being the raw value to use in updating the Analog Output Point 3
The controller is not limited to only query and response communications and fully supports communications initiated from the controller itself such as the reporting of a change of status.

PowerHome also provides a controller command (9990) that allows you to send any string you like to the connected controller through the serial port. This string can be an actual command adhering to the standard protocol or can be something else entirely if you wished to extend the protocol and have added support for it in your external device. Use the ph_ctlrcmd ( ) function to send the controller command. The string to send to the serial port should be in Parm3. An example of sending an infrared command using the Pronto format might look like this: ph_ctlrcmd(5,"ARDUINO",9990,0,0,"*IR:0000 0071 0022 0002 0149 00A7 0014 003F 0014 0014 0014 003F 0014 0014 0014 0014 0014 0014 0014 0014 0014 003F 0014 003F 0014 0014 0014 003F 0014 003F 0014 0014 0014 003F 0014 003F 0014 003F 0014 0014 0014 003F 0014 003F 0014 0014 0014 0014 0014 0014 0014 0014 0014 0014 0014 003F 0014 0014 0014 0014 0014 003F 0014 003F 0014 003F 0014 003F 0014 003F 0014 05A4 0149 0053 0014 05A4~r~n","")

A sample of actual Arduino code for control and query of several points can be seen below and can be modified to suit your own creations:

//CDS AI 1
//Temp AI 2
//Humd AI 3
//Ultrasonic
AI 4
//PIR DI 1
//Pink Jack DI 2
//Yellow Jack DO 3

#include <SimpleDHT.h>

#define DHTPIN 5
#define CDSPIN 4
#define PIRPIN
2
#define UTrigPin 7
#define UEchoPin 8
#define PINKPIN 3
#define
YELLOWPIN 4

#undef abs

SimpleDHT22 dht22(DHTPIN);

int CDSval = 0;
int Temp = 0;
int Humd = 0;
int
PIRval = -1;
int Udistance = 0;
int Pinkval =       -1;
int Yellowval =
-1;
unsigned long DHTmilli = 0;

char serialBuf[64];

void setup()
{
pinMode(PIRPIN,INPUT);
pinMode(UTrigPin,OUTPUT);
pinMode(UEchoPin,INPUT);
pinMode(PINKPIN,INPUT_PULLUP);
pinMode(YELLOWPIN,OUTPUT);

digitalWrite(YELLOWPIN,LOW);

Serial.begin(19200);
}

void loop()
{
ReadDigital("I:1",false,PIRPIN,&PIRval);
ReadDigital("I:2",true,PINKPIN,&Pinkval);
ReadDigital("O:3",false,YELLOWPIN,&Yellowval);

ReadAnalog("I:1",0.05,CDSPIN,&CDSval);

ReadDHT22(2,3,&Temp,&Humd,2,10,&DHTmilli);

ReadDistance(4,UTrigPin,UEchoPin,&Udistance);

ReadSerial();
}

void ReadDigital(const char *type,boolean invert,int pin,int *value)
{
int temp;

temp = digitalRead(pin);

if(*value != temp)
{
*value = temp;
Serial.print("*D");
Serial.print(type);
Serial.print(",");

    if(invert)
{
Serial.println((*value ==       HIGH ? 0 :
1));
}
else
{
Serial.println(*value);
}
}
}

void ReadAnalog(const char *type,float percentchg,int pin,int *value)
{
int temp;

temp = analogRead(pin);

  if(abs(*value - temp) > (int)round(*value *
percentchg))
{
*value =
temp;
Serial.print("*A");
Serial.print(type);
Serial.print(",");
Serial.println(*value);
}
}

void ReadDHT22(int tempvpin,int humdvpin,int
*tempvar,int *humdvar,int tempchg,int humdchg,unsigned long
*millisec)
{
float TempRaw;
float HumdRaw;
int
Temptemp;
int Humdtemp;
unsigned long millitemp =
millis();

if(abs(*millisec - millitemp) >
2000)
{
dht22.read2(&TempRaw, &HumdRaw,
NULL);
Temptemp = round((TempRaw * 9 / 5 + 32) *
10);
Humdtemp =       round(HumdRaw * 10);

    if(abs(*tempvar - Temptemp) >
tempchg)
{
*tempvar =
Temptemp;
Serial.print("*AI:");
Serial.print(tempvpin);
Serial.print(",");
Serial.println(*tempvar);
}

    if(abs(*humdvar - Humdtemp) >
10)
{
*humdvar =
Humdtemp;
Serial.print("*AI:");
Serial.print(humdvpin);
Serial.print(",");
Serial.println(*humdvar);
}

*millisec = millis();
}
}

void ReadDistance(int vpin,int trigpin,int echopin,int
*distance)
{
int temp;
unsigned long duration = 0;

  digitalWrite(trigpin,LOW);
delayMicroseconds(2);
digitalWrite(trigpin,HIGH);
delayMicroseconds(10);
digitalWrite(trigpin,LOW);
duration =
pulseIn(echopin,HIGH);
temp = duration / 74 / 2;
temp =
*distance - (*distance / 3) + (temp / 3);
if(abs(*distance - temp)
> (int)round(*distance * 0.10))
{
*distance =
temp;
Serial.print("*AI:");
Serial.print(vpin);
Serial.print(",");
Serial.println(*distance);
}
}

void ReadSerial()
{
static int ndx =
0;
static int cmd = 0;
static int point = 0;
static int value = 0;
char rc;

while (Serial.available() > 0)
{
rc = Serial.read();

switch(rc)
{
case '*':
ndx = 1;
cmd = 0;
point = 0;
value = 0;
break;
case 'A':
case 'D':
if(ndx == 1)
{
cmd = rc - 64;
ndx ++;
}
else
ndx = 0;
break;
case 'I':
case 'O':
if(ndx == 2)
{
cmd = cmd * 10 + rc - 72;
ndx ++;
}
else
ndx = 0;
break;
case 'R':
case 'W':
if(ndx == 3)
{
cmd = cmd * 10 + rc - 81;
ndx ++;
}
else
ndx = 0;
break;
case ':':
if(ndx == 4)
{
point = 0;
value = 0;
ndx ++;
}
else
ndx = 0;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if(ndx == 5)
{
point = point * 10 + rc - 48;
}
else if(ndx == 6)
{
value = value * 10 + rc - 48;
}
else
ndx = 0;
break;
case ',':
if(ndx == 5 && point > 0)
ndx ++;
else
ndx = 0;
break;
case '\r':
break;
case '\n':
if(ndx == 5 || ndx == 6)
ndx = 7;
else
ndx = 0;
break;
}

if(ndx == 7)
{
switch(cmd)
{
case 111: //AIR
switch(point)
{
case 1:
CDSval = 0;
break;
case 2:
Temp = 0;
break;
case 3:
Humd = 0;
break;
case 4:
Udistance = 0;
break;
}
break;
case 411: //DIR
switch(point)
{
case 1:
PIRval = -1;
break;
case 2:
Pinkval = -1;
break;
}
break;
case 471: //DOR
switch(point)
{
case 3:
Yellowval = -1;
break;
}
break;
case 476: //DOW
switch(point)
{
case 3:
if(value == 0)
digitalWrite(YELLOWPIN,LOW);
else
digitalWrite(YELLOWPIN,HIGH);
Yellowval = -1;
break;
}
break;
}

      ndx =
0;
cmd = 0;
point = 0;
value = 0;
}
}
}


Insteon Hub V2 (HTTP)

Insteon Hub V2 (HTTP) Controller

The Insteon Hub V2 (HTTP) controller is for connecting to any generation Insteon Hub (both the original "rectangular" hub and the newer "square" hub). This controller uses the HTTP API that is required by the newer "square" hub. If you have an older "rectangular" Insteon Hub, you can use either this controller type or the Insteon NetLinc/Hub controller which uses the more efficient (and less resource intensive) raw PLM protocol. Setup for this controller is nearly the same as the Insteon NetLinc/Hub controller except you'll also need to define the Port, User ID, and Password for your Insteon Hub.


Mi-Light WIFI

MiLight WIFI Controller

The PowerHome MiLight WIFI controller enables PowerHome to interact and control MiLight bulbs. These bulbs are sold under the MiLight, LimitlessLED, and EasyBulb brands. In order to control these bulbs from PowerHome, you must have a MiLight bridge properly setup and configured to communicate with your MiLight bulbs using the MiLight application.

Once your bulbs and bridge have been properly setup and configured using the MiLight app, you can then configure the PowerHome MiLight WIFI controller. Configuration is simple requiring only the IP address of the MiLight bridge and the Port that it uses. The default port for a MiLight bridge is 8899 so you shouldnt need to change this value in the "Settings" window for the MiLight controller. A single MiLight bridge is ONLY able to control 4 different "groups" of bulbs. A "group" can consist of more than one bulb but ALL bulbs within a group will be controlled together with no ability to control bulbs individually. To control bulbs individually, they each must be in their own "group". If you have more than 4 bulbs you wish to control individually, then you'll need another MiLight bridge which you can also configure as another controller within PowerHome.

The PowerHome MiLight controller uses the Analog IO screen to declare and configure your bulbs. The only Analog IO device type support for MiLight bulbs is a device type of "Output". Bulbs will be declared as two separate devices in the Analog IO screen. One entry is to handle On, Off, and brightness settings of the bulb. The second entry is to handle the Color settings of the bulb. To configure a status/brightness device entry, set the Unit column to 0. Set the Point column to the group number (1, 2, 3, or 4) you will this device to represent. You can set the Point column to 0 for "ALL" groups. To configure a Color/Mode device entry, set the Unit column to 1. The Point column is set the same as a status/brightness device entry (Unit = 0) with a value 0 meaning all groups and 1, 2, 3, or 4 for an individual group. You can use the predefined User Range "MILIGHT_LEVEL" for Unit 0 device types and the User Range "MILIGHT_COLOR" for Unit 1 device types.

An explanation of the Raw values used for setting MiLight status/brightness Analog IO devices follows. The values used for "setting" or controlling a MiLight status/brightness group are different from the values that actually end up being stored as the raw value once the control is complete. MiLight devices only support 26 levels of brightness. You'll still set brightness using ranges of 0 to 100 but the actual brightness the bulb will achieve will be rounded to 26 levels of precision. A value of 0 will turn a MiLight group off. A value of 256 will turn a MiLight group on at whatever the last level was. So to control a MiLight status/brightness device, you'll send Raw values of 1 to 100 to turn a group on and set the brightness, a 0 to turn a device off, and 256 to turn a device on at the last brightness level.

The raw values used for storing the current state of a MiLight status/brightness Analog IO device are thus: The MiLight groups support independent brightness leves for both color mode and white mode. PowerHome needs to store both brightness levels, the current mode (color / white), and the current status. The current mode is determined by bit 64 of the raw value. If the formula: ph_and(rawvalue,64) > 0 then the group is in "Color" mode. If the result of the formula equals 0, then "White" mode. Bit 32 indicates the current status of the group as either On or Off. If bit 32 is set, then the group is On. If bit 32 is clear, then the group is Off. The following formula will give you the status: if(ph_and(rawval,32) > 0,"On","Off"). The brightness setting for each mode (Color / White) is stored as a number from 2 to 27 representing 1 of the 26 brightness levels plus 1. The "White" mode brightness is stored in the first 5 bits of the raw value and can be obtained with the following formula: round((ph_and(rawvalue,31) - 1) / 26 * 100,0). The "Color" mode brightness is stored in the raw value as the level (from 2 to 27) multiplied by 128. You can get this Color mode level using this formula: round((ph_and(rawvalue,3968) / 128 - 1) / 26 * 100,0).

To set the mode and color of a MiLight Color/Mode Analog IO device (Unit = 1), use the following raw values. MiLight devices ONLY support 256 unique colors in the range of 0 to 255. To set a device to color mode, send a color value from 0 to 255. If you wish to set a device to "White" mode, use a raw value of 256. A raw value of 1000 will put the device in "Disco" mode. Raw values of 1001 and 1002 will "Slow Down" and "Speed Up" Disco mode respectively. The raw values for storing the current state of a Color/Mode device type are the nearly the same as those used for setting color/mode. A stored raw value of 0 to 255 means the light is in "Color" mode with the color being the actual 0 to 255 value. A stored raw value of 256 indicates "White" mode. A value of 1000 indicates "Disco" mode. The raw values of 1001 and 1002 for controlling the speed of Disco mode are NOT reflected in the stored raw value and will cause no change to the stored raw or calcuated value. When changes are made to a Color/Mode device type (Unit = 1), if a matching status/brightness device (Unit = 0), the status/brightness will be updated as appropriate to reflect the actual light state (color mode, brightness, status).


MQTT

MQTT Controller

The PowerHome MQTT controller gives you the ability to utilize the MQTT (Message Queuing Telemetry Transport) protocol which has become very popular with a multitude of IOT devices. MQTT is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. This PowerHome controller supports devices created in the Analog IO screen as well as the new MQTT Publish and MQTT Subscribe screens in the PowerHome Explorer. To learn more about MQTT, please visit the homesite at http://mqtt.org

The PowerHome MQTT controller (as well as the PowerHome MQTT plugin) make use of the open source M2Mqtt C# code written by Paolo Patierno to handle the low level MQTT transactions and protocol. You can find the M2Mqtt sourcecode repository here: https://github.com/eclipse/paho.mqtt.m2mqtt and you can find the M2Mqtt homepage here: https://m2mqtt.wordpress.com/

In order to use the MQTT protocol in your environment, you must first install and setup an appropriate MQTT Broker (Server) which acts as a central hub for all MQTT incoming and outgoing messages. There are a number of free brokers available for a variety of platforms. One of the most popular ones is Mosquitto and can be installed on the PowerHome machine itself. You can learn more about this broker at its homesite at https://mosquitto.org. As an alternative to installing and running your own MQTT broker, you can make use of any number of brokers that are available on the web.

Once you have an MQTT broker properly setup and configured (either your own or a web based one), you will next need to configure the controller in the PowerHome Explorer under Setup->Controllers by pressing the "Settings" button for your MQTT controller entry. Doing so will bring up the following screen with the defaults pictured below:

The first section describes the MQTT broker that you will be connecting to. You'll enter either the IP address of your broker or the URL if you are using a web based broker. If you installed a broker on your PowerHome machine, you can use the default IP of 127.0.0.1.

Next enter the Port that your broker is configured to use. The default port for MQTT brokers is typically 1883. If your MQTT broker is configured to use secure connections (SSL or TLS), then check the SSL / TLS box. If your broker does not use secure connections, leave this box unchecked. Doing so will automatically set the SSL Protocol to "None". If you are using secure connections, next select the SSL Protocol that your broker uses. You'll also need to supply the CA Certificate and Client Certificate as full path and filenames to X509 certificates.

The next section to configure is the "Client" section. This has to do with how PowerHome will connect to the MQTT broker. You must have a unique ID (unique with respect to all other clients connected to your chosen broker) and you can use the default if you're hosting your own broker or change it to something that identifies your particular PowerHome installation. If your broker requires a userid/password to connect, you'll enter those values in the appropriate boxes.

The next configuration area are the "Prefixes". The Prefixes area allows you to define prefixes to the MQTT topics that you will publish or subscribe to. You have a set of publish and subscribe fixes that handles devices created in the Analog IO screen and you have a set of publish / subscribe prefixes that are used in the MQTT Publish and MQTT Subscribe screens in the PH Explorer. Since MQTT topics can get quite long and often you're subscribing and publishing to a heirarchy that is the same at the upper levels, you can put these upper level "prefixes" in this screen and won't need to enter the redundant information in the Analog IO or MQTT Publish / Subscribe screens. Whatever is entered in the prefix fields in the Settings window will be prefixed to the topics that you configure within the Analog IO and MQTT screens within PowerHome. On the off chance that you need to publish or subscribe to a topic that is outside of the heirarchy that is described in the prefix fields, you can add a "$" character as the first character of a topic in the MQTT Publish / Subcribe screens or in the Analog IO screen. Adding a "$" as the first character of either a subscribe or publish topic will cause PowerHome to drop the "$" character and NOT prepend the relevant prefix to the topc. While the "$" character is a valid topic character at the beginning of an MQTT topic, these topics are not typically used for client communication and is therefore used by PowerHome as a "Don't apply prefix" flag for a topic. Don't be confused by the MQTT protocol specification for the use of "$" as the first character of a topic and PowerHomes internal use of "$" at the beginning of topics.

Once your MQTT controller is properly configured in PowerHome, restart or reinit (changes to the Setup section of PH Explorer requre a reinint or restart to take effect). You are now ready to either defined devices in the Analog IO screen or the MQTT screens to take advantage of the MQTT controller.

To define Analog IO devices for use with MQTT, you need to create and configure them in the Analog I/O Units screen of PowerHome Explorer. The MQTT controller supports analog device types of IOT Input, IOT Output, IOT Input (Calc), and IOT Output (Calc). The difference between the IOT Input/Output and IOT Input/Output (Calc) device types are that the (Calc) device types will actually send the Analog Calculated value to the broker vs sending the normal Raw value. Messages received on the Subscribe topic will also be treated as Calc values and the Raw value will be updated from the Calc value vs the other way around for non-(Calc) device types. Enter the Subscribe Topic for the Analog device into the "ROM ID / IP / Topic / Channel" column. Messages received from the broker on this topic will update the raw and calc values for the Analog device. While the MQTT protocol allows you to use wildcard characters (+ #) in Subscribe topics, you CANNOT do so in the Analog IO screen and must fully qualify the Subscribe topic that will update the Analog IO device. If your chosen device type is an Output device, you have the option to Publish messages (setting an Analog Output device from within PowerHome) to a separate MQTT topic from the Subscribe Topic. If you have defined an Output device and wish to have the separate Publish topic, enter the Publish topic in the "P Topic / O Channel" column. The MQTT protocol does NOT allow wildcard characters (+ #) in Publish Topics. The Unit and Point columns in the Analog IO screen for MQTT controlled device types works a little different from other controllers and instead hold details upon how topics are configured with the broker. Set the Unit column to 0 to have topic messages NOT be retained. Any other value will cause topic messages to be retained (see MQTT documentation for more information on these details). Set the Point column to the QOS (Quality Of Service) level you desire for the topic messages. Valid values are 0, 1, or 2. Any other value will be treated as a QOS level of 0. While MQTT allows for using different QOS levels for Subscribe and Publish messages, the Analog IO devices will use the same Point value for QOS for both Publish and Subscribe messages.

Controlling an Analog IO device from within PowerHome (setting the device to a new value using the Device Status screen, ph_setanalogout function, etc) will Publish the Raw value for normal IOT Input/Output device types or the Calc value for the IOT Input/Output (Calc) devices to the Publish topic WITHOUT any formatting or conversion to JSON, XML, or similar. The Publish message will ONLY contain the Raw or Calc value. Receiving values from the MQTT broker on the Subscribe Topic for the Analog IO device default expects the message to ONLY contain the Raw or Calc value. This can be overridden though by placing a "check" in the JSON column for the Analog IO device. Checking the JSON column will cause PowerHome to interpret the incoming message as JSON data and will attempt to extract the raw or calc value from a name:value pair where the name matches one of the following: (value | status | state | set).

When controlling Analog IO devices (from PowerHome) associated with the MQTT controller, the Analog IO device will NOT have it's Raw or Calc values updated in the table. An Analog Out trigger will ALSO NOT be fired. Controlling an MQTT Analog IO device from PowerHome merely publishes a message to the Publish topic. The Published message will be received by the broker and then echoed back on the Subscribe Topic of the Analog IO device if the Publish and Subscribe topics are the same. If they differ, then the results of the Publish message are expected to ultimately be reflected back to the Subscribe topic by the remote controlled device. You WILL get an Analog In trigger on the received Subscribe topic. This is what will update the Raw and Calc values for the Analog IO device. If you have an IOT Output device type and left the Publish topic blank and entered only a Subscribe topic, controlling this device from PowerHome will Publish a message with the data to the Subscribe topic (Subscribe and Publish are the same). The broker receives this message which then sent out to all clients that have subscribed to that topic of which PowerHome is one. The message that was just sent will come in on the Subscribe topic, update the Analog IO device and then fire an Analog In trigger.

If the design of how Analog IO devices works with MQTT cannot be applied to your situation, you still have the flexibility to adapt to nearly any scenario. In this case, you can create Analog IO devices with a device type of Input or Output and assign them to the PowerHome Virtual controller (must be setup in the Controllers screen). You can then place a call to the ph_mqttpub function in either the RawtoCalc formula, CalctoRaw formula, or an Analog Out trigger to publish the appropriate message containing data structured exactly how you want. You would also create a record in the MQTT Subscribe screen of PowerHome Explorer using your preferred Subscribe topic (including wildcards if you desire) and place a call to the ph_setanalogvalue ( ) function in the "Formula" column to update the respective Analog IO device. A little more work than just declaring the device in the Analog IO screen but full control over the Publishing and Subscribing of MQTT messages.

In addition to using the Analog IO screen to setup MQTT associated devices, you can also interact with the PowerHome MQTT controller through the MQTT Subscribe and MQTT Publish screens in the PowerHome Explorer under the MQTT section. The MQTT Subscribe screen allows you to define topic filters (including wildcards) that you would like to Subscribe to. When a message is received matching the Topic Filter that was Subscribed to, the "Formula" for that particular line will be queued and executed allowing you to act on the incoming message however you like.

The MQTT Publish screen allows you to define topics that you would like to Publish messages to. A Publish Topic cannot contain wildcards (+ #) and so must be fully specified in the Publish Topic column. You also can specify the QOS and whether messages should be retained or not on a per topic basis. The "sending" of messages a particular Publish Topic in this screen is done via the ph_mqttpub ( ) function using the "(MQTT table)" syntax (3 parameters).

Using the PowerHome MQTT controller, you also have the option to Publish messages to topics that have not been predefined and do not appear in the MQTT Publish screen. You do this using the ph_mqttpub ( ) function using the "(General)" syntax that takes 6 parameters.

You also have the ability to Subscribe to topics of your choice that are NOT defined within the MQTT Subscribe screen or in the Analog IO screen. You do this by calling the ph_ctlrcmd ( ) function and using a "command" value of 9997. You supply the Topic filter you wish to subscribe to in the "parm3" parameter and the QOS in the "parm1" parameter. When an incoming message is received on a Subscribed Topic, if the topic DOES NOT match any Analog IO device topics AND does not match any Topic Filters in the MQTT Subscribe screen, then a Generic Controller trigger will be fired on Command 1, Option 1 with details of the topic and message.

To Unsubscribe from messages previously Subscribed to, use the ph_ctlrcmd ( ) function with a "command" value of 9996. The topic you wish to Unsubscribe from will be in "parm3".


Philips Hue

Philips Hue Controller

The Philips Hue controller allows PowerHome to communicate with a Philips Hue Bridge and control / query status of Philips Hue bulbs, groups, and scenes. PowerHome in no way supports the configuration of Hue devices within a Hue bridge and is not a replacement for the appropriate Hue app that performs these functions. In order for PowerHome to control individual devices, groups, and scenes, they must first be configured within the Hue bridge using the Philips Hue smartphone (or equivalent) app.

Once your Philips Hue devices / groups / scenes are configured and able to be controlled via the Hue app, you can then configure PowerHome to also control and monitor the defined devices. Setup within PowerHome is accomplished using the Analog IO screen using Input/Output device types. Using Input/Output device types, you declare a single light (on/off/brightness) as a Unit 0 device. A Unit 1 device is the color/temperature values associated with a single device. To fully support a color bulb, you must declare two Analog IO devices, a unit 0 for the status/brightness and a unit 1 for the color/temperature settings.

Unit 2 and Unit 3 devices are equivalent to Unit 0 and Unit 1 devices respectively but represent a Philips Hue Group vs a single device ID. A Unit 2 device controls a groups status/brightness and a Unit 3 device controls a groups color temperature values.

Unit 4 covers Philips Hue scenes and allows you to define a list of scenes and allows you to select a scene from this list to activate it. Scenes are declared within the "User Ranges" screens of the PowerHome Explorer under Devices->Analog I/O->User Ranges. A user range for Philips Hue scenes associates a raw value with an "Alpha Value" that contains the Philips Hue unique scene ID.

Unlike Unit values of 0, 1, 2, 3, and 4 which are declared as Input/Output device types, a Unit 5 device (single scene activation) is declared using IOT Input / IOT Output device types. The Philips Hue unique scene ID will be entered in the "ROM ID / IP / Topic / Channel" column for these device types. Configuring a scene within PowerHome using this method does not require you to define the scene in the User Range section. Keep in mind that a single scene can equivalent to a Unit 5 scene can be accomplished by declaring a Unit 4 scene with a User Range containing a single scene.

For Units 0, 1, 2, and 3, the Point column is set to the unique sequential numeric ID that configuration within the Philips Hue app assigned to individual devices or groups.

For Units 5 and 6, you can limit the actual scene being activated to a specific group by setting the Point value to the sequentially assigned group ID. If you wish a scene activation to apply to ALL devices (assuming they have been configured to respond to the scene), use a Point value of 0.

For individual devices (Unit 0) and groups (Unit 2) on/off/brightness, the rawvalues are set as follows: To turn off the light, use a rawvalue of 0. To turn on the light at the last brightness level, use a rawvalue of 256. To set a brightness (Hue devices use brightness values from 1 (least bright) to 254 (most bright)), set the rawvalue to the appropriate brightness value in the range of 1 to 254. Setting a brightness will also turn on the light if it is off. You cannot set the brightness without also turning it on. To retrieve the current "status" of a device or group, check bit 256 of the rawvalue to determine if the device or group is on or off. If bit 256 is set, the group/device is on. If bit 256 is clear, it is off. To determine the level (whether on or off), bitwise "and" the rawvalue with 255. On or Off status: if(ph_and(rawvalue,256) > 0,"On","Off"). Brightness level: ph_and(rawvalue,255).

For color settings for individual devices (Unit 1) or groups (Unit 3), Philips Hue devices that support color can do so using one or more methods of XY, Hue/Sat, or CT (Color Temperature). PowerHome supports all 3 methods for the setting of color values as well as the storing of the color values in the rawvalue field. PowerHome also supports the setting of colors using standard RGB color values for devices or groups. If a device or group is set using an RGB color value, it is first converted to XY color values before being sent to the Hue bridge. Rather than using an RGB color value to set a color, you would typically want to set color values using one of the three Philips Hue methods (XY, Hue/Sat, CT) since RGB color values are converted to XY values before sending to the Hue bridge. When the device or group is "polled", the reported color value will be in XY mode and that is the value that will be used to represent the color status in the Analog IO rawvalue.

When "polling" the Hue bridge for the current color values of devices and groups, the value will be retrieved into PowerHome using Hue bridge "colormode" parameter which will be set to the method (XY, Hue/Sat, CT) that was last used to update the device or group.

Color values for setting and referencing are encoded into the rawvalue. Bits 536870912 and 268435456 control how the value is interpreted. If both of these bits are clear, then rawvalue is in RGB mode. If bit 268435456 is set, then the rawvalue is in XY mode. If bit 536870912 is set, then the rawvalue is in CT mode. If both bits 536870912 and 268435456 are set, then the rawvalue is in Hue/Sat mode.

For Unit 1 and Unit 3 color settings, you can set an RGB color value simply by setting the rawvalue to the RGB value. No conversions are necessary. This RGB value will be stored in the Analog IO rawvalue column and will remain at this value until the next time the light or group is "polled" at which time the color rawvalue will be updated to the equivalent XY color setting.

To set an XY color value for a Unit 1 or Unit 3, take the X value (a decimal from 0 to 1) and multiply by 10,000 and truncate any remaining decimal portion. Next take the Y value (a decimal from 0 to 1) and multiply by 10,000 and then multiply by 16,384. Truncate any remaining decimal portion. Add the new X and Y values together and then add 268435456. This is the rawvalue for setting color using a Philips Hue XY color. If you were retrieving the status of a rawvalue, you would first bitwise "and" the rawvalue with 536870912 + 268435456 (total value: 805306368) and then divide by 268435456. The resulting value will be 0 (RGB), 1 (XY), 2 (CT), or 3 (Hue/Sat). If this value is 1, then to get the X value, use the following formula: ph_and(rawvalue,16383) / 10000. To get the Y value, use this formula: ph_and(rawvalue,268419072) / 16384 / 10000.

To set a CT (Mired Color Temperature) value for a Unit 1 or Unit 3, start with the color temperature in degrees Kelvin (typically between 2000K and 6500K). Take the value 1,000,000 and divide it by the color temperature and truncate any decimal remainder. If you wanted to set a color temperature value of 6500K then the calculation would look like: long(1000000 / 6500) which would be equal to 153. Take the resulting value and add 536870912. If we were to use our example of 6500K, then the rawvalue would be 536871065. To reverse this process and get the data out of the rawvalue field, first execute: ph_and(rawvalue,805306368) / 268435456. If the result is 2, then we know the color value in rawvalue is stored in CT mode. To extract the color temperature, use this formula: long(1000000 / ph_and(rawvalue,16383)) which will result in 6535.

To set a color value using Hue/Sat for a Unit 1 or Unit 3, start with values supported by the Philips Hue bridge. The bridge expects Hue values to be in the range of 0 to 65535 and Saturation values in the range of 0 to 254. Take the Sat value and multiply it by 65536 and then add in the Hue value (0 - 65535). To this sum, add the value 805306368 to set the bits to indicate the value is a Hue/Sat mode color value. Extracting the value is the reverse of the process and similar to the other reverse methods above. First determine the mode that the value is stored in using this formula: ph_and(rawvalue,805306368) / 268435456. If the result is 3, then the rawvalue contains a color value in Hue/Sat mode. To extract the Hue, use this formula: ph_and(rawvalue,65535). To extract the Saturation, use this formula: ph_and(rawvalue,16711680) / 65536.

A Unit 4 Input/Output device allows for the activation of a scene selected from a list that was created as a User Range. In order to utilize this Unit 4 device, you must first create a User Range and associate rawvalues (the actual value is not really relevant other than it must be unique within the range) with a Philips Hue scene ID (and alphanumeric value that will be entered into the "Alpha Value (Optional)" field). You would also enter an appropriate Calc Value as the text representation of the scene. To activate a scene in a Unit 4 device, the rawvalue will be looked up in the User Range table and the associated Hue scene ID will then be sent to the Hue bridge.

A Unit 5 IOT Input / IOT Output device allows for the activation of the single scene associated with the device. You do NOT have to create a User Range for this scene activation method as the unique scene ID is entered into the "ROM ID / IP / Topic / Channel" column. You activate this device scene by setting the rawvalue to any value.

The PowerHome Philips Hue controller also exposes a controller command that allows you to send any Hue API command you desire to the Hue bridge. This can be achieved by calling the ph_ctlrcmd ( ) function with a "command" value of 999. Parm1 is a number from 0 to 3 that equates to the following HTTP methods used by the Hue API protocol: GET, PUT, POST, and DELETE. A value of 0 would be GET, etc. Parm2 is also a number from 0 to 3. A parm2 value of 0 will return the raw JSON returned by the Hue bridge as a result of the command. A parm2 value of 1, 2, or 3 will pass the raw JSON through the ph_flattenjson ( ) function with a type of 0, 1, or 2 respectively. Parm3 is the actual Hue API command you wish to send to the bridge. Parm4 is the JSON data that you wish to pass as part of the command.

The following formulas demonstrate the 999 controller command and allow you to query the Hue bridge for configuration for lights, groups, and scenes. These formulas are very useful as some of this information is needed to properly configure PowerHome for control of lights, groups, and scenes:

This formula will query the connected Philips Hue controller for a list of defined lights and their status. Substitute the first parameter "HUE" for the PowerHome ID of your Hue controller: ph_ctlrcmd("HUE",999,0,1,"/lights","")

This formula will return the defined groups: ph_ctlrcmd("HUE",999,0,1,"/groups","")

This formula will return the defined scenes: ph_ctlrcmd("HUE",999,0,1,"/scenes","")

To get the detailed information associated with a particular scene, use the previous formula to get the unique scene ID and then substitute that for the "XXX" in the 5th parameter: ph_ctlrcmd("HUE",999,0,1,"/scenes/XXX","")


Z-Wave Razberry

Z-Wave Razberry Controller

The Razberry controller gives PowerHome the ability to query and control Z-Wave devices. The Razberry is a Z-Wave enabled daughtercard for the Raspberry Pi. It can be purchased on Amazon at this link: https://www.amazon.com/Z-Wave-Me-RaZberry2-Plug-Raspberry-frequency/dp/B01M3Q764U. Details of the Razberry can be found here at the manufacturers website: https://z-wave.me/products/razberry/. In order to use this controller with PowerHome you must first have a Raspberry Pi paired with a Razberry daughtercard and the Z-Way software properly installed configured. Details on this can be found on the manufacturers website. PowerHome uses the "Expert" mode interface of the internal Z-Way webserver running on the Raspberry Pi to perform its control.

Once you have your hardware running properly, you can create a "Z-Wave Razberry" controller in the Setup section of PowerHome Explorer. The "Settings" window for this controller will look similar to this:

Set the IP Address to the IP of your Raspberry Pi hosting the Z-Way webserver. The default port is 8083 so unless you've changed, the default value on this screen should be fine. The UserID and Password fields hold the UserID and Password you previously configured in the Z-Way web interface when you initially setup your hardware. The Z-way Poll Interval is how often in seconds that you wish to poll the Z-Way server for any Z-Wave changes. The Raw Log File should be set to a path and filename where you would like to have log information written if you enable it within the Z-Wave Explorer.

Configuration of Z-Wave devices within PowerHome is done using a dedicated Z-Wave screen called the Z-Wave Explorer. You can do basic Z-Wave setup such as Inclusion and Exclusion in this screen or the Z-Way web interface. Once you have included Z-Wave devices in your Razberry home network, they will appear on the "Nodes" tab of the Z-Wave Explorer. This tab is primarily informational data but you can configure some of the columns such as the "Given Name" and the "Switch All Mode". You can also click on the "Options" button for a node and perform some control actions associated with it as well as configure parameters specific to the node. Any changes made on this tab will be directly reflected within the Z-Way expert interface and vice versa so you can use whichever interface you prefer.

To define actual Z-Wave devices in PowerHome, you'll use the "Devices" tab. While "nodes" represent the physical Z-Wave devices that have been "included" on your network, "Devices" represent the logical functions available within a node and are tied to a specific Command Class that the node supports. Z-Wave "Devices" defined within PowerHome are NOT reflected in the Z-Way interface and are PowerHomes representations of the functions available for Nodes. You'll enter an ID and Description and the Node number that the device is a function of. Once you've entered the "Node ID", the "Command Class" column will present CC's that are available for that Node. This screen is similar to the Analog IO screen where you have the option to supply RawtoCalc and CalctoRaw formulas for manipulating the raw and calculated values or performing other actions such as updating the foreground and background colors for the device displayed in the Device Status screen. You can also enter a "Poll Interval" (in seconds) for how often you would like the Razberry controller to query the Z-Wave device.

The Z-Way Tree tab is very useful for seeing the entire raw Z-Way data structure that is maintained within the Raspberry Pi Z-Way interface. This data is normally returned in JSON format but is flattened for display on this screen. This screen is useful to see all options available within your "included" nodes.

With the Razberry Z-Wave controller, you have a number of Z-Wave related functions available for control and query of Z-Wave devices. You also have 3 triggers available: Z-Wave Device Chg, Z-Wave Get, and Z-Wave Set.


ThingSpeak IOT

ThingSpeak IOT Controller

The ThingSpeak IOT controller allows you to interact with IOT devices through the ThingSpeak cloud website at https://www.thingspeak.com. Thingspeak has multiple options for paid accounts as well as completely free options. To get started you'll need to create at least a free account at the ThingSpeak website. A free ThingSpeak account allows you to have 4 separate channels (each ThingSpeak channel can have up to 8 devices associated with it for a total of 32 total devices for a free account). With the free account you get up to 3 million messages/year or approx 8,200 messages/day. With a free account you also have an update limit of once every 15 seconds.

The PowerHome ThingSpeak IOT Controller allows you to interface with a ThingSpeak account. To setup the controller, you'll provide the API URL as well as up to 4 channels in the "Settings" window on the Controllers screen in PowerHome Explorer. For each channel, you'll enter your Read key and Write key. The ThingSpeak API provides for multiple methods of access, update, and reading of data but the PowerHome controller ONLY supports the HTTP API.

Configuring your ThingSpeak "devices" is done in the Analog IO screen with device types of IOT Input, IOT Output, IOT Input (Calc), or IOT Output (Calc). Input device types are intended to primarily read data from the ThingSpeak cloud but you can update the device in the cloud using PowerHome functions. Output device types can both read and update the ThingSpeak cloud with the ability to read/update a single channel/device or declare a separate channel/device for read and a separate channel/device for write.

When configuring your devices in the Analog IO screen, you'll enter the channel ID in the "ROM ID / IP / Topic / Channel" column. For Input devices and Output devices reading and writing to the same channel/device, set the Unit column to 0 and the Point column to the device number (1 thru 8). If your Output device updates a different channel/device from the read operation, enter the update channel ID in the "P Topic / O Channel" column and the update device number in the Unit column (1 thru 8). For both Input and Output device types, you can set a "Poll Interval" in seconds where PowerHome will query the ThingSpeak cloud for the latest data.


PowerHome ThingSpeak

PowerHome ThingSpeak Controller

The PowerHome ThingSpeak controller is very much like the ThingSpeak IOT controller except that the ThingSpeak "cloud" is within PowerHome itself. This controller implements the same HTTP API that the ThingSpeak IOT controller uses but all communication is done directly with PowerHome. This works very well if you are accessing and working with devices within your control so you can configure them to speak to the PowerHome ThingSpeak controller vs the actual ThingSpeak IOT cloud server.

Setup is done nearly the same except you'll define the webserver port your PowerHome ThingSpeak controller will use vs the ThingSpeak IOT cloud API URL. You still have the ability to declare up to 4 channels with Read and Write keys (you'll make these values up yourself). Instead of being limited to only 8 devices per channel, the PowerHome ThingSpeak controller allows you to have up to 256 devices per channel. In the "Settings" window in the Controller setup screen, you'll also have the ability to make the PowerHome ThingSpeak controller secure by checking the Secure box and providing a path/filename to a certificate file.

Configuring your PowerHome ThingSpeak "devices" is done in the Analog IO screen with device types of IOT Input, IOT Output, IOT Input (Calc), or IOT Output (Calc), the same as you would with the ThingSpeak IOT controller. Input device types only work with a single channel/device for both read and write operations while Output device types can have separate channel/device configurations for read and write operations.

When configuring your devices in the Analog IO screen, you'll enter the channel ID in the "ROM ID / IP / Topic / Channel" column. For Input devices and Output devices reading and writing to the same channel/device, set the Unit column to 0 and the Point column to the device number (1 thru 256 for the PowerHome ThingSpeak controller). If your Output device updates a channel/device (within the same controller) different from the read operation, enter the update channel ID in the "P Topic / O Channel" column and the update device number in the Unit column (1 thru 256). There is no need for "Poll Intervals" for either Input or Output devices since the data is already contained within the PowerHome controller.


TP-Link

TP-Link Controller

The TP-Link controller allows you to control on/off and dimmer devices that conform to the TP-Link (Kasa) standard. All setup and configuration must be first done using the TP-Link smartphone app but afterwards, you can perform actual control through PowerHome.

On/Off devices are configured in the PowerHome Explorer on the Digital IO screen as IOT Input and IOT Output device types. Enter the TP-Link device IP address into the "IP / Address" column. Unit and Point must have values but are not used (0,0 is fine).

Dimmer devices are configured within PowerHome Explorer on the Analog IO screen as IOT Input and IOT Output device types. Enter the TP-Link device IP address into the "ROM ID / IP / Topic / Channel" column. Unit and Point must have values but are not used (0,0 is fine).

Since TP-Link dimmers track the on/off status separately from the dimmer value, the two separate data values must be encoded together into a single number. Dimmer values are 0 to 100 but are stored and set as a value from 1 to 101. The number 128 signifies that the TP-Link device is off. The number 256 signifies that the TP-Link device is on. By combining the values (or not) you can change the on/off state and dimmer level in a single command, change only the on/off state, or change only the dimmer state (you can change the dimmer level even when the TP-Link device is off and doing so does NOT turn the device on). To turn off a dimmer without changing the current level, use an analog value of 128. To turn on a TP-Link dimmer without changing the level, use an analog value of 256. If you want to change the dimmer level only without changing the on/off state, use an analog value of 1 to 101. If you want to change both the on/off state and the level in the same command, add the values together. Assuming you want to change the level to 50%, then turning on at 50% would be 256 + 51 or 307. To turn off and set the level to 50% would be 128 + 51 or 179. The values that are stored internally in the Analog IO table within PowerHome is the combined on/off state and dimmer level.

You can use the predefined User Range ID for WEMO (TP-Link devices and Wemo devices are handled internally in the same manner) to handle the various on/off and dimmer states.


Tuya

Tuya Controller

The TUYA controller controls the plethora of low cost, Chinese made IOT devices that you can buy nearly everywhere online. This includes outlets, Light switches, and bulbs. Any of these basic devices that can be controlled by the Tuya, Smart Life, or Jinvoo Smart smartphone apps can be controlled by this controller. All setup and configuration must be first done using the appropriate smartphone app but afterwards, you can perform actual control through PowerHome.

Be aware that the control is accomplished using the undocumented Tuya cloud API that was developed for Home Assistant. These devices are all cloud controlled so PowerHome speaks to the cloud service and then the cloud service talks to the device and performs the requested action. This means internet connectivity is required and the cloud provider can potentially track when and what you are controlling.

Most of these devices can be flashed with an alternative firmware (Tasmota is very popular) which will then allow for local control of the device using MQTT

PowerHome supports on/off devices including devices such as powerstrips with multiple individually controlled outlets, dimmer switchs, and bulbs including adjustable color and temperature.

On/Off devices can be defined as IOT Input or IOT Output in the Digital IO screen. The Unit can be any value (the default of 0 is fine). If the device is a single controlled device (such as a single outlet) then set the Point column to 0. If the device has multiple control points (such as a powerstrip), set the point to the socket you wish to control (1 for the 1st socket, 2 for the 2nd socket, etc). If you wish to control ALL control points as a single device, then set the point value to 0. Set the IP/ Address column to the base unique Tuya ID (see below).

Dimmers, Color bulbs, and Scenes are all configured in the Analog IO screen. You can also configure your On/Off devices in the Analog IO screen (instead of the Digital IO screen) if you'd like a little more flexibility. On/Off, Dimmers, and Bulbs are defined using either the IOT Input or IOT Output device types. The Unit column determines what is actually being controlled as follows: 0 is used for an On/Off device. 1 is used for a dimmer or bulb (On/Off/Level) device. 2 is used strictly for adjusting Color and Temperature for a bulb (if you have a color bulb, you'll typically define two devices, one for the status and level and one for the color/temperature). 3 is used for specifying a specific scene.

In addition to the above single scene option (IOT Output, Unit 3), you can declare Scenes using Input and Output device types and set the Unit to 4. The difference is that an IOT Output, Unit 3 scene describes a single scene ID with the only option for control is to "Activate" the scene. An Output, Unit 4 scene allows you to define a dropdown list of scenes using a Range ID that allows you to select from multiple scenes to be controlled using a single device. Basically, if you have 5 scenes, you can create 5 IOT Output, Unit 3 devices or create 1 Output, Unit 4 device (or any combination thereof).

For IOT Input / IOT Output and Units 0 thru 3, you will enter the base unique Tuya identifier in the ROM ID / IP / Topic / Channel column. For Input / Output Unit 4 scenes, the ROM ID / IP / Topic / Channel is not available and instead the unique Tuya identifier for the scenes are defined in a Range of values and then that Range ID is assigned to the Input / Output Unit 4 device.

For Input / Output Unit 4 scenes, set the Point column to a unique value to distinguish it from other Input / Output Unit 4 scenes for the same controller (internally the Point column is not used but it needs to have a unique value in order to be saved to the database). For IOT Input / Output (Units 0 thru 3), set the point to the specific control point for the device. If the device has a single control point, then set the Point to 0. If the device has multiple control points, set the Point to the specific number. Using a Point value of 0 will cause ALL control points in a multiple control device to be controlled together.

For binary controlled devices (On / Off) in the Analog IO screen (IOT Input / IOT Output Unit 0), On / Off control is done by setting the output to 1 for Off or 2 for On (actually any value <= 1 will be treated internally as a 1 for Off. Any other value > 1 will be treated as a 2 for On).

For unit 1 devices (on/off/level) in the Analog IO screen, the value to "set" the device is different than the rawvalue that is used to store the current status. Because a Tuya device has multiple possible options, this value can be difficult to understand and needs some explaining. The value used to "set" or control a unit 1 device is calculated as follows: If you are setting a level, take the level (in a range of 0 to 100), multiply by 64 and then add 2 (adding 2 signifies that the device is turned on. Most Tuya devices automatically turn on when the brightness is set to a level > 0. If the brightness is set to 0, then most Tuya devices will turn off. You can set the brightness alone without the appropriate on/off value but PowerHome may not show the proper on/off status until the device is polled for its status). If you are just turning a device on or off without wanting to change the level, the set value is 2 for on or 1 for off (using a set value of 0 will automatically be converted to a 1).

The rawvalue that is used to determine the status of a unit 1 device is a bit more complicated that the value used to "set" the status. Because a device (such as a bulb) may also have a color option, a white color temperature, and support separate brightness levels for color and white modes, all of these data values must be included in the single rawvalue value. Bit 1 set signifies that the status is off. Bit 2 set signifies that the status is on. Bit 4 set indicates that the device is in "white" mode. Bit 8 set indicates that the device is in "color" mode. Bit 16 set indicates that the device does NOT support a separate color brightness. Bit 32 set indicates that the device DOES support a separate color brightness. Starting at bit 64 and continuing to bit 131072 is the "white" mode level (as well as the "color" mode level if bit 16 is set and bit 32 is clear). Starting at bit 262144 and continuing to bit 536870912 is the separate "color" mode brightness level (bit 16 would be clear and bit 32 would be set). You can determine the on/off status of a device by using the ph_and( ) function like this: if(ph_and(rawvalue,2) > 0,"On","Off"). You can determine the current mode of a device (white or color) with this statement: if(ph_and(rawvalue,12)= 8,"Color","White"). The following formula is an example of how to return the current brightness level depending upon the current mode: if(ph_and(rawvalue,40) = 40,ph_and(rawvalue,1073479680) / 262144,ph_and(rawvalue,262080) / 64).

For unit 2 devices (color/temperature) in the Analog IO screen, you "set" the status as follows. Bit 1 determines if the value being "set" is a "color" or a "temperature". Set bit 1 for color values and clear bit 1 for temperature values. If you are setting a "color", calculate the desired RGB color (for example Red would be rgb(255,0,0) which is equal to 255) and multiply by 2 and then add 1 (bit 1). To set a unit 2 device to Red, 255 * 2 + 1 = 511. If you are setting a "temperature", valid temperature values are from 1000K (Kelvin) to 10,000K. Take the desired temperature in Kelvin and multiple by 2 (do not add a 1). For a temperature of 3500K, use a rawvalue of 7000. Unlike Unit 1 devices, the rawvalue used to determine the status is the same as the rawvalue that is used to "set" the status. If a bulb does not support the setting of white temperature, you can set the mode by setting the unit 2 device to value of 0. If you wish to just toggle between color and white modes using the last color and white settings, you can send a value of 1 to go to color mode and a value of 0 to go to white mode. The next time the device is polled, it will update the appropriate color/temperature setting. Whenever you toggle modes in a unit 2 device, the equivalent unit 1 device will also have its first 4 bits updated (either 6 for On/white or 10 for On/color) to reflect the current mode.

For unit 3 devices (single scene activation) in the Analog IO screen, you "activate" a scene by sending a rawvalue of 2 (same value you would use to turn "on" a device). Since a scene cant be "deactivated", there is no equivalent "off" value which would normally be a 1. Since a unit 3 device is an IOT Input/Output device type and the unique scene ID is contained in the ROM ID / IP / Topic / Channel column, there isnt much else needed concerning the setting of a unit 3 device.

For unit 4 devices (scene activation by choosing from a list) in the Analog IO screen, you MUST declare the scenes by first creating a range of values containing the scenes you intend to use. This allows you to associate a raw (numeric) value with a unique Tuya scene ID (alphnumeric). You "activate" a scene by setting the rawvalue to the particular to the rawvalue that was assigned to the scene in the range of values. When the controller goes to activate the scene, it looks up the "Alpha Value" in the range of values (you must enter the Tuya unique scene ID in the "Alpha Value (Optional column)" in the range of values screen) associated with the Raw value and then sends that unique scene ID to the Tuya API.

In order to perform the setup within PowerHome of Tuya devices and scenes, the unique Tuya ID associated with the device or scene is needed for entry into the appropriate screens. Once you've configured your devices and scenes using your chosen smartphone Tuya app (Tuya, Smart Life, Jinvoo Smart) and defined the Tuya Cloud controller in PowerHome, you can retrieve these values as well as additional internal information by running the following formula. The example assumes that the ID of your PowerHome Tuya controller is "TUYA": ph_ctlrcmd(5,"TUYA",9998,0,0,"","")


Wemo

Wemo Controller

The Wemo controller allows you to control on/off and dimmer devices that operate using the Belkin "Wemo" standard. All setup and configuration must be first done using the Wemo smartphone app but afterwards, you can perform actual control through PowerHome.

Wemo On/Off devices are setup in the PowerHome Explorer in the Digital IO screen as IOT Input and IOT Output device types. Enter the Wemo device IP address into the "IP / Address" column. Unit and Point columns must have values but are not used (0,0 is fine). The Wemo Port is determined internally from within PowerHome

Dimmer devices are setup in the PowerHome Explorer on the Analog IO screen as IOT Input and IOT Output device types. Enter the Wemo device IP address into "ROM ID / IP / Topic / Channel" column. Unit and Point columns must have values but are not used (0,0 is fine). The Wemo Port is determined internally from within PowerHome.

Since Wemo dimmers track the on/off status separately from the dimmer value, the two separate data values must be encoded together into a single number. Dimmer values are 0 to 100 but are stored and set as a value from 1 to 101. The number 128 signifies that the Wemo device is off. The number 256 signifies that the Wemo device is on. By combining the values (or not) you can change the on/off state and dimmer level in a single command, change only the on/off state, or change only the dimmer state (you can change the dimmer level even when the Wemo device is off and doing so does NOT turn the device on). To turn off a dimmer without changing the current level, use an analog value of 128. To turn on a Wemo device without changing the level, use an analog value of 256. If you want to change the dimmer level only without changing the on/off state, use an analog value of 1 to 101. If you want to change both the on/off state and the level in the same command, add the values together. Assuming you want to change the level to 50%, then turning on at 50% would be 256 + 51 or 307. To turn off and set the level to 50% would be 128 + 51 or 179. The values that are stored internally in the Analog IO table within PowerHome is the combined on/off state and dimmer level.

You can use the predefined User Range ID for WEMO to handle the various on/off and dimmer states.


Plugins
Plugins are extensions to the PowerHome program and can provide additional functionality that is not built into PowerHome. Each plugin runs in it's own separate thread so as not to burden PowerHome with processing and eliminates the possibility of problems within a plugin causing PowerHome to hang.
Plugins are developed using the PowerHome Plugin SDK and may be developed by programming savvy users or other third parties using a variety of languages. Plugins are able to directly control and interact with the PowerHome environment as well as monitor the internal processes of PowerHome by listening to the messages sent by the UDP Broadcast server. Plugins are also capable of being directly interacted with by PowerHome using the ph_picmd and can fire it's own specific triggers.
Plugins are defined within the Setup section of the PowerHome Explorer under the "Plugins" section. To properly setup a plugin, you must know it's activeX class name and any initialization parameters that may be required. These values are specific to the plugin and you should consult the plugin manufacturer for the proper settings.
Listed below are the plugins that are supplied with the PowerHome installation. These plugins will have been installed in the plugins subdirectory beneath the PowerHome directory.
Skeleton
Skeleton .Net
Alexa (fake Wemo)
AVTech Camera DVR
Caller ID
Directory Monitor
Fake SMTP Server
File Monitor
FireTV control via ADB
Growl
MQTT
ODBC
Power Monitor
Raw COMM
Raw Socket
Roku
Russound
UDP Listener
URL Scraper
URL Scraper 1
VideoStorm CRM88 Matrix switch
Virtual Serial Port
Windows Lock
Window Monitor
XPL


Plugin SDK

PowerHome Generic Plugin SDK:
PowerHome now supports the use of user developed and third party generic plugins. With the Generic Plugin SDK, PowerHome functionality can now be extended or enhanced as the user sees fit. The details of how to create your own PowerHome plugins are listed below.
Starting with version 1.2 of the SDK, all plugins run in their own separate thread.
To initialize a plugin within PowerHome, open the PowerHome Explorer and navigate to PowerHome|Setup|Plugins. In the Setup Plugins screen, you give specific details about the plugins you wish PowerHome to load. The Load Order column determines what order a plugin loads. You must give a unique ID to all plugins. Currently only ActiveX type plugins are supported. The "Launch Data" field MUST contain the ActiveX Classname of the plugin. Some plugins may require Initialization Data. If none is required, leave this field blank. Otherwise, enter the data appropriate to the specific plugin. PowerHome must either be restarted or reintialized before any changes on this screen take effect.
Version 1.2 of the PowerHome Generic Plugin SDK:
  1. All plugins MUST be compiled as a COM (activex control) object. Plugins may be written in any language that supports these objects including Visual Basic, C, and PowerBuilder.
  2. All plugins MUST support a predefined set of public interface functions. These functions are detailed below:
    • PHPI_Init(long hPH, integer iI, string sID) returns integer.
      This function is called within the plugin when PowerHome initializes the plugin. This is the first function called within the plugin and it is passed vital initialization data which should be stored for future reference and use by the plugin. The hPH parameter contains the Windows handle of PowerHome and is required for the plugin to communicate back to PowerHome. The iI parameter contains the PowerHome internal plugin index. This value is necessary for any plugins wishing to make use of the PowerHome Plugin Passthru window. The sID parameter contains the ID that was assigned to the Plugin within the Setup Plugins screen of PowerHome. It is required if you will be firing Generic Plugin Triggers. You should return a 0 from this function.
    • PHPI_SDKVersion() returns double.
      This function will be called to determine what SDK level the plugin supports. Currently, all plugins should return a value of 1.2. Version 1.1 of the plugin SDK is no longer supported. This function is called immediately after PHPI_Init during initialization of a plugin.
    • PHPI_InitData(string sData) returns integer.
      This function is called by PowerHome immediately after initialization but before PHPI_Enable. The string data that is passed to it is the data defined in the Setup Plugins screen under "Initialization Data". What the plugin does with this data or the type of data required is entirely up to the plugin developer. If a plugin requires multiple initialization parameters, the plugin developer may opt to use this data to point to the location of an INI file. This function should return a 0.
    • PHPI_Enable() returns integer.
      This function is called by PowerHome after the plugin is initialized and when PowerHome is ready for the plugin to be enabled. A plugin developer does not HAVE to directly do anything with this function but if the plugin runs tasks in the background, it is advised that they support the PHPI_Enable and PHPI_Disable functions to enable and disable plugin functionality. Even if the function is not supported (doesnt do anything) it MUST exist and return a value. You should return a 0 from this function.
    • PHPI_Disable() returns integer.
      This function is called by PowerHome prior to shutting PowerHome down and gives a plugin a chance to gracefully shutdown running processes. You should return a 0 from this function.
    • PHPI_Status() returns integer.
      This function should return the enabled or disabled status of the plugin. IF the plugin is enabled, this function should return a 1. If the plugin is disabled, the function should return 0.
    • PHPI_GetPIVersion() returns string.
      This function may be called by PowerHome to determine what version the plugin is. This value is particular to the plugin and is primarily used to display in the Help|About window. It is up to the plugin developer to return a value he deems appropriate.
    • PHPI_GetPIInfo() returns string.
      This function is also called by PowerHome during display of the Help|About window. The plugin developer is free to return whatever text he deems appropriate and is intended as a text description of the plugin.
    • PHPI_Close() returns integer.
      This function is called by PowerHome after PHPI_Disable prior to PowerHome shutting down. This is the last function to be called before PowerHome closes a plugin. This function should return a 0.
    • PHPI_Command(long lCMD, long lData1, long lData2, string sData3, string sData4) returns string.
      This function is the gateway into controlling the plugin from within PowerHome. This is the only function that is exposed to the user through the PowerHome function ph_picmd. The design is such that the Plugin developer will use the lCMD parameter to determine the type of command to be executed with lData1 thru lData4 representing data specific to the command. It is intended that the plugin developer use a construct such as a CASE statement to interpret the lCMD parameter and branch to the appropriate course of action. However, the plugin developer is free to use these parameters however he sees fit. The return value of this command will be passed back to the user through the ph_picmd function.
    • PHPI_SysCommand(long lCMD, long lData1, long lData2, string sData3, string sData4) returns string.
      This function is similar to the PHPI_Command function but is intended for internal use rather than directly by the user through PowerHome. This function is used to pass data from the PowerHome Plugin Passthru window with the wparam and lparam values in lData1 and lData2. The plugin developer is free to implement this function in whatever manner he deems appropriate.
    • PHPI_WebCmd(string sAction, integer iAuth, string sB64Auth, string sIP, string sParms) return string.
      This function is a users gateway into the plugin via the internal PowerHome webserver. This function must exist even if you don't plan to implement a web interface for your plugin. If you dont want a web interface, you may return an empty string or optionally a simple HTML message saying that the plugin does not have a web interface.ThisfunctionisactivatedviathePowerHomewebserverwitha/phpi-cgi/typeofURLcall.AstandardURLwouldappearsimilarto:http://127.0.0.1/phpi-cgi/PLUGIN_ID/command?param1=val1&parm2=val2. When a call similar to the above is made to the PowerHome webserver, the data will be passed to the plugin whose ID is PLUGIN_ID using the PHPI_WebCmd function. The "command" in the URL will be passed in the sAction variable and the current user authorization will be in the iAuth variable (0 - Unauthorized, 1 - Guest, 2 - Administrator). You can use the iAuth if you want to use the same security that the internal PowerHome webserver uses. If you wish to implement security separate from PowerHome's, then the sB64Auth will contain the Base64 authorization string that a user has entered. The sIP contains the IP of the user's machine and the sParms field will contain the parameters after the "?" mark in the sample URL above.
The above functions are the required minimum in order for a plugin to comply with version 1.2 of the PowerHome Generic Plugin SDK. In order for a plugin to be truly useful, it needs to have a mechanism to communicate with PowerHome. Since the language that PowerHome is written in (PowerBuilder) does not support the use of callback functions, an alternative method of communicating with PowerHome had to be devised. This was implemented via the use of Windows messages and a special form of the COPYDATASTRUCT. In order for this method to work, it's useful if the plugin developer also creates an internal function using this method to communicate with PowerHome. The details of this are explained below in the optional ph_formula function.
To make use of the plugin COPYDATASTRUCT, a standard COPYDATASTRUCT structure must be defined consisting of three 4 byte long values. The first long value contains a value of from 1000 to 1003 inclusive. If a value of 1000 is used, PowerHome will evaluate the accompanying formula using the currently loaded internal LOCAL and TEMP variables and wait for a return. If a value of 1001 is used, PowerHome will evaluate the formula using a newly created copy of LOCAL and TEMP variable values and wait for a return. A value of 1002 is the same as 1000 except that PowerHome returns immediately and the formula is queued. A value of 1003 is the same as 1001 and PowerHome returns immediately. The second long contains the length in bytes of the PowerHome formula to be evaluated. The third long contains the address in memory of the PowerHome formula to be evaluated. Once this COPYDATASTRUCT is initialized, it is sent to PowerHome using a standard windows message (remember the PowerHome handle that was passed in the PHPI_Init function). The event to send the COPYDATASTRUCT to is 74, the larpam should contain the PowerHome Index of the plugin (PHPI_Init), and the wparam must contain the address in memory of the COPYDATASTRUCT. PowerHome will then evaluate the formula pointed to by the COPYDATASTRUCT's third long variable and store the result within a COPYDATASTRUCT within PowerHome. The address of this COPYDATASTRUCT containing the formula result (type 1000 and 1001) will be returned from the "sendmsg" api call. You will need to use this returned address to access the COPYDATASTRUCT and parse out the formula return value. A sample ph_formula function in VB syntax is listed below:
Private Function ph_formula(ByRef sFormula As String, ByVal lType As Long) As String
'lType = 1000 - Use current PH variable set and wait for return
'lType = 1001 - Create new PH variable set and wait for return
'lType = 1002 - Use current PH variable set and return immediately
'lType = 1003 - Create new PH variable set and return immediately

Dim lRet As Long
Dim lLen As Long
Dim lPtr As Long
Dim sRet As String

cds.dwData = lType
cds.cbData = Len(sFormula)
cds.lpData = sFormula

lRet = SendMessage(hPwrHome, 74, iIndex, cds)

If lRet <> 0 Then
CopyMemAny lLen, lRet + 4, 4
CopyMemAny lPtr, lRet + 8, 4
sRet = Space(lLen - 1)
CopyMemStr sRet, lPtr, lLen
End If

ph_formula = sRet End Function
Plugin developers are free to interact with PowerHome through any of the available PowerHome control methods, but it is recommended to use the provided COPYDATASTRUCT method to evaluate formulas. PowerHome interacts with plugins using the ph_picmd function that is a direct link to the PHPI_Command plugin function. PowerHome also has a new trigger type of "Generic Plugin Trigger" with trigger numbers from 1 to 256 and trigger values from 1 to 256 giving a plugin a total of over 65,000 possible trigger combinations. A new PowerHome formula is provided for plugins to use called ph_pitrigger. It is intended for a plugin to call this PowerHome function whenever the plugin needs to raise a PowerHome trigger. The advantage to using this trigger is that PowerHome will actually convert the single function call into 4 separate trigger calls to include the [Any] options available in the Generic Plugin Trigger. Plugin developers are free to fire any triggers however using the ph_checktrigger function but are encouraged to use the Generic Plugin Trigger for plugin specific processes that do not fit within the current available trigger types.
Complete details of these processes as well as how to create a working plugin can be seen in the sample PowerHome plugins sourcecode available for download on the PowerHome website.


Skeleton

Plugin: Skeleton
Launch Data (ActiveX Classname): PowerHome_Plugin.phplugin
Initialization Data: None
This plugin is a generic skeleton plugin with no real value other than as a learning aid for creating actual plugins. The sourcecode is available as well as the complete VB project on the PowerHome download website. This plugin accepts 3 different command values from the ph_picmd function. Command 1 will cause the plugin to display a messagebox with the data passed in the data3 parameter. Command 2 will evaluate the data in data3 as a formula by passing the formula to PowerHome for evaluation. Command 3 will cause the plugin to fire the generic plugin trigger for command 1, option 1.


Alexa (fake Wemo)

Plugin: Alexa (fake Wemo)
Launch Data (ActiveX Classname): PH_AlexaWemo.phalexawemo
Initialization Data:A full path and filename to the plugin INI file. A base configuration INI file can be found in the plugins directory at c:\powerhome\plugins\phalexawemo.ini. Details on how to configure the INI are provided below.
This plugin provides the ability to control and interact with PowerHome using an Amazon Alexa and the smart home interface. Alexa supports a number of SmartHome technologies but the majority of them require an app specific to the technology to be installed as a plugin to your Alexa and then linking that plugin to your account for the specific technology. There are a couple of SmartHome protocols supported by Alexa that do NOT require installing a plugin and/or linking to an app/account for the technology. Those two protocols are the Philips Hue bridge and the Wemo device support. This plugin works by emulating Wemo devices that Alexa can control. A proper integration of PowerHome and Alexa (and hopefully Google Home) will be in the works but for now this plugin should suffice for basic control.
The plugin supports the creation of virtual Wemo devices that are either "plugs" or "dimmers" but Alexa only supports the functionality of plugs (on or off) for Wemo devices that are not linked to the Wemo app. What that means is that you'll be able to control devices with either on or off commands...you won't have access to dimmer or level commands. While the plugin supports status requests for the virtual devices, for some reason this is not supported by an Alexa device (Echo, Dot, etc) and is only supported in the Alexa app.
With each virtual Wemo device you define, you will give the device a "Name". This is the name you will use when speaking to Alexa to invoke an on or off command. For each virtual device you'll also be able to specify the actions you wish PowerHome to take for the "On", "Off", and "Status" commands. Each action can be one of several types: None, Device Control string, Macro ID, Formula ID, or Raw Formula. You can also specify whether a trigger will be fired for each action.
INI File Configuration:
The base configuration INI (c:\powerhome\plugins\phalexawemo.ini) is listed below:
[Setup]
devicecount=2
startingport=8200
;*leave upnpserverip blank to use any available IP
upnpserverip=
;*leave upnpdevices blank so that ALL devices below will have their UPNP info echoed back on an M-SEARCH
;To limit the M-SEARCH response to certain devices, enter a comma separated list of device numbers (no spaces)
;It is sometimes necessary to limit the number of devices as Alexa is not able to discover a large number of devices
;and may require you to discover them in groups.
upnpdevices=
;*debug=0 no debug trigger fired. debug=1 debug trigger is fired (command 255). debug=2 Error Exceptions trigger is fired (command 256). debug=3 Debug and Error triggers are fired.
debug=0
;*device actiontypes must be one of the values listed below
;0 = none
;2 = device status
;4 = macro
;6 = formula
;8 = raw formula
;add 1 to any of the above to fire a trigger (command num = device num, option 1 = On, option 2 = off, option 3 = status)
[device_1]
name=Kitchen Test Light
;*leave ip blank to use the default machine ip
ip=
;*set port to 0 or leave blank to use ports based off of startingport
port=
devicetype=0
actionontype=3
actionon=INSTEON+KITCHEN+ON
actionofftype=3
actionoff=INSTEON+KITCHEN+OFF
actionstatustype=3
actionstatus=INSTEON+KITCHEN
[device_2]
name=Family Room Test
Light
ip=
port=
devicetype=1
actionontype=3
actionon=INSTEON+FAMILYRM+ON
actionofftype=3
actionoff=INSTEON+FAMILYRM+OFF
actionstatustype=2
actionstatus=INSTEON+FAMILYRM
Keep in mind when reviewing the file above that the ";" character at the start of a line in an INI file indicates the line is a comment. It is not an actual part of the configuration. The first section you'll see is the [setup] section. You'll start by defining the total number of virtual Wemo devices you would like to emulate in the "devicecount" parameter. In the sample above, we've defined two virtual Wemo devices. The next parameter is the "port". Actual Wemo devices have each have a unique IP address and typically the same default port. In actual use, the Wemo device will change the port in use up and or down 1 or 2 values but for the most part what distinguishes one Wemo device from another is the IP address and not the port. In the Wemo emulator, the plugin is running on the PowerHome machine which would typically have a single IP address. To distinguish between multiple virtual devices, each device will have a unique port. Alexa doesnt really care that the IP address is the same and the port isnt in the standard range so this works well. The "port" parameter should be set with your starting port of the first virtual device. The plugin will then increment this port number for each subsequent device. If the starting port is 8200, then [device_1] will have port 8200, [device_2] will have port 8201, etc. Care should be taken that you don't reuse ports that may already be in use on the PowerHome machine depending upon how many virtual devices you have.
Emulating a Wemo device requires at least 2 servers. One is a UPNP (Universal Plug-n-Play) server that uses the UDP protocol that is used for device discovery. The other is the actual webserver that is built into each Wemo device and is what the "port" parameter is assigned to. Since the UPNP server uses a specific port, we use a single instance of this server to handle the UPNP requirements of ALL the virtual Wemo devices. The "upnpserverip" parameter allows you to specify the specific IP on the PowerHome machine that you want the UPNP server to be associated with. Since most machines will have a single IP, just leave this parameter blank to use the default.
The "upnpdevices" parameter is also usually left blank, especially during initial virtual Wemo device discovery and during normal use. When Alexa searches for "New Devices", it sends a special UPNP command that any listening device that matches the search term will respond to. UDP traffic is a connectionless protocol and essentially a "broadcast" and hope someone hears it. Since it is likely that you already have a fair amount of devices in your home that are UPNP compliant along with however many virtual Wemo devices you create, that can be ALOT of traffic and almost always, some of it is missed and unacknowledged. So if your Alexa is having a difficult time discovering ALL your virtual Wemo devices, you can set the "upnpdevices" parameter to a comma separated list of device numbers (the numbers of the devices you're having trouble discovering) that you wish to respond to the UPNP search command and having devices that have already been discovered NOT responding to help reduce traffic.
The last [setup] parameter is the "debug" parameter. In normal use (assuming everything is working properly), you'll set this to 0. If you are debugging issues, then you can set this parameter to either 1, 2, or 3 to fire "Debug" triggers, "Exception" triggers, or both Debug and Exception triggers. In these triggers you would typically log the [TEMP?] variables to a file or display them onscreen in a messagebox (trust me, logging to a file is easier with the amount of traffic).
After the [setup] section, you will have a [device_?] section for each device you've specified up to the "devicecount" parameter. The first parameter for a device is the "name" parameter. This is the name you'll use to invoke control from Alexay and should be unique from any other virtual Wemo device (or other actual devices that may be in use by Alexa). The "ip" parameter allows you to specify a specific IP to use for the device if you do have multiple IP's associated with your PowerHome machine. Usually you'll leave this parameter blank. The "port" parameter allows you to override the "startingport" parameter and specify a specific port that this virtual device will use. The "devicetype" parameter will be either 0 or 1. 0 is used to have the virtual device appear as a Wemo "plug" and 1 is used to have the device appear as a Wemo "dimmer". As stated earlier, Alexa does not support the "dimmer" functionality without being linked to the Wemo app so you can use either but probably best to just set to 0 for all devices.
The 6 remaining parameters for a device consist of 3 pairs of parameters. One pair for the "On" action, one pair for the "Off" action and one pair for the "Status" action. For each action type, you can use the values 0, 2, 4, 6, or 8 for the following action types: None, Device Control string, Macro ID, Formula ID, Raw Formula. For each action type, you can also add the value 1 to ALSO fire a Generic Plugin trigger when the Alexa invokes the action. After setting the action type, you'll then declare the actual action based upon the action type you chose.
Keep in mind that your actions DONT have to actually reflect an actual device. You can create a virtual device named "Good Night" and then have it fire a macro that performs any number of actions you choose.
Controller Commands supported:
The following controller commands are supported by this plugin and can be activated by using the ph_picmd( ) function:

Command | Parm1 | Description
0 | 0 | Returns a string listing all the parameters specified for all the devices configured (1 thru DeviceCount)
0 | 1 thru DeviceCount | Returns a string listing all the parameters for the specified Device number in Parm1
Generic Plugin triggers fired:
Command | Option | Description
1 thru DeviceCount | 1 | This trigger is fired when Alexa sends an "On" command to a virtual Wemo device that matches the Device Number specified in the Command parameter if the "On" Action Type for that device is set to fire a trigger (Action Type values 1,3,5,7,9).
1 thru DeviceCount | 2 | This trigger is fired when Alexa sends an "Off" command to a virtual Wemo device that matches the Device Number specified in the Command parameter if the "Off" Action Type for that device is set to fire a trigger (Action Type values 1,3,5,7,9).
1 thru DeviceCount | 3 | This trigger is fired when Alexa sends a "Status" command to a virtual Wemo device that matches the Device Number specified in the Command parameter if the "Status" Action Type for that device is set to fire a trigger (Action Type values 1,3,5,7,9).
255 | 1 | If the debug parameter is set to 1 or 3, this trigger fires when the HTTP server for a virtual Wemo device is successfully created.
255 | 2 | If the debug parameter is set to 1 or 3, this trigger fires when ALL the HTTP servers have been created for the virtual Wemo devices.
255 | 3 | If the debug parameter is set to 1 or 3, this trigger fires when the UPNP Listener server is successfully created.
255 | 4 | If the debug parameter is set to 1 or 3, this trigger fires when the UPNP server receives an M-SEARCH message.
255 | 5 | If the debug parameter is set to 1 or 3, this trigger fires if a matching Search Term from an M-SEARCH message is found.
255 | 6 | If the debug parameter is set to 1 or 3, this trigger fires when the UPNP server sends a response to an M-SEARCH message..
255 | 7 | If the debug parameter is set to 1 or 3, this trigger fires when a virtual Wemo device HTTP server accepts a request.
255 | 8 | If the debug parameter is set to 1 or 3, this trigger fires when a virtual Wemo device HTTP successfully receives a request.
255 | 9 | If the debug parameter is set to 1 or 3, this trigger fires when a virtual Wemo device HTTP server sends a response for SETUP.XML
255 | 10 | If the debug parameter is set to 1 or 3, this trigger fires when a virtual Wemo device HTTP server sends a response for SetBinaryState
255 | 11 | If the debug parameter is set to 1 or 3, this trigger fires when a virtual Wemo device HTTP server sends a response for GetBinaryState
255 | 12 | If the debug parameter is set to 1 or 3, this trigger fires when a virtual Wemo device HTTP server sends a response for unknown requests
255 | 13 | If the debug parameter is set to 1 or 3, this trigger fires when a virtual Wemo device HTTP server completes a response for an HTTP request
255 | 14 | If the debug parameter is set to 1 or 3, this trigger fires when a virtual Wemo device HTTP server sends a response for METAINFOSERVICE.XML
255 | 15 | If the debug parameter is set to 1 or 3, this trigger fires when a virtual Wemo device HTTP server sends a response for EVENTSERVICE.XML
256 | 1 | If the debug parameter is set to 2 or 3, this trigger fires if an exception occurs when trying to determine the plugin local IP
256 | 2 | If the debug parameter is set to 2 or 3, this trigger fires if an exception occurs when initializing an HTTP server for a Wemo device
256 | 3 | If the debug parameter is set to 2 or 3, this trigger fires if an exception occurs when initializing the UPNP server
256 | 4 | If the debug parameter is set to 2 or 3, this trigger fires if an exception occurs when receiving a UPNP multicast request
256 | 5 | If the debug parameter is set to 2 or 3, this trigger fires if an error occurs when sending a UPNP unicast response
256 | 6 | If the debug parameter is set to 2 or 3, this trigger fires if an exception occurs when sending a UPNP unicast response
256 | 7 | If the debug parameter is set to 2 or 3, this trigger fires if an exception occurs during an HTTP Accept
256 | 8 | If the debug parameter is set to 2 or 3, this trigger fires if an exception occurs during an HTTP Read
256 | 9 | If the debug parameter is set to 2 or 3, this trigger fires if an exception occurs during an HTTP Initial Send
256 | 10 | If the debug parameter is set to 2 or 3, this trigger fires if an exception occurs during an HTTP Callback Send


Caller ID

Plugin: Caller ID
Launch Data (ActiveX Classname): PH_CID.phcid
Initialization Data: The full path and filename pointing to the phcid.ini configuration file. The phcid.ini file will need to be edited to set the proper configuration. The first section to configure is the [config] section. Set the "port" value to the COM port your CID modem is listening to. The default settings of "9600,N,8,1" should be fine for most modems. There will be several "CIDInit" parameters with all but one commented out (preceeded with a semicolon). Select the CID Initialization parameter for your modem and make sure it is the only uncommented one. For a caller ID modem, set the "format" to 1. For a NetCallerID box, set the "format" to 2. "Lookupnames" can be set to 1 to have CID supplied names substituted with names of your choosing as defined in the [Names] section. A value of 0 will use CID supplied names. The [HangUp] section can be configured to optionally automatically hang up on user defined numbers.
This plugin provides Caller ID support within PowerHome. With a properly configured Caller ID modem or NetCallerID box, PowerHome will fire triggers when the phone rings based upon caller ID information. When a call comes in, the plugin will fire a generic plugin trigger on command 1, option 1 for all calls. The CID number will be in [TEMP5] and the CID name will be in [TEMP10]. If you have configured the CID plugin to hang up on certain numbers, calls that are hung up on will ALSO fire a generic plugin trigger on command 1, option 2. The same information will be available in the [TEMP] variables. In addition to the triggers, the plugin also provides support for directly communicating with the modem via the ph_picmd function. Command 1 and 2 are available in the CID plugin. Command 1 will send the string in data3 direct to the modem. This string can contain binary characters by escaping them with the "\" character followed by 3 digits for a decimal representation of the ASCII code or followed by an "x" and 2 digits for a hexadecimal representation of the ASCII code. Command 2 will send the string in data3 to the modem with no interpretation and will automatically embed a carriage return at the end.


Fake SMTP Server

Plugin: Fake SMTP Server
Launch Data (ActiveX Classname): PH_SMTPServer.phsmtpserver
Initialization Data: A full path and filename to the PH_SMTPServer ini file. A base configuration INI file can be found in the plugins directory at c:\powerhome\plugins\smtpserver.ini. Details on how to configure the INI are provided below.
This plugin emulates an actual SMTP (Simple Mail Transport Protocol) server but does NOT send email on its own and instead fires triggers within PowerHome when applications attempt to send email through the plugin. This is useful for interfacing with software and hardware that doesnt provide another viable interface for communicating with PowerHome but does provide for sending SMTP email messages. You can then configure the software/hardware to use this plugin as the SMTP server so PowerHome can be notified of events. The data that is sent to the PowerHome triggers can then be used to construct and send an actual email using PowerHome internal function as well as performing other desired actions.
INI File Configuration:
The base configuration INI file contents will appear like this:
[setup]
ip=10.0.2.15
port=25
emailcount=1
[email_1]
address=dhoward@myx10.com
subjectcount=2
subject_1=test
subject_2=
In the setup section, set the IP parameter to the IP of the machine that PowerHome (and the plugin) is running on. This will be the IP you'll configure the remote hardware/software to point to as the SMTP server. Set the Port to the value you wish the SMTP server to listen to. The default port for SMTP traffic is 25.
The plugin works by comparing the "To Address" and the "Subject" to the values in the INI file and looking for matches. The remote hardware/software that is attempting to send email will provide these values to the SMTP server. You can distinguish between multiple different software/hardware devices attempting to send email by the To Address and Subject you configure them to use. If you have multiple different email accounts that SMTP will attempt to send to, specifiy the total number of unique addresses in the [setup]emailcount parameter.
For each email address you specified in the "emailcount" parameter, you'll have a corresponding [email_?] section. If your emailcount parameter is set to 2, then you'll have an [email_1] and [email_2] section. With each section, you'll set the "address" parameter to the email address you wish to monitor for.
Within an email section, you define your subjects. Set the "subjectcount" parameter to the total number of subjects you want to match on. If you set the subjectcount parameter to 3, you'll have 3 "subject_?" parameters beneath it: subject_1, subject_2, and subject_3. You'll set the subject_? parameters to the subject data you wish to match on.
When an email is attempted to be sent through the SMTP server plugin, it will first gather the full email information (To Address, From Address, Subject, Email Body). It will then sequentially try to do an exact match on the "To Address" to the address parameter in each [email_?] section starting with the first section and continuing. When a match is found, the plugin will then loop through and try to match the subject. This match is done by taking the "subject_?" text checking to see if it is contained within the Subject that was sent by SMTP. If the SMTP subject is "Alert: Motion detected!" then a subject_? parameter set to "Motion" (or "Alert" or "Motion detected", etc) will result in a match. Once a match is found, a PowerHome Generic Plugin trigger will then be executed. Once a match is found and the trigger is sent, then the loop and comparison will be terminated and the plugin will wait for the next SMTP email. If you wish to match on ANY subject, leave the "subject_?" parameter blank.
Controller Commands supported:
None
Generic Plugin triggers fired:
When an SMTP email / subject combination is matched, a Generic Plugin trigger will be fired with the "Trigger ID Number" column "Command ?" matching the [email_?] number that was matched. The "Trigger Value" column "Option ?" will match the "subject_?" number that was matched. When the trigger is fired, the [TEMP5] system variable will contain the IP of the client sending the SMTP followed by a tab followed by the From Address followed by a tab followed by the To Address. The [TEMP10] variable will contain the SMTP email message body.


File Monitor

Plugin: File Monitor
Launch Data (ActiveX Classname): PH_FileMon.phfilemon
Initialization Data: Enter the full path and filename of the INI file for this particular instance of the File Monitor plugin. If you're using the defaults, then this value will be: c:\program files\powerhome\plugins\phfilemon.ini
The PowerHome File Monitor plugin allows the user to specify up to 256 files to monitor for changes. It does this by monitoring the date/time stamp of the file. Any change to a monitored files date/time stamp will cause the plugin to fire an appropriate Generic Plugin trigger. If more than 256 files need to be monitored, then another instance of the plugin can be loaded for an additional 256 files to be monitored. Since the plugin runs in it's own thread, it takes no PowerHome resources.
Configuring the phfilemon.ini file:
  1. Open the phfilemon.ini file in Notepad. You'll need to configure the File Monitor plugin by modifying this file.
  2. Under [Setup] section, set the "FileCount" parameter to the number of files you will be defining in the INI file for monitoring.
  3. Under the [Files] section, set the full path and filename of the files you wish to monitor. If you wish to monitor 3 separate files, you will set the FileCount parameter to 3 and you will have 3 parameters beneath the [Files] section running from File1 to File3.
  4. Once you've finished editing your INI file, close and save the file.
Using the PowerHome File Monitor Plugin:
  • The File Monitor plugin will fire Generic Plugin triggers anytime a change is detected on any of the monitored files. The trigger fired will be "Command 1" and the "Trigger Value" will match the File Number of the monitored file. For example, if "File2" in the INI file is "c:\program files\powerhome\pwrhome.ini" and this file changes, the plugin will fire a Generic Plugin trigger on the Plugin ID, Command 1, Option 2 (Option 2 for File 2). The [TEMP5] variable will contain the datetime of the modified file and [TEMP10] will contain the path and filename of the modified file.
  • The File Monitor plugin also allows for a small selection of commands to be sent to it using ph_picmd function. The allowed command numbers are:
    1. Retrieve number of monitored files.
      lData1 = Unused
      lData2 = Unused
      sData3 = Unused
      sData4 = Unused
      Returns the number of monitored files.
    2. Retrieve the path/filename of a specified monitored file.
      lData1 = The filenumber of file to be returned.
      lData2 = Unused
      sData3 = Unused
      sData4 = Unused
      Returns the full path/filename of the specified file number. If the file number is out of range, 998 will be returned.
    3. Add a new file to be monitored into the first available spot. A spot is considered available if the path/filename is empty.
      lData1 = Unused
      lData2 = Unused
      sData3 = The full path and filename of the file to be added for monitoring.
      sData4 = Unused
      Returns the filenumber that the file was added to.
    4. Change an -existing monitored filenumber to a new path and filename.
      lData1 = The file number to change
      lData2 = Unused
      sData3 = The full path and filename of the new file to be to be monitored.
      sData4 = Unused
      Returns the filenumber that was changed. 998 is returned if the file number is out of range. To stop a file from being monitored, set it's filenumber path and filename to an empty string.
  • A 999 will be returned for any unsupported commands.


FireTV Control via ADB

Plugin: FireTV Control via ADB
Launch Data (ActiveX Classname): PH_FireTV.phfiretv
Initialization Data: A full path and filename to the plugin INI file. A base configuration INI file can be found in the plugins directory at c:\powerhome\plugins\firetv.ini. Details on how to configure the INI are provided below.
This plugin provides control over Amazon FireTV devices using the ADB debug control protocol. To use this plugin, you must have ADB (Android Debug Bridge) installed and you must configure your FireTV to allow for ADB debugging. You can find information on how to do this here: https://developer.amazon.com/docs/fire-tv/connecting-adb-to-device.html .
INI File Configuration:
The base configuration INI file contents will appear like this:
[settings]
ip=192.168.0.128
adbpath=C:\android_sdk\adt-bundle-windows-x86-20130522\sdk\platform-tools
kill=yes
Set the IP parameter to the IP of your FireTV device. It is best if you can configure a static DHCP address for your FireTV so that the IP does not change. Set the "adbpath" parameter to the full path where the ADB.EXE file can be found. The "kill" parameter should be set to either "yes" or "no". If set to "yes", then the plugin will attempt to kill the ADB server whenever the plugin is enabled or disabled. Killing the ADB server helps with problems where the ADB server is sometimes hung.
Controller Commands supported:
The following controller commands are supported by this plugin and can be activated by using the ph_picmd( ) function. Instead of using the "command" parameter and supplying a command number, this plugin uses the "parm3" parameter to differentiate between the different commands using the strings below:

Parm3 Command | Description
killserver | Sets the "kill" flag (same as the INI file parameter) to either "yes" or "no". The value you wish to set is int the Parm1 parameter. Use 0 for "no" and any other value for "yes".
up | Sends an up arrow command
down | Sends a down arrow command
left | Sends a left arrow command
right | Sends a right arrow command
enter | Sends an Enter or Select command
select | Same as the "enter" command above
back | Sends a back command
home | Sends a home command
menu | Sends a menu command
play | Sends a play command
pause | Sends a pause command
prev | Sends a previous command
next | Sends a next command
power | Sends a Power command
volup | Sends a Volume Up command
voldn | Sends a Volume Down command
delete | Sends a delete command
tab | Sends a tab command
key | Sends a keystroke(s). The key to send will be in the Parm4 parameter. If multiple characters appear in the string passed in Parm4 then the characters will be sent sequentially one at a time.
Generic Plugin triggers fired:
None


MQTT

Plugin: MQTT
Launch Data (ActiveX Classname): PH_Mqttpi.phmqttpi
Initialization Data: A full path and filename to the plugin INI file. A base configuration INI file can be found in the plugins directory at c:\powerhome\plugins\phmqttpi.ini. Details on how to configure the INI are provided below.
This plugin provides support for MQTT (Message Queue Telemetry Transport) protocol. This technology is in use by a large number of IOT (Internet Of Things) devices and even be implemented in your own DIY projects such as those based upon Arduino or ESP8266/ESP32 devices. Before using this plugin, you must first have setup and configured an MQTT broker. To learn more about MQTT, please visit the homesite at http://mqtt.org
The PowerHome MQTT plugin (as well as the PowerHome MQTT controller) make use of the open source M2Mqtt C# code written by Paolo Patierno to handle the low level MQTT transactions and protocol. You can find the M2Mqtt sourcecode repository here: https://github.com/eclipse/paho.mqtt.m2mqtt and you can find the M2Mqtt homepage here: https://m2mqtt.wordpress.com/
In order to use the MQTT protocol in your environment, you must first install and setup an appropriate MQTT Broker (Server) which acts as a central hub for all MQTT incoming and outgoing messages. There are a number of free brokers available for a variety of platforms. One of the most popular ones is Mosquitto and can be installed on the PowerHome machine itself. You can learn more about this broker at its homesite at https://mosquitto.org. As an alternative to installing and running your own MQTT broker, you can make use of any number of brokers that are available on the web.
PowerHome supports MQTT via this plugin and the PowerHome MQTT controller. You can use one or the other or both of them at the same time. A common use would be to use the PH MQTT controller for device status/update in the Analog IO screen and the MQTT Plugin for all other tasks.
INI File Configuration:
The base configuration INI file contents will appear like this:
[setup]
host=192.168.0.125
port=1883
secure=0
cacert=
clientcert=
sslprotocol=0
clientid=PH MQTT Plugin
userid=
password=
willflag=
willtopic=
willqos=
willretain=
willmessage=
cleansession=
keepaliveperiod=
publishprefix=
subscribeprefix=
subscribecount=4
options=0
[subscribe_1]
topicfilter=#
qos=0
actiontype=1
action=
[subscribe_2]
topicfilter=ph/lights/+
qos=0
actiontype=9
action=ph_msgbox("Variables",ph_returnallvars(6),90)
[subscribe_3]
topicfilter=ph/test/+/light
qos=0
actiontype=1
action=
[subscribe_4]
topicfilter=+/+/#
qos=0
actiontype=1
action=
A number of the parameters in the [Setup] section of the INI file are the same as for the MQTT Controller. The Host and Port parameters should be set to the IP and Port of your MQTT broker. If your broker is configured for secure communications (SSL/TLS), then set the Secure parameter to 1. Otherwise set to 0. If you set the Secure parameter to 1, then you must supply the CA Certificate and Client Certificate in the CACert and ClientCert parameters. If the Secure parameter is 0 (for no secure communications), then set the SSLProtocol parameter to 0. If the Secure parameter is 1, then set the SSLProtocol parameter to the number representing the SSL/TLS protocol in use by the broker (0 - None, 1 - SSL v3, 2 - TLS v1.0, 3 - TLS v1.1, 4 - TLS v1.2)
Set the ClientID to a unique identifier (unique within the broker) to identify your the plugin instance of the MQTT client. If you are also running the MQTT Controller (or multiple instances of the MQTT Plugin, you must make the ClientID different within each instance if they are connecting to the same broker). If your broker requires a userid/password, then set those values in the UserID and Password parameters.
The MQTT protocol allows for a "Will" message for a client. More information can be found on the MQTT site. Basically it is a topic/message that is the last data that will be sent when the client disconnects. If you want a "Will" message, set the WillFlag parameter to 1. In not, then set it to 0. If you set the WillFlag to 1, then you need to specifiy values for the WillTopic, WillQOS, WillRetain, WillMessage parameters.
Set the CleanSession as appropriate to either 1 (CleanSession = true) or 0 (CleanSession = false). Basically, setting the CleanSession flag to false means that the broker will save the client session on disconnection (subscribed topics, messages for these topics delivered on reconnection). If you set the CleanSession flag to true (usually the default), the broker will NOT retain data to be sent to the client when it reconnects.
Set the KeepAlivePeriod to an appropriate value in seconds. Setting this parameter to 0 disables the Keep Alive mechanism. The default value is 60 (seconds). This parameter is the maximum amount of time for no communication (either way) between the broker and the client to occur before the client will be disconnected.
Set the PublishPrefix and SubscribePrefix parameters to appropriate values if you always want to have a set "prefix" for your topics. If you don't want prefixes, you can leave these parameters blank.
The Options parameter is not a part of MQTT and instead controls how the plugin works. This parameter is a flags parameter where you add the desired values together to a total. A value of 1 indicates that the plugin will fire "Status" triggers when they occur. Status triggers are fired when the MQTT connection is closed, a message is published, a topic is subscribed, or a topic is unsubscribed. This value would typically be used during initial debugging to determine if these events are occurring properly. A value of 2 tells the plugin to fire "Exception" triggers. An exception trigger occurs whenever an exception occurs within the plugin. Normally there shouldnt be exceptions but this option may be handy for debugging purposes or to catch when an exception occurs in normal use. In normal use scenarios, you would usually set the Options parameter to either 0 or 2. In a debug scenario, a value of 3 (1 + 2) would be the preferred setting.
The last parameter to be concerned with is the SubscribeCount. Set this parameter to the number of topics you wish the plugin to subscribe to and to be configured in the following [subscribe_?] sections. If you wish to subscribe to 4 topics, then you'll have [subscribe_1], [subscribe_2], [subscribe_3], and [subscribe_4] sections.
Each [subscribe_?] section has 4 parameters with the TopicFilter and QOS parameters being self explanatory if you're familiar with the basics of the MQTT protocol. The ActionType and Action parameters instruct the plugin what to do when a message is received on one of the subscribed topics. The ActionType parameter is a flags parameter where you the values together to get the desired total value. A value of 2 indicates that the Action is a Device Control string. A value of 4 indicates that the Action is a Macro ID. A value of 6 indicates that the Action is a Formula ID. A value of 8 indicates that the Action is a raw formula. You will ONLY use 1 value from the 2, 4, 6, 8 action option values. To the action value you've chosen, you may add a 1 to have the plugin also fire a trigger within PowerHome. If you ONLY want a trigger to be fired when a message is received on a topic, set the ActionType to 1. If you wanted to fire a trigger AND execute a Device Control string, set the ActionType to 3, etc. The Action parameter will be set to the value that corresponds with your chosen ActionType (blank if you didnt choose an action type option (2, 4, 6, or 8).
Controller Commands supported:
Command | Parm1 | Parm2 | Parm3 | Parm4 | Description
0 | 0 |  |  |  | Return details on all Subscribed topics
0 | 1 thru SubscribeCount |  |  |  | Return details on Subscribed topic number specified in Parm1
1 | 0 |  |  |  | Return all configuration INI parameters in the [Setup] section (except for Password)
1 | 1 |  |  |  | Return the [Setup]Host parameter
1 | 2 |  |  |  | Return the [Setup]Port parameter
1 | 3 |  |  |  | Return the [Setup]Secure parameter
1 | 4 |  |  |  | Return the [Setup]CACert parameter
1 | 5 |  |  |  | Return the [Setup]ClientCert parameter
1 | 6 |  |  |  | Return the [Setup]SSLProtocol parameter
1 | 7 |  |  |  | Return the [Setup]ClientID parameter
1 | 8 |  |  |  | Return the [Setup]UserID parameter
1 | 9 |  |  |  | Return the [Setup]WillFlag parameter
1 | 10 |  |  |  | Return the [Setup]WillTopic parameter
1 | 11 |  |  |  | Return the [Setup]WillQOS parameter
1 | 12 |  |  |  | Return the [Setup]WillRetain parameter
1 | 13 |  |  |  | Return the [Setup]WillMessage parameter
1 | 14 |  |  |  | Return the [Setup]CleanSession parameter
1 | 15 |  |  |  | Return the [Setup]KeepAlivePeriod parameter
1 | 16 |  |  |  | Return the [Setup]PublishPrefix parameter
1 | 17 |  |  |  | Return the [Setup]SubscribePrefix parameter
1 | 18 |  |  |  | Return the [Setup]SubscribeCount parameter
1 | 19 |  |  |  | Return the [Setup]Options parameter
2 | 1 thru SubscribeCount | 0 |  |  | Return the Subscribed Topic for the [Subscribe_?] specified in Parm1
2 | 1 thru SubscribeCount | 1 |  |  | Return the Subscribed QOS for the [Subscribe_?] specified in Parm1
2 | 1 thru SubscribeCount | 2 |  |  | Return the Action Type for the [Subscribe_?] specified in Parm1
2 | 1 thru SubscribeCount | 3 |  |  | Return the Action for the [Subscribe_?] specified in Parm1
3 | 0 |  |  |  | Unsubscribe from all topics and then Subscribe to all topics
3 | 1 |  |  |  | Unsubscribe from all topics
3 | 2 |  |  |  | Subscribe to all topics
3 | 3 | 1 thru SubscribeCount |  |  | Unsubscribe from topic specified in Parm2
3 | 4 | 1 thru SubscribeCount |  |  | Subscribe to topic specified in Parm2
4 | 0, 1, or 2 (QOS) | ActionType value | Topic filter | Action string | Adds an "on the fly" topic subscription (not described in the INI file) to the current list of subscribed topics. See the INI configuration info above for the values to use for the Parm? fields
5 | 1 thru SubscribeCount | ActionType value | Topic filter | Action string | Update/Change the Subscribe parameters for the Subscribe topic number specified by Parm1. The QOS will be 0
6 | 1 thru SubscribeCount | ActionType value | Topic filter | Action string | Update/Change the Subscribe parameters for the Subscribe topic number specified by Parm1. The QOS will be 1
7 | 1 thru SubscribeCount | ActionType value | Topic filter | Action string | Update/Change the Subscribe parameters for the Subscribe topic number specified by Parm1. The QOS will be 2
8 |  |  | Topic filter |  | Searches the subscribed topic filters for a match with the topic filter specified in Parm3 and returns the index number if found. If not found, returns 0
10 | 0 |  |  |  | Returns 1 if the MQTT client is connected, 0 otherwise
10 | 1 |  |  |  | Returns 1 if CleanSession is true, 0 if false
10 | 2 |  |  |  | Returns the Client ID
10 | 3 |  | "get" |  | Returns 3 if the MQTT client version in use is 3.1. Returns 4 if the MQTT client version in use is 3.1.1
10 | 3 | 3 or 4 | "set" |  | Sets the MQTT client version to 3.1 if Parm2 = 3 and 3.1.1 if Parm2 = 4
10 | 4 |  |  |  | Return the MQTT client Attempts On Retry value
10 | 5 |  |  |  | Return the MQTT client Delay On Retry value
10 | 6 |  |  |  | Return the MQTT client InFlight Queue size
10 | 7 |  |  |  | Return the MQTT client Port
10 | 8 |  |  |  | Return the MQTT SSL Port
10 | 9 |  |  |  | Return the MQTT client Timeout on Connection value
10 | 10 |  |  |  | Return the MQTT client Timeout on Receiving value
10 | 11 |  |  |  | Return the MQTT client Will Flag value
10 | 12 |  |  |  | Return the MQTT client Will Topic
10 | 13 |  |  |  | Return the MQTT client Will QOS
10 | 14 |  |  |  | Return the MQTT client Will Message
100 | 0, 1, or 2 (QOS) | 0 or 1 (Retain flag) | Publish Topic | Publish Message | Publish a message using the values in the supplied parameters
Generic Plugin triggers fired:
Command | Option | Description
1 thru SubscribeCount | 1 | This trigger is fired if the ActionType for the Topic filter that is matched to an incoming message is set to fire a trigger (Action Type values 1,3,5,7,9). The Command parameter will be set to the [subscribe_?] index number that matches the incoming message. An incoming message MAY match multiple subscribed topics and a trigger (with the appropriate Command value) will be fired for each match.
255 | 1 | Fired when the MQTT client connection is closed
255 | 2 | Fired whenever the plugin MQTT client successfully Publishes a message to a Topic
255 | 3 | Fired whenever the MQTT client successfully Subscribes to a Topic
255 | 4 | Fired whenever the MQTT client successfully UnSubscribes from a Topic
256 | 1 | Fired when an exception occurs when trying to determine the plugin local IP
256 | 2 | Fired when an Invalid Topic Filter exception occurs
256 | 3 | Fired when an exception occurs with creating the MQTT client object
256 | 4 | Fired when an exception occurs with the MQTT client connecting to the broker
256 | 5 | Fired when an exception occurs with the MQTT client disconnecting from the broker
256 | 6 | Fired when an exception occurs with destroying the MQTT client object
256 | 7 | Fired when an exception occurs when Subscribing to an MQTT Topic
256 | 8 | Fired when an exception occurs when UnSubscribing to an MQTT Topic


Raw COMM

Plugin: Raw COMM
Launch Data (ActiveX Classname): PH_Comm.phcomm
Initialization Data: The COM port, a space, the comma separated settings string. Can be left blank to establish a connection manually. In all cases where a "settings" string is required, it consists of the BPS, the data bits, the parity, and the stop bits all separated by commas. An example of 9600 BPS, 8 data bits, No parity, and 1 stop bit would be: 9600,N,8,1
This plugin provides raw COM port functionality for PowerHome. If a COM port and settings string is supplied in the Init Data parameter then the connection will be established when the plugin is loaded. Several commands are available using the ph_picmd function. Command 1 will send the string in data3 out the COM if a connection is already established. This string can contain binary characters by escaping them with the "\" character followed by 3 digits for a decimal representation of the ASCII code or followed by an "x" and 2 digits for a hexadecimal representation of the ASCII code. Command 2 will send a single character represented by the ASCII value contained in the data1 parameter (assuming the COM is connected). Command 3 will manually connect to the COM port in data1 using the settings supplied in data3 (you must be disconnected first). Command 4 disconnect the COM port if already connected. Command 5 will return the current connection status (0 = connected, 1 = disconnected). Command 6 will return the COM port. Command 7 will return the settings.
This plugin will also fire a generic plugin trigger whenever data is received on a connected COM port. The trigger fired will be command 1, option 1 with the length of the data, the string data with binary characters escaped, and the string data with ALL characters escaped available in the [TEMP] variables.


Raw Socket

Plugin: Raw Socket
Launch Data (ActiveX Classname): PH_Socket.phsocket
Initialization Data: A total of up to 3 parameters each separated by a single space character. The first parameter is the IP to connect to, the second parameter is the Port, and the third parameter is a flag of either 0,1, or 2 controlling the use of escape sequences within received data. If you omit the third parameter, a value of 0 is assumed. You also have the option of leaving the initialization data blank and manually connect later through controller commands after PowerHome and the plugin have been loaded. An example of initialization data might look like: "192.168.0.11 8200 1" without the quotes.
This plugin provides raw socket connectivity for PowerHome. If parameters are supplied in the Init Data, then a connection will be established when the plugin is loaded. Otherwise, you can initiate a connection manually using the ph_picmd function after the plugin is loaded.
Controller Commands supported:
Command Number | Description
1 | Writes data to the socket. Parm1 contains a timeout value in seconds. For no timeout, use 0. Parm3 contains the data you wish send.
2 | Applies new Initialization Data and connects the socket. Socket must not already be connected. Parm1 contains the port. Parm2 contains the escape sequence flag (0, 1, 2). Parm3 contains the IP.
3 | Disconnects the socket
4 | Returns the connection status. Returns "0" if connected. Returns " -2" if disconnected
5 | Returns the current IP for the socket
6 | Returns the current Port for the socket
7 | Returns the current Escape flag
8 | Sets a new value for the Escape flag. Parm1 contains the new value
9 | Forcibly disconnect socket
10 | Writes data to the socket but allows for the passing of escape characters. A character is escaped by using the "\" character followed by a 3 digit decimal number representing the ASCII value of the character or using the "\" character followed by an "x" followed by a 2 digit hexadecimal number representing the ASCII value. Parm1 contains the timeout in seconds (Use 0 for no timeout) and Parm3 contains the data to send with special characters escaped.
11 | Returns the current socket timeout value
12 | Set the socket timeout value. Timeout value is in Parm1
13 | Returns the current "Mode". The mode is a number of 0, 1, or 2 and represents how the plugin alerts PowerHome of events (Error, Data received, etc). A value of 0 (default) will fire a plugin trigger. A value of 1 will fire a PowerHome Windows event which can be intercepted by a PowerHome trigger. A value of 2 will result neither a trigger or a Windows event.
14 | Sets the current "Mode"
100 | Returns the current data in the receive buffer
101 | Returns the last error number
102 | Returns the last error string
Generic Plugin triggers fired (when Mode = 0):
Command | Option | Description
1 | 1 | Fires when data is received by the socket.
1 | 2 | Fires when the socket connect
1 | 3 | Fires when the socket disconnects
1 | 4 | Fires when an error occurs
Escape flag values:
The Escape flag parameter accepts values of either 0, 1, or 2 and controls how data received by the socket is "escaped". PowerHome is not able to handle non-printable ASCII characters so if you need to see these characters, they must be escaped. A value 0 tells the plugin to NOT escape out of range ASCII characters. Any character outside of the ASCII values of 9, 10, 13, or the range 32 to 125 will simply be dropped from the received data. A value 1 tells the plugin to escape the out of range characters. Characters outside the range of ASCII values 9, 10, 13, the range 32 to 125, and the "\" character (92) will be escaped by a "\" followed by a 3 digit decimal ASCII value. The ASCII character represented by decimal 15 would be escaped as \015 if the escape value is 1. An escape value 2 tells the plugin to escape EVERY character received by the socket. This parameter has nothing to do with how characters are sent to the socket. Whether characters that are written to the socket are escaped or not is controlled by the controller command number. See commands 1 and 10 above.
Mode values:
The Mode value is initially set to 0 but can be changed either 0, 1, or 2 by controller command 14. A Mode value of 0 (the default) tells the plugin to fire one of the generic plugin triggers above when an event occurs. A value of 1 tells the plugin to instead send a Windows command to the main PowerHome window handle allowing for the firing of a "WM_USER" Trigger Type and a "Trigger 1" Trigger ID. The TEMP3 system variable will contain the Index of the plugin (this is determined by the order the plugin is loaded. The first plugin loaded is index 1, the second is index 2, etc. The load order is determined by the "Load Order" column in the "Setup Plugins" screen. The TEMP4 variable will contain a value matching the Option value in the Generic Plugin triggers table above. For example, if the plugin has a "Load Order" of 40, the Mode value is 1, and data is received by the socket, a Windows message will be posted to the PowerHome window allowing a trigger of type WM_USER with a trigger ID of "Trigger 1" to be fired. The TEMP3 system variable will contain the number 4 (Load Order / 10)and the TEMP4 variable will contain the number 1 (Option 1 in the Plugin table is fired when data is received). A Mode value of 2 tells the plugin to NOT fire a Generic Plugin trigger nor a post a Windows message. PowerHome will receive no notification of incoming data, connect, disconnect, or errors.


UDP Listener

Plugin: UDP Listener
Launch Data (ActiveX Classname): PH_UDPListener.phudp
Initialization Data: The UDP port to listen on
This plugin listens for UDP broadcasts on the specified port. There are no commands accessible using the ph_picmd function. UDP broadcasts received on the specified port will cause the plugin to fire a generic plugin trigger on command 1, option 1. Data available in the [TEMP] variables will be the port the UDP was received on, the UDP message, and the IP address of the device originating the UDP message. If you need to listen for UDP broadcasts on multiple ports, create a plugin entry for each port.


URL Scraper

Plugin: URLScraper / URLScraper1
Launch Data (ActiveX Classname): PH_URLScraper.phurlscraper or PH_URLScraper1.phurlscraper1
Initialization Data: Enter the full path and filename of the INI file for the URLScraper plugin. If you're using the current PH release version defaults, then this value will be: c:\powerhome\plugins\urlscrape.ini

The PowerHome URL Scraper plugins (URLScraper and URLScraper1) are designed to parse data from designated web pages, in a manner similar to the ph_regex() family of string search functions, except that the scraper plugins run in the background in their own independant thread, and take no PowerHome resources.

The preferred scraper is "URLScraper" which is the most general scraper implementation which uses the Catalyst HTTP Control functions. In rare instances where a unique website is incompatible with the Catalyst HTTP Control for some reason, the alternative URLScraper1 that uses raw socket communications is available, and will generally be successful.

The regex search that is done uses the VBScript regular expression engine (the same that is used in the new ph_regex2 functions). Full details, and good tutorials, on the protocol can be found here ...

http://www.regular-expressions.info/quickstart.html

Using the PowerHome URLScraper Plugins:

To use the scraper the Plugin must be ...
1) defined in PowerHome Explorer>Setup>Plugins,
2) the default initialization file "c:\powerhome\ plugins\urlscraper.ini" needs to be modified or replaced, and
3) a trigger event created in the PowerHome Explorer Triggers table (to call a Macro, or other Action).

Defining the urlscraper.ini file:

A definition for the URLScraper1 plugin must be entered in the PowerHome Explorer>Setup>Plugins table as follows (the 'Load Order' number doesn't have to be as exampled below. Any sequence number, is appropriate). See following discussion regarding the use of "URLScraper" or "URLScraper1".

The example image below shows both plugin versions defined for reference purposes, although normally only one would be used.

plugin definition

Configuring the urlscraper.ini file:
  • Open the "c:\powerhome\ plugins\urlscraper.ini" file in Notepad. You'll need to configure the URLScraper plugin actions by modifying that file.
  • The scraper .ini file is comprised of two main parts (see example below), one of which may be repeating depending on the number and complexity of the "scrapes."

    The 1st section is the [config] area, which has a single entry that defines how many different URL's will be defined to be searched. The urlcount parameter can be up to a maximum of 10. If you need to scrape more than 10 URL's, you can declare another instance of the scraper in the Setup Plugins table (ie, URLSCRAPER2). See also, above image.

    The 2nd section is comprised of a primary [URL_x] and one, or more, secondary sub-sections [URL_x_y].

    The Primary part defines the URL address (eg, news.google.com), how often (in minutes) that URL is to be scanned, and the number of 'scrapes' to be applied to the URL

    Since the urlcount can be 10, or less, there can thus be primary URL sections from URL_1 to URL_10.

    (There can be an unlimited number of scrapes (eg, [URL_1_113] would be possible.) The number of matches (or snaps) is determined by the number of () parenthesis snap blocks within a scrape. The examples below only show a single snap per scrape but you can have up to five (5) multiple snaps per scrape. Within a single scrape, the individual snaps will be placed in the LOCAL variables (LOCAL1 thru LOCAL5) in the same order as found.

    In addition to the LOCALs, all of the snaps within a scrape will also be placed concatenated together in the TEMP5 variable with a separator of <|> between each snap ( ie, "wind<|>15<|>" ).

    Here is a weather data extraction Example that pulls five (5) snaps off a page.

    [URL_1_1]
    regexsearch=<div id="main">[\s\S]*?<span>(.+)</span>[\s\S]*?<h4>(.+)</h4>[\s\S]*?<label>Wind:</label>[\s\S]*?<span>[\s\S]*?<span>(.+)</span>[\s\S]*?<label>Humidity:</label>[\s\S]*?<div class="b">(.+)</div>[\s\S]*?<div id="details1">[\s\S]*?<p>(.+)</p>
    regexoccur=1
    regexflags=0
    Each sub-section (as exampled in the image above) defines the regex search string, along with two parameters.

    The regexoccur defines which (if multiple) occurrences of the regex match is to be returned. If an HTML had the <td>Temperature</td>random text<b>78</b> multiple times and you wanted to return the value contained in the 3rd occurrence, then you would set the regexoccur parameter to 3. Take for example this snippet:

    <td>Temperature</td><br>Apopka: <b>78</b><br>
    <td>Temperature</td><br>Orlando: <b>79</b><br>

    A regexoccur of 1 will return the temperature for Apopka. A regexoccur of 2 will return the temperature for Orlando. The regex search string of...

    <td>Temperature</td>[\s\S]*?<b>(.+)</b>

    will match both entries but if you want the second one, you need to change the regexoccur parameter (or change the regex search itself to specifically state Orlando).

    In the weather data INI code above, the regexsearch looks for <div id="main"> then skips over everything, with the [\s\S]*? which matchs any text that appears up to the next <span> tag.

    The [\s\S] matches "\s" any "whitespace" character (ie, space, tab, line break, form feed) and the "\S" matches any non-whitespace character (ie, all characters).

    The *? makes this a non-greedy (ie, lazy) search that stops at the first match found.

    The (.+) denotes that everything between the "</span"> and "</h4>" tags be "snapped" out of the data string (the temperature in this case) for this regex search. This is a greedy search that will find the last occurance on a line. We are safe using it here because there are no data repeats before the next Return code.

    The default regexflags parameter of 0, can have a 1, or 2 (or both) added to it, where the "1" determines case sensitivity, and a "2" determines plugin trigger firing conditions, as follows ...
  • Adding 1 makes the search case sensitive, otherwise searches are case insensitive.
  • Adding 2 causes the plugin to ONLY fire the generic plugin trigger if the snapped value has changed (the plugin stores the last "snap" of each scrape and if the new "snap" is different from the last snap, then the trigger will be fired. If 2 is not added to the flags parameter, then the trigger will fire everytime even if the value is the same as the last scrape).

    Example urlscraper.ini File
    [config]
    urlcount=1
    The urlcount determines how many unique URL's will be retrieved (NOTE: a single instance of the plugin can retrieve multiple different URL's). For each URL in the URL count, you'll have URL_x sections. That is, for URL count of 1, you'll have a [URL_1] section. If you have a count of 2, you'll have both a [URL_1} and [URL_2] section.

    [URL_1]
    url=http://m.wund.com/cgi-bin/findweather/getForecast?brand=mobile&query=32712
    freq=0.5
    scrapecount=2

    Within a [URL_X] section, you'll have the url, the freq (the frequency in minutes for how often to retrieve the URL), and the scrapecount. The scrapecount is how many regex searches are going to be made against the retrieved URL HTML data. For [URL_1] with a scrapecount of 2, you'll have both a [URL_1_1] and [URL_1_2] section. If you have a [URL_2] section with a scrapecount of 1, then you'll have only a [URL_2_1] section.

    [URL_1_1]
    ;Temperature {The ";" makes this a comment line}
    regexsearch=<td>Temperature</td>[\s\S]*?<b>(.+)</b>

    The [URL_X_Y] section defines a regex search for the URL and fires a generic plugin trigger. The "X" value corresponds to the Trigger ID column (Command 1 for an X value of 1) and the "Y" value corresponds to the Trigger Value column (Option 1 for a Y value of 1).

    The search looks for the unique string of " <td>Temperature</td>" and then captures everything "[\s\S]" that is either a 'whitespace character or not a whitespace character' (ie, everything) that occurs one or more times "*" and makes the search non-greedy "?" (that is, stop at the first match found, rather than looking for more).

    regexoccur=1 {Grab the first match found (actually redundant with the ? in the search string}
    regexflags=0 {Use 0 for case insentive searchs. Add 1 for case sensetive searches, and/or add 2 for triggers only on "new" snaps.}

    [URL_1_2]
    ;Humidity
    regexsearch=<td>Humidity</td>[\s\S]*?<b>(.+)</b>
    regexoccur=1
    regexflags=0

    These two searches will find the Temperature and the Humidity from the m.wund.com web site and return to the Trigger the Temperature in LOCAL1 and the Humidity in LOCAL2. Up to 9 parameters can be captured. If more are needed a second (ie, {URL_2] section could be defined to capture additional data.

    NOTE: The [URL_x] sections are independant of each other and thus can be used to capture additional data from the same site, as indicated above, or may be directed at totally different sites with different frequencies and scrape counts for different purposes (ie, weather on one and football scores on another).

    • Configuring the Triggers:

    Create a new generic plugin trigger for each of the URL_x scrapes. You can give them ID's of WEATHER1 and WEATHER2. Set the Trigger ID number to "Command 1" for both and the Trigger Value to "Option 1" for WEATHER1 and "Option 2" for WEATHER2.

    When the WEATHER1 trigger fires, the Temperature will be in LOCAL1. When WEATHER2 fires the Humidity will be in LOCAL1.

    If you wanted only a single trigger with temperature and humidity, you would need to have a single scrape (URL_1_1) with two snap sections. Then you could have temp in LOCAL1 (if it occurs first) and humidity in LOCAL2.

    As referenced above in the URL_1_1 description, up to 5 search matches can be captured in a single trigger. If more are needed, then a 2nd URL_x (ie, URL_2) must be defined. It can pass five more data elements.

    All Triggers for ULR_1 extractions are triggered with a "Trigger ID Number" of "Command 1", where the "Trigger Value" will be "Option 1" for the first (LOCAL1) snap, Option 2 for the 2nd (LOCAL2) snap, etc.

    URL_2 extractions will be triggered from "Command 2" triggers with "Option 1" (LOCAL1) for the 1st snap in this 2nd URL Group, and "Option 2" (LOCAL2) for the next snap, etc.

    URL Scrape Trigger

    Weather Extraction Example Using the Weather Underground API

    The following examples demonstrates an extraordinarily way to extract weather data [Special thanks to "snoker" who discovered this!]

    Weather Underground has a free "developer API" you can sign up for that will VERY quickly return a customized XML-formatted document with only the raw information needed (including full compliment of weather data combined with precipitation over time).

    You have to sign up for a free API key (be sure to pick the free option which is the developer/500 call-per-day/10 call-per-minute option - any larger volumes they sensibly want you to pay for).

    You simply register a free account with them. They send a confirmation e-mail for the account creation, and once you're in go through their "cart" (as mentioned previously at no charge to you if you pick the correct option) and check out.

    You are then issued an unlimited call API key (keep this tight for obvious reasons).

    The documentation (http://www.wunderground.com/weather/api/d/docs) is fairly straight up. You can call by LAT/LON, city location, or look up a specific station by that ID (tif you know of a maintained station nearby at a school, airport, etc.. Here is an example call to a local site using the Weather Underground demo API key that goes after a specific weather station:

    ph_geturl1( "http://api.wunderground.com/api/6f4c56e1c72e7c82/geolookup/ conditions/q/pws:KCOHIGHL5.json",1,20)

    ...and here is an example of how to call out to a city location instead:

    ph_geturl1( "http://api.wunderground.com/api/6f4c56e1c72e7c82/conditions /q/CA/San_Francisco.json",1,20)

    NOTE: You have to put your own API key in where theirs (6f4c56e1c72e7c82) is used here (I'm sure they cycle them so probably disable these on a frequent basis - these may not work directly without inserting your own key). Also, if you want to extract the HTML to examine its actual contents, you can use one of the two example method above, but it's output will be so volumenous that your will have to use a ph_write file() function to get the full results. For example...

    URL Test Code

    But you have to open the result in something like NotePad++ to see it...and it's AWESOME (excerpt below):

    . . . .
    . . . .
    "weather":"Clear",
    "temperature_string":"69.5 F (20.8 C)",
    "temp_f":69.5,
    "temp_c":20.8,
    "relative_humidity":"57%",
    "wind_string":"From the West at 1.2 MPH Gusting to 3.0 MPH",
    "wind_dir":"West",
    "wind_degrees":270,
    "wind_mph":1.2,
    "wind_gust_mph":"3.0",
    "wind_kph":1.9,
    "wind_gust_kph":"4.8",
    "pressure_mb":"1015",
    . . . .
    . . . .

    The following URLScraper ini structure will access the weather site via its API and scrape off the Temperature and wind speed data elements and pass them via the Trigger in LOCAL1 and LOCAL2 respectively. If the Trigger Action Type field is set to a Macro, that macro can then use the data passed in LOCAL1...LOCALx as apppropriate.

    NOTE: all of the scrapes could also be captured in a single URL_1_1 scrape as illustrated in the "five (5) snaps off a page" example under the "Configuring the urlscraper.ini file" heading above.

    NOTE: Setting the regexflags=2 would only fire the Trigger when the weather data actually changed from one reading to the next. If there are no changes, then there will be no attempt to fire the Trigger, thus minimizing extra CPU loading.

    [config]
    urlcount=1

    [URL_1]
    url=http://api.wunderground.com/api/7d6ed69e542ccec1/conditions/q/MA/Boston.json
    freq=15.0
    scrapecount=1

    [URL_1_1]
    regexsearch="temp_f":(.+),
    regexoccur=1
    regexflags=0

    [URL_1_2]
    regexsearch="wind_mph":(.+),
    regexoccur=1
    regexflags=0


XPL

Plugin: XPL
Launch Data (ActiveX Classname): PH_XPL.phxpl
Initialization Data : Enter the full path and filename of the INI file for this particular instance of the xPL plugin. If you're using the defaults, then this value will be: c:\program files\powerhome\plugins\phxpl.ini
The PowerHome Generic xPL Plugin provides send and receive support for xPL messages to PowerHome. It is the first of a series of steps to implementing the xPL protocol from within PowerHome. The next step is to provide an xPL controller within PowerHome so PowerHome can send and receive controller commands from other xPL gateways. If you would like to learn more about xPL as well as the programs available, visit http://wiki.xplproject.org.uk/index.php/Main_Page.
Using the xPL Plugin, users can send xPL messages using the ph_picmd function. Multiple filters for incoming messages can be set and the plugin will fire Generic Plugin triggers on incoming messages. You can also have multiple instances of the xPL Plugin running with a completely different set of filters and triggers. You MUST have an xPL Hub running on the PowerHome machine. It is also useful to have some xPL compliant programs running on either the PowerHome machine or on other machines on your internal network in order for the plugin to be useful. Keep in mind that you MUST have an xPL Hub running on every machine that is hosting an xPL program. You will also most likely need to configure personal firewalls such as Comodo or ZoneAlarm in order to allow the xPL traffic to be transmitted and received.
Configuring the phxpl.ini file:
  • Open the phxpl.ini file in Notepad. You'll need to configure the xPL plugin by modifying this file.
  • Under the [Setup] section, set the "Instance" parameter to a unique instance name for this iteration of the plugin. The instance name MUST be lower case letters a thru z and numbers 0-9 only. No spaces, no dashes, or any others characters are acceptable. The total length of the instance name MUST be 16 characters or less. If you will be running multiple instances of the xPL plugin, you MUST make a copy of the phxpl.ini file with a different filename (such as phxpl1.ini). Make sure that each xPL plugin instance has a separate, unique "Instance" parameter.
  • Set the "Target" parameter to a valid xPL target application ID for direct communications. Use "*" without the quotes to broadcast your xPL messages to all xPL clients. The "Target" parameter only affects the sending of xPL messages.
  • Set the "Interval" parameter to a value between 5 and 9 inclusive. This is how often an xPL heartbeat message will be sent by the plugin. The default value of 5 should be fine.
  • Set the "PassHBeat" parameter to "yes" if you want the plugin to pass xPL heartbeat messages to the filter processor (a filter may still block the message depending upon the filters). If you set the parameter to "no" then heartbeat messages are outright discarded.
  • Set the "PassConfig" parameter to "yes" if you want the plugin to pass xPL config messages to the filter processor (a filter may still block the message depending upon the filters). If you set the parameter to "no" then config messages are outright discarded.
  • Under the [Filters] section, you can define up to 16 different filters for incoming messages. Keep in mind that filters ONLY affect incoming messages. Messages sent from the plugin are automatically discarded. When an xPL message is received, it's first checked to see if it originates from the current plugin instance. If it does, it's discarded. It's then checked for accuracy in following proper xPL format and if it fails, it's discarded. The message is then determined whether it's a heartbeat or config message and depending upon the settings in the [Setup] section, may be discarded. If a message makes it this far, it is then checked against the filters in order from 1 to 16 (or less if you have less). If a message does not MATCH a filter, it is discarded. In order for the plugin to fire a trigger on a message, it MUST match at least one plugin. This means that you MUST declare at least ONE filter. More information on Filters can be found on the xPL website under the Core Protocol documentation. Below is a very brief overview of filters to get started with.
  • The filter to match ALL incoming xPL messages is: *.*.*.*.*.*
  • An xPL message consists of 6 separate sections separated by a single period. You can use the asterisk (*) character to wildcard a section. The sections are: xPL command, source vendor, source device, source instance, schema, and type. A typical message might look like: xpl-cmnd.pha.phpi.xpl.x10.basic. This would be a fully qualified message and would be matched by the ALL filter above or the following filters:
    1. *.pha.*.*.x10.*
    2. *.pha.phpi.*.*.*
    3. *.*.*.*.x10.*
    4. xpl-cmnd.*.*.*.*.*
    5. xpl-cmnd.pha.phpi.xpl.x10.basic
  • In order for a trigger to be fired, the incoming message MUST match at least one filter. The particular filter that is matched, WILL ALSO determine the particular trigger that is fired. As such, the order in which you define filters is important. It would do no good to define the following filters in this particular order:
    1. *.pha.*.*.*.*
    2. *.pha.phpi.*.*.*
  • Since the first filter will always be matched before the second filter has a chance to be checked. As such, filters should typically be defined in order of most restrictive to least restrictive. Leave unused filter lines blank.
  • Once you've finished defining your filters, close and save the INI file.
At this point, you should already have an xPL Hub up and running. Launch PowerHome and open the PowerHome Explorer. Navigate to Setup|Controllers and create a new blank plugin line. Give the plugin an appropriate ID and use the following information for the "Launch Data (ActiveX Classname)": PH_XPL.phxpl
For the "Initialization Data" field, enter the full path and filename of the INI file for this particular instance of the xPL plugin. If you're using just a single instance or this is the first instance, the default value would be: c:\program files\powerhome\plugins\phxpl.ini
Close the PowerHome Explorer and restart or reinitialize PowerHome in order for the plugin to be loaded. Once PowerHome restarts, go to Help|About|Plugins and verify that the plugin successfully started.
Using the PowerHome xPL Generic Plugin:
  • To send xPL messages, use the ph_picmd function. The simplest way to send an xPL message is shown in the example below:
    1. ph_picmd(5,"XPL",1,0,0,"x10.basic","command=ON~ndevice=B5")
    2. In the example above, the first parameter is 5 which is the number of seconds to wait for the plugin to process the command before timing out.
    3. The second parameter is "XPL" which is our sample programs ID for the xPL plugin (defined in the Plugins screen of the PowerHome Explorer).
    4. The third parameter is the command type for the plugin to perform. In this case, the value is 1 which tells the plugin to send a simple xPL message using the INI file supplied target and the INI file supplied Instance as part of the source ID. The hops will be set to 1.
    5. The fourth parameter (0 in the example) is the type of xPL message to send. A value of 0 is for an xpl-cmnd message.
    6. The fifth parameter is not used so is left as 0.
    7. The sixth parameter is "x10.basic" which is the xPL schema and type.
    8. The seventh parameter("command=ON~ndevice=B5" in the example) is the body of the xPL message. This particular message has two name/value pairs consisting of command and device. It's important to note that a "~n" is used to separate the name/value pairs. The "~n" is the PowerHome equivalent to the line feed character and is required to separate name/value pairs when constructing your xPL messages. You MUST not embed any spaces, commas, or other characters in the body unless it's actually a part of the value section of a name/value pair.
  • The available command types for use in the ph_picmd function are:
    1. Send Simple xPL message.
lData1 = xPL command type (0 = xpl-cmnd, 1 = xpl-stat, 2 = xpl-trig)
lData2 = Unused
sData3 = xPL schema and type
sData4 = xPL message body. Separate name/value pairs
    with a line feed character (~n in PowerHome)
    2. Send Raw xPL message.
      lData1 = xPL command type (0 = xpl-cmnd, 1 = xpl-stat, 2 = xpl-trig
      lData2 = Unused
      sData3 = Source ID (in the format of xxx-yyy.zzz), Target ID (in the format of xxx-yyy.zzz or *), and schema/type. Separate the 3 individual components with a line feed character.
      sData4 = xPL message body. Separate name/value pairs with a line feed character (~n in PowerHome)
    3. Set the default target for messages sent with command 1.
      lData1 = Unused
      lData2 = Unused
      sData3 = New target in the form of xxx-yyy.zzz or * for broadcast.
      sData4 = Unused
    4. Retrieve the current default target for sending xPL messages.
      lData1 = Unused
      lData2 = Unused
      sData3 = Unused
      sData4 = Unused
    5. Set the values for whether or not to pass Heartbeat and Config messages.
      lData1 = 0 to NOT pass Heartbeat messages. > 0 to pass Heartbeat messages. < 0 for no change.
      lData2 = 0 to NOT pass Config messages. > 0 to pass Config messages. < 0 for no change.
      sData3 = Unused
      sData4 = Unused
    6. Return whether the plugin is configured to pass Heartbeat messages or not.
      lData1 = Unused
      lData2 = Unused
      sData3 = Unused
      sData4 = Unused
    7. Return whether the plugin is configured to pass Config messages or not.
      lData1 = Unused
      lData2 = Unused
      sData3 = Unused
      sData4 = Unused
  • The return value from the ph_picmd function will be as follows:
      0 = success
      1 = error
      99 = bad command
      100 = plugin not enabled
  • On command 2, a "2" can be returned if the sData3 parameter was not properly constructed.
  • On command 4, the return value will be the current Target ID.
  • On commands 6 and 7, "1" will be returned if the value is true, "0" will be returned on false.
  • If a match is made on one of the 16 filters, then the plugin will fire a "Generic Plugin" trigger. The particular values for the "Trigger ID Number" and "Trigger Value" will depend upon the type of xPL message received and the particular filter that was matched. To fire a single trigger on ANY matching xPL message, use a "Trigger ID Number" of "(Any)" and a "Trigger Value" of "(Any)".
  • The Trigger ID Number fired is dependant upon the filter matched (in the case of broadcast messages) or if it's a direct message matching the source ID of the xPL plugin. The Source ID of the xPL plugin will be: pha-phpi.INSTANCE where INSTANCE is the instance defined in the INI file. If the message is a direct message that exactly matches the source ID of the plugin, the Trigger ID Number will "Command 1". If it's a broadcast message that matches Filter1, then "Command 2" will be fired. A Filter2 match will fire "Command 3". Following this sequence, this means that valid Trigger ID Numbers will be from Command 1 to Command 17. You can use (Any) to fire on any match.
  • The Trigger Value fired is dependant upon the type of xPL message. Option 1 will be fired for xpl-cmnd messages. Option 2 will be fired for xpl-stat messages. Option 3 will be fired for xpl-trig messages. You can use (Any) to fire on any type of message.
  • When the trigger is fired, both the [TEMP] and [LOCAL] variables will populated with trigger related data. The data populated will be as follows:
      [TEMP1] = The ID of the trigger
      [TEMP2] = 0
      [TEMP3] = The number of name/value pairs in the body of the xPL message
      [TEMP4] = The number of hops in the xPL message
      [TEMP5] = The Schema and type of xPL message
      [TEMP6] = 27
      [TEMP7] = The ID of xPL plugin
      [TEMP8] = The Trigger ID Number (1 for Direct message, 2 - 17 for Filter 1 thru 16
      [TEMP9] = The Trigger Value (1 for xpl-cmnd, 2 for xpl-stat, 3 for xpl-trig
      [TEMP10] = The Source ID of the xPL message
      [LOCAL1] = The value of the 1st Name/Value pair
      [LOCAL2] = The value of the 2nd Name/Value pair
      [LOCAL3] = The value of the 3rd Name/Value pair
      [LOCAL4] = The value of the 4th Name/Value pair
      [LOCAL5] = The value of the 5th Name/Value pair
      [LOCAL6] = The value of the 6th Name/Value pair
      [LOCAL7] = The value of the 7th Name/Value pair
      [LOCAL8] = The raw body section of the xPL message (The name/value pairs)
      [LOCAL9] = The target of the xPL message
      [LOCAL10] = The complete raw xPL message
  • Since xPL messages have their name/value pairs in a predictable order (based upon the message), you should be able to quickly reference up to the first seven values in the [LOCAL1] thru [LOCAL7] variables. If the message has more than 7 name/value pairs OR if you wish to access the NAME as well as the VALUE, you'll need to parse [LOCAL8] since it will contain ALL of the name/value pairs in raw format.


Insteon
PowerHome provides full support for SmartHome's Insteon protocol and devices including software linking. Please read through the Insteon section of the Help file in order to maximize your results when using Insteon with PowerHome.
PowerHome utilizes the SmartHome Device Manager ActiveX control for Insteon PLC support. This control allows both the serial and USB versions of the Insteon PLC to be used and later the ethernet interface when made available. PowerHome also supports the newer PLM controller which doesnt require the use of the SDM.


Insteon Background
To fully realize the features and possibilities of Insteon, it helps to understand a little about how it works.
Unlike X10, each Insteon device comes preconfigured from the factory with a unique address. With X10, you could individually address each device by choosing a housecode from A to P (16 possible choices) and a unitcode from 1 to 16. This gave you a maximum of 256 possible unique devices. With Insteon, each device is preconfigured with a 3 byte address yielding a possible 16777216 combinations. This 3 byte address is represented in hexadecimal format (the decimal numbers 0 thru 9 and the letters A thru F). You will typically see an Insteon address such as: 01.2A.4C. Each two hexadecimal digits represent a single byte with each byte representation separated by a period. All Insteon devices will have a label showing what their unique address is.
Dimmable Insteon devices will have an output level ranging from 0 to 255. A value of 0 would be fully dimmed or off and a value of 255 would be 100% bright. When you control an Insteon device locally, it will default to turning full on. You can optionally set a "local level" so that when you turn a dimmable Insteon device on locally, it will turn on at a predefined level of your choosing. Once on at this level, if you press the "On" switch again, the light will go to "full on". If you set the "local level" to 0, the light will turn on to the last level the light was at when it was turned off. Additionally, each dimmable Insteon device has an individual "local ramprate". The local ramprate controls how quickly the device turns On or Off when the device is locally switched. Values for the ramprate range from 0 to 31 with 31 being nearly instant and 0 taking close to 9 minutes.
All Insteon devices are inherently two-way unlike X10 where typically only the more expensive devices were capable of two-way communication. Most Insteon devices are capable of being remotely controlled as well as acting as a controller to control other Insteon devices.
The Insteon specification allow for a number of standard and extended length messages, but for our purposes, we really only need to concern ourselves with two types of standard messages. These are direct commands and group commands. A direct command is a single Insteon device directly communicating with another single Insteon device. These communcations are typically acknowledged through two-way communication between the devices and automatically retried in the event of communication failure. The second type of message is a group message. Group messages are not acknowledged and are a broadcast command. In other words, the message is not sent to a single device. The message originates with a single device and is "broadcast" to any device within range.
When an Insteon device controls another Insteon device, this is accomplished through group commands. A standard SwitchLinc dimmer has a single on/off paddle. As such, a SwitchLinc dimmer is capable of controlling a single group of devices. Multiple devices may be contained within a single group. When a SwitchLinc dimmer is turned on locally by pressing the "On" paddle, the dimmer turns itself on to the "local level" using the "local ramprate". It also sends out a group command if it has been "linked" to any other Insteon devices. This group command will be for group 1 of the SwitchLinc's address. Any device linked to the SwitchLinc will turn on at the "group level" and "group ramprate". Without getting overly complicated and technical, in addition the a "local level" and "local ramprate", each device has a "group level" and "group ramprate" for each group/device combination that it belongs to.
When the group broadcast command from the SwitchLinc is received by another Insteon device, that device will check it's internal database and see wheither or not it is a member of the SwitchLinc's group 1. If it is, it will look up the "group level" and "group ramprate" associated with the SwitchLinc's address and group 1 and will turn on to that level using the ramprate. A similar thing happens when the SwitchLinc is switched off or dimmed or brightened locally at the switch.
As part of the Insteon standard, after the group command is sent (not acknowledged), the controller will then scan it's internal database and will send a direct group cleanup command (acknowledged) to each device that is a member of it's group to insure that the group command is carried out. It's important to remember that when a device is added to a group (this process is called "linking"), not only is a record created in the database of the controlled device, but also a record is created in the database of the controlling device. This way, the controlled device knows who is controlling it and the controlling device knows who it is controlling.
The process of creating groups is called "linking". Each Insteon device has it's own "database" of devices it controls and devices that control it. This data is stored in EEPROM and is remembered even in the event of power failure. A standard use of linking, is during the setup of 3 or multi-way switches. Unlike X10 where a 3-way lighting circuit had a master controller and then a cheap "dummy" slave switch that is electrically linked to the master, Insteon accomlishes 3 and multi-way circuits virtually. Essentially, a single Insteon switch (the master) is electrically connected to the light being controlled with any "slave" type switches being removed from the circuit with simple wiring changes. The "slave" switch is then wired into the house wiring, but with no load(light) connected and without a direct connection to the master. The slave switch is then "linked" to the master with an Insteon group. When the slave switch is turned on, a group command is sent to the master and the master switch then turns on. At this point, it is not required to do any more in order for the 3 way circuit to work. However, if you want the LED indicator light on the slave switch to reflect the status of the light when the light is switched using the master, you must "cross link" the slave to the master. Basically what is done is that the slave is linked to the master such that the slave controls the master (this is necessary just to get the 3 way switch to work) and additionally, the master is "cross linked" to the slave so that the master controls the slave. Even though the slave is not electrically tied to the light, it will still receive an "on" command when the master is switched on and it's status LED will reflect that the master is "on".
An important point to remember is that if an Insteon device does not control any other devices (no links exist in it's database as a controller), when the device is switched locally, no Insteon message is generated from the switch. What this means is that the PLC and any program attached to it will be unaware that a transition ocurred. As long as the switch is controlling at least one other device, a group message will be sent and the PLC and any program attached will know that the switch was turned on or off locally.
If local switch sensing is desired and the switch does not control any other loads, you can still link the switch directly to the PLC. This will in effect create a record in the switch's database and a group command will be sent. Although the PLC will not respond to the command, it will receive the message and pass it on to any connected program.
The PLC device itself can have it's own groups and control them as well. The PLC device can have a total of 254 groups from 1 to 254. The PLC CANNOT trigger another devices groups. All Insteon messages are signed with the address of the originating device and the PLC is no different. If you have a KeyPadLinc that controls 5 lights in it's group 3, then you cannot trigger that group directly from the PLC and would instead have to re-create the same group of 5 lights into a PLC group.
Group 255 is an "All Units On" group. If the PLC or another Insteon device sends a command to group 255, then any device that is a member of any group from the controlling device will respond. This is how a ControLinc performs an "All Lights On" and "All Lights Off" commands.


Setting up Insteon

Insteon and PowerHome
How PowerHome uses Insteon:
PowerHome supports both direct commands from the PLC to another Insteon device as well as group commands sent from the PLC. PowerHome should also accurately track all Insteon commands whether they originate from PowerHome or from any other Insteon device on the network and update the Device Status screen appropriately.
PowerHome also supports the creation of links within the PLC and remote devices from within PowerHome. If you prefer to create links using the physical tap-tap method, PowerHome supports this as well and will automatically query remote devices for any changes within their database.
To set PowerHome up for Insteon use, you must first declare an Insteon controller in the PowerHome Explorer. Open the PowerHome Explorer and using the left-hand tree view, navigate to PowerHome->Setup->Controllers. Assign a short, meaningful ID (you will use this ID to send Insteon commands) and choose either the "Insteon DM" controller type if you have a PLC or the "Insteon PLM" if you have a PLM. Click the "Active" box. You can click the "Settings" button to see the individual settings, but the defaults should be fine. Restart or Reinitialize (Files->Reinitialize) PowerHome in order for the changes to take effect and allow the Insteon Controller to load.
Once PowerHome is restarted, the SmartHome Insteon Device Manager should automatically load if selected "Insteon DM". PLM users can ignore the comments concerning the SDM. You should see a new icon in the System Tray (the list of icons on the far right of the Start toolbar). The Device Manager should automatically detect the type of PLC and what port it is on but sometimes fails to do so. If the Device Manager is unable to sense your PLC, PowerHome will respond with the message: "The XXX PLC is not responding. Commands will not be sent." where XXX is the ID you assigned to your Insteon controller. If you should get this message, open the SmartHome Device Manager by doubleclicking it's icon in the System Tray. You should see the SmartHome Device Manager window open. Left click anywhere in the big log window and then type the letters D M. A single line edit window should open towards the bottom of the screen. Type "port=?" without the quotes in the edit window and press enter. This should force the DM to locate your PLC. Give it a few seconds and you should see "PLC: port=true" in the log window. However, if it still cannot locate your PLC, you may get a "PLC: port=false" message. Whatever message you get, type "getport" in the edit window and press enter. In the log window, you should see what port the DM is currently looking at. If you have a USB PLC, then the port should be "USB4". If your PLC is serial, then you should see COM followed by the number of the COM port the PLC is in. If the port returned by getport is not correct for your setup then type "port=USB4" if your PLC is USB and "port=COM1" if your PLC is serial and connected to COM1. Adjust the COM port number for your situation. You can verify the port was set using the "getport" command. Once the DM finally recognizes your PLC, it will store the settings in the registry and will be remembered unless you change the port. Once everything is communicating, you can minimize the DM.
Once a controller has been created and communications established with the Insteon Device Manager, you're ready to setup your Insteon network. The easiest way to do this is to use the Insteon Explorer. This new window is totally dedicated to setting and maintaining your Insteon network. You can read about this screen in the next section.


Insteon Explorer
Overview
PowerHome's Insteon Explorer is a dedicated screen for all things Insteon. From this single centralized screen, you can completely manage your Insteon network from device setup and discovery to link creation, maintenance, and discovery to specialized reports detailing the particulars of your Insteon network and communication statistics.
Each section of Insteon Maintenance has been broken down into a tabbed screen with related functions grouped together. Within the Insteon Explorer, there is no need to right-click for popup menus. Context sensitive help is available for most sections of the Insteon Explorer by clicking on the question mark icons.
The top section of the Insteon Explorer contains the global Insteon controller settings. These are the same settings that appear in the controller setup screen. When you open the Insteon Explorer, these controls will reflect the current settings. You can use the Insteon Explorer to on-the-fly make changes to these settings (and optionally save them permanent) without having to restart or reinitialize. In the case of the "Poll Interval" and "Max Failures" settings, you must tab off of (or click out of) these fields for PowerHome to know that changes have been made. For the other fields, checking or unchecking the box will take effect immediately.
Below the Insteon controller settings are three windows giving you a real-time update of what is going on with the PLC and what PowerHome is doing. The first window to the left is the "Pending Operations" window. This window will list what background operations PowerHome is planning to do. How often PowerHome performs a background operation is determined by the "Poll Interval" parameter. The background operations that PowerHome will perform are controlled in part by the controller settings you've selected and by what operations you've asked PowerHome to perform such as create or delete links. After PowerHome has performed the next background operation, it will be removed from the "Pending Operations" window and copied to the "Completed Operations" window. This window displays a history of background operations performed by PowerHome whilst the Insteon Explorer has been open. The third window to the right is the "Insteon SDM Log". This color coded real-time log shows you the raw data that is being sent and received from the SmartHome Insteon Device Manager. Log entries in black shows received transactions, blue transactions are transmits. Red entries are an indication of something not working right such as a command not being acknowledged. Occasional red entries are nothing to be too concerned about since communication errors do occur. However, if every blue transmit is followed by a red NAK (No Acknowledge), then you may want to view your communication reports to try and identify where the problem is.
Below the status windows is the tabbed maintenance control. You can resize the amount of screen space utilized by the status windows and the tabbed maintenance window by clicking and dragging the horizontal bar between the two.
Getting Started
Before you can work with your Insteon network, PowerHome must know what Insteon devices you have. However, before we get to this step, we must first configure our connected PLC to work with PowerHome if not done so previously. On the "Setup" tab are all of the functions for configuring the PLC.
The PLC is like a miniature computer in itself and the first thing we must do is make sure it's running the right program. This program is called the "Core Application" and PowerHome requires a specific version in order to operate properly. This program was installed along with PowerHome and can be installed on the PLC by pressing the "Download" button. The progress bar will move and you'll get status messages in the log. This step must be done before any other operations can be performed. You may also need to do this occasionally if your PLC does not seem to be working properly.
Once the "Core Application" is downloaded to the PLC, we have a couple of choices to make. If this is a fresh PLC that hasnt been used by any other software application (meaning it should contain no useful data we want to copy), we can proceed to "Clear PLC Database" by pressing the "Clear" button. This will make sure that the PLC's database memory is clear in preparation for Auto Discovery or manual entry of our Insteon devices. If the PLC has been used by another software application or has been linked to existing devices that you'd like to have entered in PowerHome, then you can use the "Create PowerHome Insteon Devices from PLC ID's" option to read the PLC database and automatically enter the Insteon addresses into the PowerHome database. The problem with this method of device entry is that the devices will have default ID's beginning with "NEW SPIDER" and a sequential, unique number with no way of knowing what the device really is.
We're now ready to let PowerHome know what Insteon devices we have. We have several options, one of which was detailed above with the "Create" button to "Create PowerHome Insteon Devices from PLC ID's". In addition to this, we have a couple of other "automated" methods of device creation. The first method is "Auto Discovery". While this is not a true "blind" discovery where PowerHome just looks for Insteon devices (the Insteon protocol does not allow for this type of discovery due to the built-in "security" features), it does simplify the entry process significantly. You must turn auto discovery on by pressing the "On" button. PowerHome will pause any background operations (so remember to turn it off when you're done) and will listen for switches to identify themselves. To get a switch to identify itself, you must physically visit the switch and either push and hold the "on" button for 10 seconds or push and hold the "set" button for 3 seconds until the device enters linking mode. As soon as the device enters linking mode, press the on or off button to exit linking mode. When the switch entered link mode, it sent a message on the Insteon network identifying itself. If you had TTS or the Play WAV file options checked, you should have gotten an audible confirmation. If you didnt, repeat the procedure above since it's possible that the identification message was lost. If you are auto discovering several switches at once, keep a list of the order in which you discover the switches. Switches that are auto-discovered will have a default ID of "NEW DEVICE??" where ?? is a sequential, unique number in the order that it was discovered. You'll want to use your list to rename the ID's to something more appropriate and identifiable.
The other method of auto discovery is spidering. The way spidering works is that every Insteon device contains a database of what devices it controls and what devices controls it. PowerHome is able to read this database and then ask the devices contained in the database to identify themselves. These newly identified devices can then have their databases read as well allowing PowerHome to query even more devices ad infinitum until every device has been identified. Spidering only works as long every device is linked in some fashion to another device. If you have an Insteon switch that has no links whatsoever, then spidering will not discover this device. The advantage of spidering is that you only have to enter 1 or 2 devices with a decent number of links (KeypadLincs are usually good for this due to their large number of links) either manually or through auto-discovery and then let PowerHome do the rest. The disadvantage is that like "Create PowerHome Insteon Devices from PLC ID's" you will not have any idea what device is what other than what a device is linked to and it's device type. Devices discovered through spidering will have an ID of "NEW SPIDER??" where ?? is a sequential, unique number. To enable spidering, make sure that the "Allow Link Spidering" controller setting is checked. Keep in mind that spidering is ONLY performed when a device's database is scanned. When a new device is entered into PowerHome through any of it's input methods (auto discovery, manual, etc.), PowerHome will immediately attempt to scan it's database. If spidering is not enabled at this time, the database will be scanned and spidering will not occur even if you enable spidering at a later time since the device's database has already been scanned. If a device's database has already been scanned and you wish to spider it's links, you must first check "Allow Link Spidering" and then flag the device so that PowerHome will rescan it's database. This can be done from the "Devices" tab.
Manual entry of Insteon devices can be done using the "Devices" tab. You MUST enter in an ID, Insteon address, and Insteon Type before the record can be saved.
Once PowerHome knows the Insteon devices in your network, it will scan every device's link database to discover the relationships between devices (if "Link Scan" is enabled). This is a good thing and essential initially in order for PowerHome to understand your network and maintain it.
Insteon Settings
Poll Interval: how often (in seconds) that PowerHome will attempt a background process. Background processes are what appear in the "Pending Operations" window. Control commands coming from PowerHome (either direct or group) take priority over the background operations and do not appear in the "Pending Operations" window. The default is 10 seconds and PowerHome will perform a queued background operation every 10 seconds. You can change this value (and tab off of the field) and the change will take place immediately. If you set this value to 0, no background operations will be performed.
Starting with version 1.03.4.12, PowerHome now includes a "quick write" feature. As long as the Insteon Explorer window is open, PowerHome will perform certain background operations (Pending Operations) as fast as the PLC will go, temporarily overriding the value set in the "Poll Interval". Most background operations such as CREATE and DELETE links will be executed as quickly as possible while the Insteon Explorer window is open. If the Insteon Explorer window is closed, then ALL background operations will be performed according to the "Poll Interval". The only background operations that do not take advantage of the "quick write" are POLL STATUS and SCAN LINK
Status Scan: enables or disables the POLL STATUS background operation. The POLL STATUS operation gets the current level status as well as the database changes flag (which lets PowerHome know if database changes have occurred and whether PowerHome should rescan the links).
Level/Ramp/X10 Scan: goes hand in hand with "Status Scan". If Status Scan is disabled, then this flag has no effect. If Status Scan is enabled and Level/Ramp/X10 Scan is enabled, then when a "Status Scan" (POLL STATUS) operation is performed, PowerHome will also scan the "local" level, ramprate, and X10 address.
Write Level/Ramp/X10: controls whether PowerHome will attempt to write the "local" settings for level, ramprate, and X10. This is determined by a "difference" in the "Local Level" and "Desired Local Level", etc. fields in the Devices tab. It's usually best to keep this flag disabled and let PowerHome scan the current settings. In a fresh system, PowerHome will set the "Local" and "Desired" fields to the same "scanned" value. If you wish to change the currently stored value, set the "Desired" field to the desired setting and save your changes. Then enable this field and PowerHome will program all devices where the local and desired fields do not match. When done, disable this setting and airgap (power cycle) the affected switches. You could leave this field always checked and PowerHome will always overwrite any scanned values with the desired values but these writes will not take effect until the switch is airgapped.
Link Scan: controls whether PowerHome will scan a remote devices link database. PowerHome will scan a devices link database when it thinks changes have occurred (as determined by the Status Scan operation) if this field is checked.
Max Failures: determines the maximum number of critical communication errors to a device before that device is flagged as "Failed Match". PowerHome will attempt communications with a device as long as the "Active" flag is set and the "Max Failures" limit for the device is not met. Setting this value to low could cause false positives. A value too high will cause PowerHome to attempt communicating to a device unneccessarily at the detriment of other device communications. If PowerHome does not seem to communicating with a device, ie. you've created links and the links are never created and always say FLAGGED CREATE, then most likely your device is flagged as failed (reddish background in "Clear Failed" column of "Devices" tab). To fix this, place a checkmark in the "Clear Failed" column for any device flagged as failed and click the "Save / Refresh" button.
PLC Group Cleanup: controls whether PowerHome will automatically send group cleanup messages after sending a group broadcast command. The Insteon protocol states that after sending a group broadcast command, a device should then follow this up with individual group cleanup commands to each member of the group. Group cleanups can cause a lot of addtional Insteon traffic. The way a group command works is that the PLC sends a single group broadcast command that it is turning on its group 5. Group Broadcast commands are NOT Acknowledged so the PLC doesnt know if the command is heard by every device or not. Any device hearing this command will search its link database to see if it's supposed to respond or not. This is the main command that will make all lights appear to act in sync. Since the broadcast is not ACKed, you can have the PLC send individual group cleanup messages. These group cleanup messages are direct commands and ARE acknowledged. These happen sequentially one after another. You'll see this behaviour when switching a KPL or SwitchLinc that controls multiple devices. If all is working well, all lights come on together. Occasionally though, you'll see most of the lights come on together followed by one or two lights coming on afterwards sequentially. These one or two lights are the result of the group cleanup commands.
Update on ACK: controls how PowerHome updates it's internal database of device status. Since Insteon is inherently two-way, PowerHome will wait to receive an ACKnowledge command from the controlled switch before updating its internal status if the "Update on ACK" field is checked. Basically, when this field is checked, PowerHome will only set its device status if a switch actually responded to a sent command. This can cause problems with the web-based Device Status screen when an Insteon command is sent. The page will be refreshed and the device will show the state as unchanged. If you refresh a second time, then the status will be correct because the ACK has now been received. It is also a problem because sometimes a device will receive a command and control OK, but the ACK message is lost due to noise or some other factor. Leaving this field unchecked, PowerHome will update the internal device status when the command is sent (in addition to also updating on ACK). It's the users choice as to which mode is more accurate because you can control a device and the controlling command is lost or you can control a device and the responding ACK is lost. Most people are probably content to leave the "Update on ACK" field unchecked because they're already used to X10 and the fact that it is inherently only 1 way.
Allow Link Spidering: allows PowerHome to automatically create Insteon Devices during device link database scanning. If this option is checked, during link scanning of a device, if PowerHome encounters an address that is not in its device table PowerHome will Ping the device and if it responds, create a new device entry with an ID in the form of "NEW SPIDER ??" where ?? is a sequential unique number. This allows the user to enter in only 1 or 2 main devices during initial setup and have PowerHome "discover" all linked devices. The drawbacks to this are that the user will have little info (unlike "Auto Discovery" which creates the sequential numbers in the order the devices were discovered) to rename the default ID to something meaningful other than the device type and what it's linked to. Another possible problem will be orphans (devices not in any way linked to the initial devices either directly or indirectly to any of its linked devices) will not be discovered.
Scroll Log: determines whether the "Insteon SDM Log" window will auto scroll as commands are sent/received. If you're trying to read the log data, it's hard to scroll back without it scrolling forward when new data arrives. Unchecking this field will still allow commands to be logged, but the window will now no longer auto scroll it into view.
Tab Scrollbars: adds horizontal and vertical scrollbars to the tabbed window in the Insteon Explorer. This would just be a personal preference and primarily useful for people running very low screen resolutions and the default Insteon Explorer screen does not fully fit within the window.


Setup

Insteon Explorer - Setup
Download
This step is required with a new PLC or anytime the PLC is reset. It may also be occasionally necessary if the PLC is not acting normally.
Clear
Clears all ID's from the PLC internal database. Usually a good idea to perform this step prior to adding PowerHome Insteon device ID's to PLC.
Add Min
Add's PowerHome Device ID's to the PLC internal database in a minimal format. This is the default method and will add the minimum amount of information in order for PowerHome to function properly. If it is desired for the PLC to have fully constructed link information, then use the "Add Full" option instead.
If the PLC is new or has been reset, this is a required step in order for PowerHome to function properly. Also may be required if Insteon Devices have been manually added to PowerHome. Usually best to Clear PLC Database prior to executing this function.
Add Full
Add's PowerHome Device ID's to the PLC internal database in full linked format. Use this method if the PLC will have custom code or be connected to an application that requires the PLC to have fully formed link information. It is not necessary to use this option if the PLC will be used only with PowerHome.
Use the "Clear" option to clear current PLC device ID's before adding new device ID's.
Links
Clears stored Insteon Device link information from PowerHome database. Does NOT affect actual link data stored within Insteon devices. Useful when you want to have PowerHome rediscover link information from Insteon devices.
Devices
Clears stored Insteon Device data from PowerHome database. Use with caution. You will either have to manually re-enter or Auto Discover Insteon devices in order for PowerHome to work properly after using this command.
Create
This option will scan the currently connected PLC for stored Device ID's (Insteon Addresses). Any ID's not found in the PowerHome Insteon Devices table will be queued for Pinging. Pinged devices that respond properly will then be automatically added to the PowerHome Insteon Devices table with a default ID in the form of "NEW SPIDER ??" where ?? is a sequential unique number.
This option is useful for quickly getting Insteon Devices into PowerHome if the PLC has already been configured to recognize them.
Auto Discovery
Places PowerHome and the PLC into Auto Discovery mode. This will allow you to register Insteon devices within PowerHome without having to manually key in their unique address. Especially useful if switches are already installed and you don't wish to remove the faceplate to read the address. Once Auto Discovery is turned on, you must visit every Insteon device and place it in linking mode by pressing the set button for 3 seconds or the On button for 10 seconds. As soon as the device enters link mode, you will hear the WAV file and/or TTS confirmation if you've enabled those options. Once link mode has been entered and confirmation received, press the On button briefly to exit link mode. Make a list of the order in which you visit the switches. When done, return to PowerHome and turn off Auto Discovery mode. Your Insteon devices will have been automatically entered into the PowerHome database for you with an ID that begins with "NEW DEVICE XX" where XX will be a number in the order that the devices were discovered (hence the need to make a list). You will want to rename the ID and Description appropriately.


Types

Insteon Explorer - Types
Types
This screen allows you to add or modify Insteon Device Types. You should make sure this screen is up to date before doing an Auto Discovery. When adding new device types, follow the format of existing types when typing in the device description.


Devices

Insteon Explorer - Devices
Devices
This screen allows you to add or modify your Insteon Devices. You may manually enter Insteon Devices using this screen or use the Auto Discovery option on the Setup tab. If you manually enter devices, PowerHome will attempt to properly add the Insteon addresses to the PLC internal database. However, if you experience problems seemingly related to communication or signals not getting through, it may be missing addresses in the PLC database. In this situation, it is best to go to the Setup tab and first "Clear" PLC Database followed by "Add Min" Insteon ID's to PLC.


PLC Groups

Insteon Explorer - PLC Groups
PLC Groups
This screen allows you to assign ID's to PLC groups. A PLC has 254 groups from 1 to 254 with group 255 being a "global" group. By assigning an ID to a PLC group number, you'll be able use the more friendly "ID" representation in Insteon Group commands.


Links

Insteon Explorer - Links
Current Device
The Current Device window shows you the currently selected device whose controllers and responders you wish to view or modify. You may select a device to view by dropping down the "Insteon Device ID" column and scrolling to the appropriate device. You may also type the first few characters in this box to quickly jump to the appropriate place in the dropdown list.
Controllers of the selected device will be shown in the "Controllers (of Current Device)" list below. Responders (devices controlled by this device) will be shown in the "Responders (of Current Device)" list below. You may double-click anywhere in the "Current Device" row to refresh the "Controllers" and "Responders" windows if you wish to monitor on-going link activity.
Directly below the Current Device window and to the far left of the Links tab is a list of Insteon devices currently identified within PowerHome. Use this window to highlight devices to add as "Controllers" or "Responders" of the "Current Device". You may highlight a single device at a time by left-clicking on it. Highlight multiple devices by holding either the "Ctrl" or "Shift" keys while clicking on a device ID. You may alternately highlight / un-highlight ALL devices ID's by clicking on the "ID" column heading.
Once ID's are highlighted in the Device List, add them as either "Controllers" or "Responders" of the "Current Device" by dragging and dropping the currently highlighted devices to either the "Controllers" or "Responders" window or both to create cross-links.
Above the Device List are two buttons, the "Remove" button and the "Reverify" button. Both buttons may be either clicked or dragged to. The "Remove" button will delete any links dragged and dropped on it or all highlighted links in both the "Controllers" and "Responders" window if clicked. The deletion is simply a removal from the PowerHome database and does not affect actual link information in the devices themselves. To completely delete a link from both PowerHome AND the Insteon devices, drag and drop highlighted links from the "Controllers" or "Responders" window to the "Device List"
The "Reverify" button will flag any links dragged to it for reverification. If the button is instead clicked, then all highlighted links in the "Controllers" and "Responders" windows will be flagged for reverification. This is handy because on occasion, poor Insteon communications can cause PowerHome to believe that a link no longer exists. This will usually be characterized by a "NOT FOUND" in the link status fields. After flagging links for reverification, you must "Save" in order for PowerHome to start reverifying links. Reverification causes PowerHome to requery the Insteon devices and validate that the flagged links truly exist properly within the device.
Refresh
The "Refresh" option will requery the PowerHome database for any changes to Insteon devices. If you either Manually Added or Auto-Discovered a new Insteon device, you must "Refresh" in order for this device to appear in the Current Device list or Devices list. This option will also requery the "Controllers" and "Responders" link information. If you have made changes, you will be given the option to save them before the refresh takes place.
This option is similar to "double-clicking" the "Current Device" in that the currently displayed screen of information will be refreshed, but different since ALL of the database information will be refreshed. Double-clicking ONLY refreshes the Controller and Responder information for the currently selected device.
Copy / Paste
The "Copy" and "Paste" options allow you to easily duplicate links from one device to another. When the "Copy" option is selected, all selected "Controller" rows and selected "Responder" rows will be copied to a temporary buffer. You will also be given the option to include the "Current Device" as a "Responder" in subsequent "Paste" operations. You may then select another Current Device and choose the "Paste" option to copy the saved links to the new device. Depending upon the device and link, you may need to fill in additional information such as remote button number or group. These areas will be shown in red in their respective window.
Rebuild
The "Rebuild" option causes PowerHome to rebuild all the links in the currently selected device. It does not matter what "Controller" or "Responder" rows are currently selected and only works on the currently selected Insteon device. This option will rebuild all of the links that PowerHome has listed as "Controller" or "Responder" links and will reprogram them into the selected device. This option is useful if you've performed a "hard reset" on the device and wish to rebuild the links. This option is also useful if the links in the device are fragmented (the list of links contain blank entries). You will be asked to confirm this operation. As soon as confirming, the rebuild will be added to the Pending queue immediately WITHOUT needing to save.
Save
The "Save" option allows you to save any changes that you've made to the Current Device's links. You must save (or abandon) your changes before selecting another Insteon device as the Current Device. As soon as your changes are saved, the associated link changes will be added to the Insteon Pending Operations queue.
Controllers
This window lists Insteon devices that "control" the Current Device. Columns with a maroon heading color pertain to the controlling device. Columns with a blue heading color pertain to the controlled device (the device displayed in the "Current Device" window). You can edit the controllers group, the responders button, and the responders level and ramprate. You can select single rows by clicking the row, multiple rows by holding either the Control or Shift keys while clicking. You can also select or deselect ALL rows by clicking on the headings or anywhere else that is not specifically a row. Selected rows may be deleted (removed from the Insteon device AND the PowerHome database) by dragging and dropping to the "Device List" on the left. You may also drag and drop the selected rows to the "Remove" button to have the links merely deleted from the PowerHome database (the actual links in the device will still remain).
Controllers Create
The "Create" option will attempt to create PowerHome Insteon Devices for all selected Controllers with an ID of [ID NOT FOUND]. To use this option, you must first select the controllers with [ID NOT FOUND] you wish to correct. PowerHome will first add them to the PLC internal database and then attempt communication with a Ping command. If the Ping is successful, then the PowerHome Insteon Device will be created with an ID in the form of "NEW SPIDER ??" where ?? is a sequential unique number.
Responders
This window lists Insteon devices that "respond" to (are controlled by) the device shown in the Current Devices window. Columns with a green heading color pertain to the controlled (responding) device. Columns with a blue heading color pertain to the controlling device (the device displayed in the Current Device window). You can edit the controllers group, the responders button, and the responders level and ramprate. You can select single rows by clicking the row, multiple rows by holding either the Control or Shift keys while clicking. You can also select or deselect ALL rows by clicking on the headings or anywhere else that is not specifically a row. Selected rows may be deleted by dragging and dropping to the "Device List" on the left. This will delete the actual links from the associated devices as well as from the PowerHome database. If you opt to drag and drop the selected links to the "Remove" button instead, then the links will ONLY be deleted from the PowerHome database leaving the actual links in the devices intact.
Responders Create
The "Create" option will attempt to create PowerHome Insteon Devices for all selected Responders with an ID of [ID NOT FOUND]. To use this option, you must first select the responders with [ID NOT FOUND] you wish to correct. PowerHome will first add them to the PLC internal database and then attempt communication with a Ping command. If the Ping is successful, then the PowerHome Insteon Device will be created with an ID in the form of "NEW SPIDER ??" where ?? is a sequential unique number.


Manual Linking

Insteon Explorer - Manual Linking
The Manual Linking tab allows a user to experiment with the new commands for automatically linking Insteon devices without pressing the "Set" button or using the older "Poke" commands. Only the very newest Insteon devices support these commands and the bugs are still being worked out. This screen may be useful for creating links between new, third party Insteon devices that do not support the "poke" memory method of link creation.
Manual Linking in no way updates the PowerHome database as is done using the "Links" tab and currently is in experimental status.
PLC as Controller Linking
Pressing the "Launch" button will place the currently connected PowerHome PLC into "link" mode as a "Controller" for the currently selected "PLC Group Number". The "link" will be complete if you press and hold another Insteon device's "set" button or by placing a device that supports it into "All-link" mode (see below).
PLC as Responder Linking
Pressing the "Link" button will cause the PLC to be linked as a "responder" to any device that is currently in link mode as a "Controller".
PLC as Controller Un-Linking
Pressing the "Launch" button will place the currently connected PowerHome PLC into "unlink" mode. Once the PLC is in "unlink" mode, placing any other Insteon device into "link" mode will cause that device to "unlink" from the PLC if it was previously linked.
PLC as Responder Un-Linking
Pressing the "Un-Link" button will cause the PLC to "unlink" from a device that is currently in "unlink" as a controller mde.
All-Linking
Allows you to place a remote device (that supports the new command set) into either "link" or "unlink" mode programmatically without having to press a device's "set" button. Select the Device ID, the group number, and then press either "Link" or "Un-Link" as appropriate.


KPL Config

Insteon Explorer - KPL Config
KPL Config
This screen allows you to configure the KeyPadLincs (KPL's) in your Insteon network. To read the current settings of a KPL, double-click the desired KPL from the list below. You may set the local level and ramprate as well as the X10 address. You can also set the KPL to be either 6 or 8 button mode as well as the intra-button linking and toggle versus non-toggle buttons.
When a KPL is in 6 button mode, it effectively has a total of 5 groups (1, 3, 4, 5, and 6). The wide top and bottom buttons are group 1 with the top button being a non-toggle on and the bottom being a non-toggle off. In 8 button mode, the KPL has 8 groups from 1 to 8 with each button defaulting to a toggle on/off button. Group 1 is always the local load.
When in 6 button mode, buttons 3, 4, 5, and 6 can be set to either toggle, non-toggle on, or non-toggle off. When in 8 button mode, all 8 buttons can be set the same as 6 button mode's 3 thru 6.
You may configure buttons other than group 1 to control the local load but the current versions of KPL's do not allow any dim level other than what was last used so you cannot setup a KPL to have a button control the local load with 25%, 50%, 75%, and 100% settings. For this type of functionality, it would be recommended to have the desired load controlled by either an InlineLinc or SwitchLinc and then have the KPL send group commands to the device controlling the load.
To set buttons as toggle, non-toggle on, and non-toggle off: The current versions of KPL's have a flaw where the current status of a button as non-toggle on or non-toggle off cannot be determined. All that can be known is that the button is either toggle or non-toggle. This same flaw also prevents us from setting in software whether the button will be non-toggle on or non-toggle off. All we can do is set a button as toggle or non-toggle. To set a button as non-toggle on or non-toggle off, first start with the buttons as standard toggle buttons. Then go to the KPL and manually press the buttons until the buttons you wish to set as non-toggle on are lit and the buttons you wish to set as non-toggle off are not lit. Go back to this util and then set the appropriate buttons from toggle to either non-toggle on or non-toggle off. It doesnt matter (other than the button is not set to be toggle) as the button will be set as non-toggle on or non-toggle off based upon the current status of the button's lights.
To setup intrabutton linking: Intra-button linking allows you to set a KPL's buttons to control one another. Keep in mind that intra-button linking in no way trigger's the group controlled by a button and ONLY controls the status of the button's light. If you wish to have a secondary button (a button other than group 1) control the main button (group 1), then you must do both intra-button linking as well as create a link with the secondary button as a controller and the main button as a responder. To control the lights of secondary buttons from other secondary buttons or the main button, you only need to do intra-button linking. Placing a check in the "LED On" box will cause the light of the button to track the light of the controlling button. For example: If you place a check in LED On boxes 3 and 4 of button 5, then when button 5 is on, both button 3 and 4 will be on. When button 5 is off, both button 3 and 4 will be off. By placing a check in the "LED Off" box, the checked buttons will be off when the controlling button is on. In the preceding example, if the checks are in LED Off of 3 and 4 of the Button 5 group, then when button 5 is turned on, buttons 3 and 4 will turn off if they were on. Turning button 5 off, will not have an effect on buttons 3 and 4. Numerous combinations can be obtained by checking the various LED On and LED Off boxes of the button groups and experimentation will likely be necessary to achieve desired results.


Variable Substitution
Within the PowerHome environment, you have access to two types of variables. The first are global variables which can be unlimited in number and are defined by the user and the second are system variables which are finite, some of which can be indirectly created by the user. Global variables are created from within the global variable maintenance section of the PowerHome Explorer. Once created, their values can be changed over and over again from within macros and formulas. A global variable will retain its state or value until changed. Even if PowerHome is shut down, restarted, or the computer should physically lose power, a global variable will retain its last value. Global variables are referenced from within formulas by their ID name (UPPER CASE A MUST) surrounded by curly braces or through an appropriate formula function. A global variable defined within the global variable maintenance section with an ID of TEST can be referenced via variable substitution as {TEST}. A system variable is similar to a global variable in that it stores information, but system variables are not defined by the user. System variables also are reinitialized everytime PowerHome is started. They DO NOT retain their state. Some system variables cannot have their values directly changed either. System variables are referenced by their name surrounded by square brackets (UPPER CASE A MUST) or through an appropriate formula function. An example of a system variable via variable substitution is the sunset system variable [SUNSET]. Variable substitution occurs when you have text with references to system and / or global variables. The way this substitution process takes place is with a repetitive search and replace loop. When a formula is processed for variable substitution, global and system variables are searched for from the start of the formula. If a global variable is found first, its value is looked up in the database and substituted for the global variable reference. If a system variable is found first, its value is referenced from memory and substituted for the system variable reference. This process is repeated indefinitely until no system or global variables exist to be replaced or until the max variable substitution limit is reached. This limit is set in the PowerHome Setup section under Script. Note that it is possible for global and system variables to contain references to other global and system variables. When a global or system variable is substituted, if the value is a number, you should be careful to place a space before and after the global or system variable if any math is to be performed. This is to solve the problems one will encounter when trying to perform math on global or system variables and not placing a space between the operators and the global or system variables.
NOTE: When referencing global variables and system variables with variable substitution from within formulas, remember to CAPTITALIZE the ID name. If this is not done, it will not be recognized as a variable and no substitution will be performed. Certain Send Keys sequences can appear as a global variable and will be looked up in the global variable table. If not found, they will then be treated as a Send Keys text and not be substituted. For this reason you should not name any global variables F1 through F12 because {F1} through {F12} is a valid Send Keys string. A special case of curly braces is included in the global variable substitution function. An open and close curly brace with nothing between them, ie. {}, will be removed during the substitution and not left in the result as would be the case with any other use of curly braces that is not a global variable. This special situation is useful when dealing with certain issues of ODBC databases which prevent one from storing certain combinations of characters in the first position. An example of this is trying to store {DSS POWER FLAG} in a formula. The {D is assumed to be an ODBC control character. You can eliminate this problem by placing the open and close curly braces in front of the global variable like this: {}{DSS POWER FLAG}. Since the open and close curly braces will be removed during substitution, the net effect is the same as if they never existed.
PowerHome has a number of formula functions which allow you to access the contents of global and system variables without using variable substitution. These functions will return the variables data as the specific data type you request within the formula. Using these functions is slightly more efficient than variable substitution as the functions access the variables contents at evaluation time instead of being searched and replaced prior to formula evaluation. You can find details on these functions in the online help or the function appendix under ph_getglobal, ph_getsystem, and ph_getvar.
You can also disable variable substitution by editing the pwrhome.ini file and setting the VARSUBSTITUTION parameter under the [Script] section to NO. To enable variable substitution, set this parqameter to YES. You can also enable and disable variable substitution via code with the ph_varsub function. You can retrieve the status of the variable substitution parameter with the ph_getvarsub function. Disabling variable substitution means you'll have to use the ph_getvar, ph_getglobal, and ph_getsystem functions exclusively in order to reference variables from within a formula but has the benefit of allowing PowerHome to run as fast as possible.


Functions

PowerHome Formula Functions
  • abs
  • acos
  • asc
  • asca
  • asin
  • atan
  • b2d
  • case
  • ceiling
  • char
  • chara
  • clipboard
  • cos
  • d2b
  • d2h
  • date
  • datetime
  • day
  • dayname
  • daynumber
  • daysafter
  • dec
  • double
  • exp
  • fact
  • fill
  • filla
  • h2d
  • h2s
  • hour
  • if
  • int
  • integer
  • isdate
  • isnull
  • isnumber
  • istime
  • lastpos
  • left
  • lefta
  • lefttrim
  • len
  • lena
  • log
  • logten
  • long
  • lower
  • match
  • mid
  • mida
  • minute
  • mod
  • month
  • now
  • number
  • ph_addtoglobal
  • ph_addtovar
  • ph_and
  • ph_backupdb
  • ph_base64decode
  • ph_base64encode
  • ph_ccaction
  • ph_ccclearchgs
  • ph_ccdescribe
  • ph_ccdescribeid
  • ph_ccimage
  • ph_ccmapinfo
  • ph_ccmodify
  • ph_ccmodifyid
  • ph_checktrigger
  • ph_chggrammar
  • ph_chgspeaker
  • ph_clearexequeue
  • ph_clearvars
  • ph_clearx10hist
  • ph_closewindow
  • ph_colorcalc
  • ph_combuffercount
  • ph_combufferptr
  • ph_combufferreset
  • ph_comclose
  • ph_comdtr
  • ph_comopen
  • ph_comopensimple
  • ph_comrecvchar
  • ph_comrecvstring
  • ph_comrts
  • ph_comsendchar
  • ph_comsendstring
  • ph_concatglobal
  • ph_concatvar
  • ph_convertimage
  • ph_convertir
  • ph_copyfile
  • ph_createdirectory
  • ph_createglobal
  • ph_createpluginpt
  • ph_createtimedevent
  • ph_createtimedevent1
  • ph_ctlrcmd
  • ph_ctlrcmd1
  • ph_ctlrcontrol
  • ph_ctlrsq
  • ph_ctof
  • ph_datetime
  • ph_dbwhereused
  • ph_debuginfo
  • ph_decrypt
  • ph_delay
  • ph_deletedata
  • ph_deletefile
  • ph_deleteglobal
  • ph_deletetimedevent
  • ph_devicebtn
  • ph_devicecontrol
  • ph_devicerefreshstat
  • ph_directsql
  • ph_disabletrigger
  • ph_doloop
  • ph_enabletrigger
  • ph_encrypt
  • ph_evalscript
  • ph_executescript
  • ph_exportdata
  • ph_exporteventlog
  • ph_extendmacrowait
  • ph_extractval
  • ph_fileexists
  • ph_filelength
  • ph_filelist
  • ph_fill
  • ph_filterdata
  • ph_finddata
  • ph_findwindow
  • ph_findwindowex
  • ph_fixhtmlquotes
  • ph_fixjsquotes
  • ph_flattenjson
  • ph_flattenxml
  • ph_forloop
  • ph_forloopwinc
  • ph_formula
  • ph_formulabtn
  • ph_formulabtn_d
  • ph_formulabtn_dt
  • ph_formulabtn_n
  • ph_formulabtn_s
  • ph_formulabtn_t
  • ph_formulabtnparm
  • ph_fromunixtime
  • ph_ftoc
  • ph_funcdef
  • ph_funclist
  • ph_genctlrtrigger
  • ph_getanalog
  • ph_getanalogcalcstat
  • ph_getanalogstat
  • ph_getcclastobj
  • ph_getcclasttab
  • ph_getccobjbcolor
  • ph_getccobjborder
  • ph_getccobjfcolor
  • ph_getccobjgraphic
  • ph_getccobjheight
  • ph_getccobjtext
  • ph_getccobjwidth
  • ph_getccobjx
  • ph_getccobjy
  • ph_getcctab
  • ph_getcctabid
  • ph_getclassname
  • ph_getcolcount
  • ph_getcolname
  • ph_getcoltype
  • ph_getdata
  • ph_getdata_cn
  • ph_getdata_raw
  • ph_getdatawithmask
  • ph_getdevicefilter
  • ph_getdevicesort
  • ph_getdevicestat
  • ph_getdeviceval
  • ph_getdigital
  • ph_getdigitalstat
  • ph_getexefromhandle
  • ph_getforegroundwindow
  • ph_getglobal_d
  • ph_getglobal_dt
  • ph_getglobal_n
  • ph_getglobal_s
  • ph_getglobal_t
  • ph_gethandle
  • ph_gethtmldata
  • ph_getinputret
  • ph_getinsteonctrl
  • ph_getinsteondt
  • ph_getinsteonlevel
  • ph_getinsteonlevelrt
  • ph_getinsteonseconds
  • ph_getinsteonstat
  • ph_getipfromhostname
  • ph_getitcurl
  • ph_getlasterror
  • ph_getlasterrorstring
  • ph_getline
  • ph_getmbret
  • ph_getmd5hash
  • ph_getmode
  • ph_getmtret
  • ph_getparent
  • ph_getphdir
  • ph_getphwebdir
  • ph_getsha1hash
  • ph_getsha256hash
  • ph_getsqlrows
  • ph_getsuntime
  • ph_getsyspwrstat
  • ph_getsystemvar
  • ph_getsysvol
  • ph_getsysvolmax
  • ph_getsysvolmin
  • ph_getteactive
  • ph_gettetime
  • ph_gettickcount
  • ph_gettimeout
  • ph_gettimezoneinfo
  • ph_getupbdt
  • ph_getupblevel
  • ph_getupblevelrt
  • ph_getupbseconds
  • ph_getupbstat
  • ph_geturl
  • ph_geturl1
  • ph_geturlviaproxy
  • ph_geturlviaproxy1
  • ph_getvar_d
  • ph_getvar_dt
  • ph_getvar_n
  • ph_getvar_s
  • ph_getvar_t
  • ph_getvarsub
  • ph_getversion
  • ph_getwburl
  • ph_getwebauth
  • ph_getwebbase64auth
  • ph_getwebcookie
  • ph_getwebheader
  • ph_getwebheaderparm
  • ph_getwebmethod
  • ph_getwebparm
  • ph_getwebremoteip
  • ph_getweburl
  • ph_getwindow
  • ph_getwindowsdir
  • ph_getwindowstate
  • ph_getwindowtext
  • ph_getx10dt
  • ph_getx10level
  • ph_getx10seconds
  • ph_getx10stat
  • ph_getzwavecalcval
  • ph_getzwavedata
  • ph_getzwavedataraw
  • ph_getzwavedt
  • ph_getzwaverawval
  • ph_getzwaverawvalrt
  • ph_guid
  • ph_handle
  • ph_handle1
  • ph_hextonum
  • ph_highestcontrast
  • ph_htmlcolor
  • ph_htmlescape
  • ph_htmlescape1
  • ph_htmlunescape
  • ph_httprequest
  • ph_huerawcmd
  • ph_huergbtoxy
  • ph_huexytorgb
  • ph_importdata
  • ph_insertdata
  • ph_insteon
  • ph_insteonclearfailed
  • ph_insteonctrl
  • ph_insteongroup
  • ph_insteongroupcu
  • ph_insteonraw
  • ph_insteonrawbcast
  • ph_insteonrawext
  • ph_insteonrawgroup
  • ph_insteonrawgroupcu
  • ph_insteonwithret
  • ph_insteonwithret1
  • ph_insteonwithretext
  • ph_insteonwithretext1
  • ph_ir
  • ph_irchain
  • ph_irdesc
  • ph_irnumseq
  • ph_isdaylightsavings
  • ph_iseven
  • ph_ismacrowaiting
  • ph_isnull
  • ph_isodd
  • ph_isssrunning
  • ph_isvalidip
  • ph_iswslocked
  • ph_itccancel
  • ph_itccreate
  • ph_itcdestroy
  • ph_itcexecuteftp
  • ph_itcexecutehttp
  • ph_itcgetdata
  • ph_itcisbusy
  • ph_itcisvalid
  • ph_itcsavedata
  • ph_itcseturl
  • ph_itcsetuserpass
  • ph_jsontoxml
  • ph_jsontoyaml
  • ph_keybd_event
  • ph_killallmacrowait
  • ph_killmacrowait
  • ph_killprocess
  • ph_latlongcalclat
  • ph_latlongcalclong
  • ph_latlongdist
  • ph_latlongendbearing
  • ph_latlongmidlat
  • ph_latlongmidlong
  • ph_latlongstartbearing
  • ph_ldapquery
  • ph_listprocesses
  • ph_locatehandle
  • ph_locatehandle1
  • ph_locateprocess
  • ph_lockworkstation
  • ph_luminance
  • ph_macro
  • ph_macroparm
  • ph_macroparmret
  • ph_minutesafter
  • ph_minutestostring
  • ph_modifytimedevent
  • ph_movefile
  • ph_mqttpub (General)
  • ph_mqttpub (MQTT table)
  • ph_mqttsub
  • ph_mqttunsub
  • ph_msgbox
  • ph_multix
  • ph_multixtime
  • ph_n2b
  • ph_natlang
  • ph_not
  • ph_number
  • ph_numtohex
  • ph_numtohex1
  • ph_openframe
  • ph_openiewindow
  • ph_openphwin
  • ph_or
  • ph_pad
  • ph_parseline
  • ph_picmd
  • ph_pictrl
  • ph_pid
  • ph_pidclear
  • ph_ping
  • ph_ping1
  • ph_pitrigger
  • ph_playlist
  • ph_playsound
  • ph_playwinmsg
  • ph_pos
  • ph_postcopydata
  • ph_postexequeue
  • ph_postformula
  • ph_postmsg
  • ph_postmsg_s
  • ph_posturl1
  • ph_posturlviaproxy1
  • ph_powerhomeuptime
  • ph_powerhomeuptime_s
  • ph_processemail
  • ph_processemailthread
  • ph_processfromhandle
  • ph_random
  • ph_readfile
  • ph_regactivex
  • ph_regex
  • ph_regex2
  • ph_regexdiff
  • ph_regexdiff1
  • ph_regexdiff2
  • ph_regexsnap
  • ph_regexsnap1
  • ph_regexsnap2
  • ph_regexsnap3
  • ph_reinitialize
  • ph_relativedatetime
  • ph_relativedtprecise
  • ph_relativetime
  • ph_removedirectory
  • ph_replaceall
  • ph_replaceallmulti
  • ph_replaceallregex
  • ph_replaceallregex3
  • ph_replaceregex
  • ph_replaceregex3
  • ph_retrievevars
  • ph_returnallvars
  • ph_rgb2milight
  • ph_rtne
  • ph_rtnes
  • ph_run
  • ph_run1
  • ph_runasuser
  • ph_runasuser1
  • ph_runavg
  • ph_runscript_0
  • ph_runscript_1
  • ph_runscript_2
  • ph_runscript_3
  • ph_runscript_4
  • ph_runscript_5
  • ph_runsync
  • ph_runsync1
  • ph_savedesktopimage
  • ph_saveframe
  • ph_saveitcurl
  • ph_saveurl
  • ph_saveurl1
  • ph_saveurlviaproxy
  • ph_saveurlviaproxy1
  • ph_scrapetext
  • ph_seconds
  • ph_secondsafter
  • ph_secondsdiff
  • ph_secondsdiffsec
  • ph_sendcopydata
  • ph_sendemail
  • ph_sendemailfile
  • ph_sendkeys
  • ph_sendkeysbtn
  • ph_sendkeysmq
  • ph_sendmsg
  • ph_sendmsg_s
  • ph_sendsmtpemail
  • ph_sendsmtpemailasync
  • ph_sendsmtpemailfile
  • ph_sendsmtpemailfile1
  • ph_sendsmtpemailfileasync
  • ph_sendsocketdata
  • ph_sendsocketdata1
  • ph_sendudp
  • ph_setanalogdisplay
  • ph_setanalogout
  • ph_setanalogoutraw
  • ph_setanalogvalue
  • ph_setccobj
  • ph_setccobjbcolor
  • ph_setccobjborder
  • ph_setccobjfcolor
  • ph_setccobjgraphic
  • ph_setccobjheight
  • ph_setccobjtext
  • ph_setccobjwidth
  • ph_setccobjx
  • ph_setccobjy
  • ph_setcctab
  • ph_setcctabid
  • ph_setdata
  • ph_setdevicefilter
  • ph_setdevicesort
  • ph_setdeviceval
  • ph_setdigitalout
  • ph_setfileattrib
  • ph_setforegroundwindow
  • ph_setforegroundwindow1
  • ph_setframe
  • ph_setglobal_a
  • ph_setglobal_s
  • ph_setinputret
  • ph_setlocals
  • ph_setmode
  • ph_setsystemvar
  • ph_setsysvol
  • ph_settemps
  • ph_settimeout
  • ph_setvar_a
  • ph_setvar_s
  • ph_setwebcontenttype
  • ph_setwebcookie
  • ph_setwebnexturl
  • ph_setwebreturn
  • ph_setzwavedisplay
  • ph_show
  • ph_shutdown
  • ph_snapxml
  • ph_sortdata
  • ph_split
  • ph_sql
  • ph_sql_d
  • ph_sql_dt
  • ph_sql_n
  • ph_sql_s
  • ph_sql_t
  • ph_sqldestroy
  • ph_sqlselect
  • ph_sqlselectinto
  • ph_ssrequest
  • ph_stacktrace
  • ph_storevars
  • ph_sumnum
  • ph_switchto
  • ph_system
  • ph_texttojson
  • ph_timedeventsctrl
  • ph_timedeventsinfo
  • ph_tounixtime
  • ph_tracemsg
  • ph_traceoff
  • ph_traceon
  • ph_trim
  • ph_trimeventlog
  • ph_tts
  • ph_ttsctrl
  • ph_ttsgetstatus
  • ph_ttspause
  • ph_ttsresume
  • ph_ttssetvoice
  • ph_ttssync
  • ph_ttswait
  • ph_upb
  • ph_upblink
  • ph_upbraw
  • ph_upbrawlink
  • ph_updatexml
  • ph_urlescape
  • ph_usererrmsg
  • ph_usermessage
  • ph_varsub
  • ph_vrdisable
  • ph_wcclose
  • ph_wcgethome
  • ph_wcgethtml
  • ph_wcgoback
  • ph_wcgoforward
  • ph_wcgohome
  • ph_wcgourl
  • ph_wcisbusy
  • ph_wcopen
  • ph_wcrefresh
  • ph_wcsethome
  • ph_wcsethtml
  • ph_wcshow
  • ph_wcstop
  • ph_webaddblob
  • ph_webclearblob
  • ph_webds
  • ph_webdschg
  • ph_webml
  • ph_webmu
  • ph_websl
  • ph_whileloop
  • ph_winampctrl
  • ph_winampinfo
  • ph_windowstate
  • ph_windowsuptime_s
  • ph_writefile
  • ph_x10
  • ph_x10btn
  • ph_x10lookup
  • ph_x10other
  • ph_x10refreshstat
  • ph_x10setstat
  • ph_xmltojson
  • ph_xor
  • ph_xp2u
  • ph_xu2p
  • ph_yamltojson
  • ph_yp2u
  • ph_yu2p
  • ph_zero
  • ph_zwaveget
  • ph_zwavegetconfig
  • ph_zwaverawset
  • ph_zwaveset
  • ph_zwavesetcalc
  • ph_zwavesetconfig
  • pi
  • pos
  • posa
  • posw
  • profileint
  • profilestring
  • rand
  • real
  • relativedate
  • relativetime
  • replace
  • replacea
  • rgb
  • right
  • righta
  • righttrim
  • round
  • s2h
  • second
  • secondsafter
  • setprofilestring
  • sign
  • sin
  • space
  • sqrt
  • string
  • tan
  • time
  • today
  • trim
  • truncate
  • upper
  • wordcap
  • year


ph_combuffercount

ph_combuffercount PowerHome formula function
Description
Returns the total number of characters in the specified COM control's incoming buffer. The buffer is automatically reset when the bufferptr (the number of characters read from the port) = buffercount.
Syntax
ph_combuffercount ( comnum )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
Return value
Long. Returns the total number of characters in the COM control's incoming buffer. Returns - 1 if a comnum < 1 or > 5 is specified. Returns - 2 if the specified COM control is not valid.


ph_combufferptr

ph_combufferptr PowerHome formula function
Description
Returns the number of characters read in the specified COM control's incoming buffer. As characters are read from the incoming buffer, this value is incremented to show how many characters have been read. The buffercount and bufferptr are automatically reset to 0 when the bufferptr = buffercount.
Syntax
ph_combufferptr ( comnum )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
Return value
Long. Returns the number of characters read in the COM control's incoming buffer. Returns - 1 if a comnum < 1 or > 5 is specified. Returns - 2 if the specified COM control is not valid.


ph_combufferreset

ph_combufferreset PowerHome formula function
Description
Resets the buffercount and bufferptr variables for the specified COM controls incoming buffer.
Syntax
ph_combufferreset ( comnum )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
Return value
Integer. Returns 0 if successful. Returns 1 if a comnum < 1 or > 5 is specified. Returns 2 if the specified COM control is not valid. This function effectively empties the incoming buffer for the specified COM control without having to read all unread characters.


ph_comclose

ph_comclose PowerHome formula function
Description
Closes an open COM control.
Syntax
ph_comclose ( comnum )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
Return value
Integer. Returns 0 if successful. Returns 1 if a comnum < 1 or > 5 is specified. Returns 2 if the specified COM control is not valid.


ph_comdtr

ph_comdtr PowerHome formula function
Description
Enables or disables the DTR (data terminal ready) line for the specified COM control.
Syntax
ph_comdtr ( comnum, dtrvalue )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
dtrvalue | Use 0 to disable the DTR line. Any other value will enable the DTR line.
Return value
Integer. Returns 0 if successful. Returns 1 if a comnum < 1 or > 5 is specified. Returns 2 if the specified COM control is not valid.


ph_comopen

ph_comopen PowerHome formula function
Description
Opens the specified COM control. PowerHome provides the user with 5 COM controls that can be opened and characters received and written to.
Syntax
ph_comopen ( comnum, comport, bps, parity, databits, stopbits, rthreshold, sthreshold, handshaking, inputmode, nulldiscard, rtsenable, dtrenable, parityreplace, id )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
comport | The COM port you wish to open. Typically a number from 1 to 8 but can be higher.
bps | The speed at which the port should be opened. A typically value would be 9600.
parity | The parity the port should be opened. Valid values are "E", "O", and "N".
databits | The number of bits within a byte that represent data. Typical values would be 7 with even or odd parity and 8 with no parity.
stopbits | The number of stop bits. Typically 1.
rthreshold | The number of bytes to receive in the incoming buffer before the receive macro is fired. A value of 1 will cause the receive macro to execute every time a character is received (Assuming the characters are read as soon as they are received).
sthreshold | The number of bytes to store in the outgoing buffer before actually being sent out the COM port. A value of 0 will force bytes to be sent immediately.
handshaking | The value to use for handshaking. Use 0 for no handshaking, 1 for XON/OFF handshaking, 2 for RTS/CTS handshaking, and 3 for both XON/OFF and RTS/CTS handshaking.
inputmode | The manner in which to receive data. Use 0 for text data, 1 for binary data.
nulldiscard | Use a 0 to include null characters (ASCII 0) in the incoming buffer. Any other value will cause null characters to be discarded.
rtsenable | Use a 0 to disable the RTS line. Any other value will enable the RTS line.
dtrenable | Use a 0 to disable the DTR line. Any other value will enable the DTR line.
parityreplace | The character to be used to replace an invalid character when a parity error occurs. Typically this would be set to "?".
id | The ID of a macro to be called when characters are received.
Return value
Integer. Returns 0 if successful. Returns 1 if a comnum < 1 or > 5 is specified. Returns 2 if the specified COM is already open.
Usage
Allows the user to easily implement serial communications from within PowerHome. The COM control has an internal incoming buffer of 2048 characters. There are also two internal variables that track status of the incoming buffer. The buffercount variable keeps track of how many total characters are in the incoming buffer. The bufferptr variable points to the position of the last read character. Both these values start at zero. As characters arrive at the buffer, the buffercount variable is increased. If this value was zero and the ID parameter is not blank, the macro represented by the ID will be placed in the execution queue. As you read characters from the incoming buffer, the bufferptr variable is increased. When the bufferptr is equal to the buffercount (all characters have been read) both variables are reset to 0. If more characters are received, the macro will again be fired.


ph_comopensimple

ph_comopensimple PowerHome formula function
Description
Opens the specified COM control. PowerHome provides the user with 5 COM controls that can be opened and characters received and written to. Same as ph_comopen with reduced parameters.
Syntax
ph_comopensimple ( comnum, comport, settings, id )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
comport | The COM port you wish to open. Typically a number from 1 to 8 but can be higher.
settings | A string containing bps, parity, databits, and stopbits all separated by commas. To set the COM port to 9600 bps, parity NONE, 8 databits, and 1 stopbit, the settings string would be: "9600,N,8,1"
id | The ID of a macro to be called when characters are received.
Return value
Integer. Returns 0 if successful. Returns 1 if a comnum < 1 or > 5 is specified. Returns 2 if the specified COM is already open.
Usage
Allows the user to easily implement serial communications from within PowerHome. The COM control has an internal incoming buffer of 2048 characters. There are also two internal variables that track status of the incoming buffer. The buffercount variable keeps track of how many total characters are in the incoming buffer. The bufferptr variable points to the position of the last read character. Both these values start at zero. As characters arrive at the buffer, the buffercount variable is increased. If this value was zero and the ID parameter is not blank, the macro represented by the ID will be placed in the execution queue. As you read characters from the incoming buffer, the bufferptr variable is increased. When the bufferptr is equal to the buffercount (all characters have been read) both variables are reset to 0. If more characters are received, the macro will again be fired.


ph_comrecvchar

ph_comrecvchar PowerHome formula function
Description
Retrieves a single byte of information from an open COM control
Syntax
ph_comrecvchar ( comnum )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
Return value
Integer. Returns the ascii value of the byte received from the COM control. Returns - 1 if a comnum < 1 or > 5 is specified. Returns - 2 if the specified COM control is not valid. Returns - 3 if no characters are waiting to be read.


ph_comrecvstring

ph_comrecvstring PowerHome formula function
Description
Retrieves a block of characters as a string from the specified COM control.
Syntax
ph_comrecvstring ( comnum, length )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
length | The number of characters that you would like returned.
Return value
String. Returns "length" characters as a string from the COM controls incoming buffer. If fewer characters are available than the length specified, then all remaining characters are returned. Returns - 1 if a comnum < 1 or > 5 is specified. Returns - 2 if the specified COM control is not valid. Returns - 3 if no characters are waiting to be read.
Usage
This function is also capable of receiving binary characters as well. Characters with ASCII values from 32 to 125 and not equal 92 will be returned as their standard character counterparts. Characters below 32, greater than 125, or equal to 92 will be returned as an escape sequence consisting of the "\" character followed by three decimal digits representing the ASCII value. For example, the "\" (backslash character) will be returned as "\092". A carriage return character will be returned as "\013". This counts as a single character concerning the number of characters returned.


ph_comrts

ph_comrts PowerHome formula function
Description
Enables or disables the RTS (request to send) line for the specified COM control.
Syntax
ph_comrts ( comnum, rtsvalue )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
rtsvalue | Use 0 to disable the RTS line. Any other value will enable the RTS line.
Return value
Integer. Returns 0 if successful. Returns 1 if a comnum < 1 or > 5 is specified. Returns 2 if the specified COM control is not valid.


ph_comsendchar

ph_comsendchar PowerHome formula function
Description
Sends a byte out of the specified COM control.
Syntax
ph_comsendchar ( comnum, bytevalue )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
bytevalue | An integer representing the ASCII value of the byte to be sent. Valid values are 0 thru 255.
Return value
Integer. Returns 0 if the character is successfully sent. Returns 1 if a comnum < 1 or > 5 is specified. Returns 2 if the specified COM control is not valid. Returns 3 if the bytevalue is out of range.


ph_comsendstring

ph_comsendstring PowerHome formula function
Description
Sends a string of characters out of the specified COM control.
Syntax
ph_comsendstring ( comnum, data )
Argument | Description
comnum | The number of the COM control you are referencing. Valid values are 1 thru 5.
data | The string of characters you wish to be sent.
Return value
Integer. Returns 0 if the string is successfully sent. Returns 1 if a comnum < 1 or > 5 is specified. Returns 2 if the specified COM control is not valid.
Usage
This function is also capable of sending binary characters. Characters with ASCII values from 32 to 125 and not equal 92 can be sent as their standard character counterparts. Characters below 32, greater than 125, or equal to 92 must be encoded as an escape sequence consisting of the "\" character followed by three decimal digits representing the ASCII value. For example, the "\" (backslash character) would be encoded as "\092". A carriage return character would be "\013". You may use the escape sequence for the standard characters as well.

You may also encode the escape sequence in a hexadecimal format rather than a decimal format. In this case, the escape sequence consists of the "\" character followed by either an upper or lower case "x" followed by two upper or lower case hexadecimal digits. A carriage return using the hex format would be "\x0D".


ph_ccaction

ph_ccaction PowerHome formula function
Description
Executes an action associated with a Control Center action object.
Syntax
ph_ccaction ( tabid, id, x, y )
Argument | Description
tabid | String. The tab ID containing the CC action object.
id | String. The ID of the CC action object.
x | Integer. The X coordinate where a click on an action object actually occurred. Use 0 if X is not important.
y | Integer. The Y coordinate where a click on an action object actually occurred. Use 0 if Y is not important.
Return value
Integer. Returns 0 if successful. Returns 1 if the tabid and id combination cannot be found.


ph_ccclearchgs

ph_ccclearchgs PowerHome formula function
Description
Resets all temporary changes made to the Control Center using the ph_setcc??? functions.
Syntax
ph_ccclearchgs ( )
Return value
Integer. Returns a 0.


ph_ccdescribe

ph_ccdescribe PowerHome formula function
Description
Reports the values of properties of a Control Center tab and controls within the tab. Each object in the Control Center tab has a set of properties. You specify one or more properties as a string and ph_ccdescribe returns the values of the properties.
Syntax
ph_ccdescribe ( tab, propertylist )
Argument | Description
tab | The number of the Control Center tab you are describing. The tabs are numbered sequentially from left to right starting with 1.
propertylist | A string whose value is a blank-separated list of properties.
Return value
String. Returns a string that includes a value for each property. A newline character (~n) separates the value of each item in propertylist. If propertylist contains an invalid item, ph_ccdescribe returns an exclamation point (!) for that item and ignores the rest of propertylist. ph_ccdescribe returns a question mark (?) if there is no value for a property.


ph_ccdescribeid

ph_ccdescribeid PowerHome formula function
Description
Reports the values of properties of a Control Center tab and controls within the tab. Each object in the Control Center tab has a set of properties. You specify one or more properties as a string and ph_ccdescribeid returns the value of the properties.
Syntax
ph_ccdescribeid ( id, propertylist )
Argument | Description
id | The ID of the Control Center tab you are describing.
propertylist | A string whose value is a blank-separated list of properties.
Return value
String. Returns a string that includes a value for each property. A newline character (~n) separates the value of each item in propertylist. If propertylist contains an invalid item, ph_ccdescribeid returns an exclamation point (!) for that item and ignores the rest of propertylist. ph_ccdescribeid returns a question mark (?) if there is no value for a property.
Usage
A good starting point for this function is to use a propertylist value of "datawindow.syntax". This will give the complete raw syntax of the tab control including all of its objects. From this listing can be seen the proper syntax for creating new objects as well as modifying existing objects.


ph_ccimage

ph_ccimage PowerHome formula function
Description
Saves a Control Center tab to the clipboard or a graphic file.
Syntax
ph_ccimage ( id, type, copykeys, filename )
Argument | Description
id | String. The ID of the tab to convert to a graphic.
type | Integer. The type of graphic to save as. Use 0 for the Clipboard, 1 for BMP, 2 for GIF, 3 for JPEG, and 4 for PNG. You may also use the enumerated values clipboard, bmp, gif, jpeg, png.
copykeys | Integer. Use a value of 1 for the keys to be saved in the graphic. Use a value of 0 to not have the keys saved in the graphic.
filename | String. The path and filename to save to. Use empty string for the clipboard.
Return value
Integer. Returns a 0.
Usage
Use this function to save a snapshot image of a Control Center tab to either the clipboard or a graphic file. Uses a bitblt function to accomplish the graphic creation.


ph_ccmapinfo

ph_ccmapinfo PowerHome formula function
Description
Generates HTML image map data for a Control Center tab.
Syntax
ph_ccmapinfo ( id, image, mapname, nexturl, target, pagetype, imagetype, flags )
Argument | Description
id | String. The ID of the Control Center tab to generate image map data.
image | String. The path and filename of the graphic file to be included in the image map HTML.
mapname | String. A string representing the name of the image map within the HTML.
nexturl | String. A string representing the next URL to be loaded as a result of clicking on the image map.
target | String. The target in which to send the nexturl data.
pagetype | Integer. The pagetype for the resulting CCMAP page for navigation type buttons.
imagetype | Integer. The imagetype for the resulting CCMAP page for navigation type buttons.
flags | Integer. The flags for the resulting CCMAP page for navigation type buttons.
Return value
String. Returns the HTML image map data.
Usage
You can combine this function with the ph_ccimage function to create a dynamic HTML image map file for a Control Center tab.


ph_ccmodify

ph_ccmodify PowerHome formula function
Description
Modifies a Control Center tab by applying specifications, given as a list of instructions, that change the Control Center object's definition.
Syntax
ph_ccmodify ( tab, modstring )
Argument | Description
tab | The number of the Control Center tab you are modifying. The tabs are numbered sequentially from left to right starting with 1.
modstring | A string whose value is the specifications for the modification.
Return value
Returns the empty string ("") if it succeeds and an error message if an error occurs. The error message takes the form "Line n Column n incorrect syntax".


ph_ccmodifyid

ph_ccmodifyid PowerHome formula function
Description
Modifies a Control Center tab by applying specifications, given as a list of instructions, that change the Control Center object's definition.
Syntax
ph_ccmodifyid ( id, modstring )
Argument | Description
id | The ID of the Control Center tab you are modifying.
modstring | A string whose value is the specifications for the modification.
Return value
Returns the empty string ("") if it succeeds and an error message if an error occurs. The error message takes the form "Line n Column n incorrect syntax".


ph_getcclastobj

ph_getcclastobj PowerHome formula function
Description
Retrieves the ID of the last action object pressed or clicked in the Control Center. This is only valid for objects in the desktop Control Center and does not apply to objects in the Web version of the Control Center.
Syntax
ph_getcclastobj ( )
Return value
String. Returns the ID of the last action object pressed or clicked in the desktop Control Center.


ph_getcclasttab

ph_getcclasttab PowerHome formula function
Description
Retrieves the tab ID for the last button pressed or clicked in the Control Center. This is only valid for buttons in the desktop Control Center and does not apply to buttons in the Web version of the Control Center.
Syntax
ph_getcclasttab ( )
Return value
String. Returns the tab ID of the last button pressed or clicked in the desktop Control Center.


ph_getccobjbcolor

ph_getccobjbcolor PowerHome formula function
Description
Retrieves the background color for the specified Control Center object.
Syntax
ph_getccobjbcolor ( )
ph_getccobjbcolor ( as_tab, as_id )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
Return value
Long. Returns the color value of the specified objects background. This value is equivalent to the value returned from the rgb() function. Returns - 1 if the object is not found.
Usage
Use this function to retrieve the background color for a Control Center object on a CC tab. A typical use of this function would be to retrieve the current background color of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to get the background color for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getccobjbcolor( ) - If called from within a formula that was triggered by the action of a Control Center object, returns the background color for that CC object
. ph_getccobjbcolor("TV","POWER") - Returns the background color for the POWER object on the TV Control Center tab


ph_getccobjborder

ph_getccobjborder PowerHome formula function
Description
Retrieves the border value for the specified Control Center object.
Syntax
ph_getccobjborder ( )
ph_getccobjborder ( as_tab, as_id )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
Return value
Integer. Returns the border value of the specified object. 0 is returned for no border, 2 is returned for a box border, 5 is returned for a lower border, 6 is returned for a raised border, and 10 is returned for a button border. Returns -1 if the object is not found.
Usage
Use this function to retrieve the border value for a Control Center object on a CC tab. A typical use of this function would be to retrieve the current border value of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to get the border value for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getccobjborder( ) - If called from within a formula that was triggered by the action of a Control Center object, returns the border value for that CC object
. ph_getccobjborder("TV","POWER") - Returns the border value for the POWER object on the TV Control Center tab


ph_getccobjfcolor

ph_getccobjfcolor PowerHome formula function
Description
Retrieves the foreground color for the specified Control Center object.
Syntax
ph_getccobjfcolor ( )
ph_getccobjfcolor ( as_tab, as_id )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
Return value
Long. Returns the color value of the specified objects foreground. This value is equivalent to the value returned from the rgb() function. Returns -1 if the object is not found.
Usage
Use this function to retrieve the foreground color for a Control Center object on a CC tab. A typical use of this function would be to retrieve the current foreground color of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to get the foreground color for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getccobjfcolor( ) - If called from within a formula that was triggered by the action of a Control Center object, returns the foreground color for that CC object
. ph_getccobjfcolor("TV","POWER") - Returns the foreground color for the POWER object on the TV Control Center tab


ph_getccobjgraphic

ph_getccobjgraphic PowerHome formula function
Description
Retrieves the current graphic file in use by a Control Center graphic object.
Syntax
ph_getccobjgraphic ( ai_type )
ph_getccobjgraphic ( as_tab, as_id, ai_type )
Argument | Description
as_tab | String (Optional). The tab ID containing the graphic object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center graphic object. If this parameter is omitted, the system variable CCOBJ will be used
ai_type | Integer. The type of graphic file to be returned. Use 0 for the "up" graphic file, 1 for the "down" graphic file.
Return value
String. Returns the full path and filename of the specified graphic object. Returns "- 1" if the tab/object cannot be found.
Usage
Use this function to retrieve the graphic file for a Control Center graphic object on a CC tab. A typical use of this function would be to retrieve the current graphic file of a Control Center graphic object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without the as_tab and as_id parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to get the graphic file for a CC graphic object other than one that initiated an action, you must use the syntax that includes the parameters for both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getccobjgraphic("FAMILYRM","FAMILYRMLIGHT",0) - Retrieves the "up" graphic file for the FAMILYRMLIGHT graphic CC object on the FAMILYRM tab


ph_getccobjheight

ph_getccobjheight PowerHome formula function
Description
Retrieves the height for the specified Control Center object.
Syntax
ph_getccobjheight ( )
ph_getccobjheight ( as_tab, as_id )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
Return value
Long. Returns the height of the specified object. Returns -1 if the tab/object is not found.
Usage
Use this function to retrieve the height for a Control Center object on a CC tab. A typical use of this function would be to retrieve the current height of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to get the height for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getccobjheight("TV","POWER") - Retrieves the height for the POWER object on the TV tab


ph_getccobjtext

ph_getccobjtext PowerHome formula function
Description
Retrieves the text for the specified Control Center object.
Syntax
ph_getccobjtext ( )
ph_getccobjtext ( as_tab, as_id )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center graphic object. If this parameter is omitted, the system variable CCOBJ will be used
Return value
String. Returns the text of the specified object. Returns "- 1" if the tab/object is not found.
Usage
Use this function to retrieve the text for a Control Center object on a CC tab. A typical use of this function would be to retrieve the current text of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to get the text for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getccobjtext("TV","MODE") - Returns the text associated with the CC object MODE on tab TV


ph_getccobjwidth

ph_getccobjwidth PowerHome formula function
Description
Retrieves the width for the specified Control Center object.
Syntax
ph_getccobjwidth ( )
ph_getccobjwidth ( as_tab, as_id )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center graphic object. If this parameter is omitted, the system variable CCOBJ will be used
Return value
Long. Returns the width of the specified object. Returns -1 if the object is not found.
Usage
Use this function to retrieve the width for a Control Center object on a CC tab. A typical use of this function would be to retrieve the current width of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to get the width for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getccobjwidth("TV","POWER") - Returns the width for the CC object POWER located on the TV tab of the Control Center


ph_getccobjx

ph_getccobjx PowerHome formula function
Description
Retrieves the x value for the specified Control Center object. This is the horizontal position of the objects upper left hand corner.
Syntax
ph_getccobjx ( )
ph_getccobjx ( as_tab, as_id )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center graphic object. If this parameter is omitted, the system variable CCOBJ will be used
Return value
Long. Returns the x value of the specified object. Returns -1 if the object is not found.
Usage
Use this function to retrieve the x value for a Control Center object on a CC tab. A typical use of this function would be to retrieve the current x value of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to get the x value for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getccobjx("FAMILYRM","FAMILYRMLIGHT") - Returns the x value position for the CC object FAMILYRMLIGHT on Control Center tab FAMILYRM


ph_getccobjy

ph_getccobjy PowerHome formula function
Description
Retrieves the y value for the specified Control Center object. This is the vertical position of the objects upper left hand corner.
Syntax
ph_getccobjy ( )
ph_getccobjy ( as_tab, as_id )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center graphic object. If this parameter is omitted, the system variable CCOBJ will be used
Return value
Long. Returns the y value of the specified object. Returns -1 if the object is not found.
Usage
Use this function to retrieve the y value for a Control Center object on a CC tab. A typical use of this function would be to retrieve the current y value of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to get the y value for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getccobjy("FAMILYRM","FAMILYRMLIGHT") - Returns the y value position for the CC object FAMILYRMLIGHT on Control Center tab FAMILYRM


ph_getcctab

ph_getcctab PowerHome formula function
Description
Returns the number of the currently active Control Center tab.
Syntax
ph_getcctab ( )
Return value
Long. Returns the number of the currently active tab in the Control Center window. Tabs are numbered left to right starting with 1. Returns 0 if the Control Center window is not open.


ph_getcctabid

ph_getcctabid PowerHome formula function
Description
Returns the ID of the currently active Control Center tab.
Syntax
ph_getcctabid ( )
Return value
String. Returns the string ID of the currently active tab in the Control Center window. Returns the empty string if the Control Center is not open.


ph_setccobj

ph_setccobj PowerHome formula function
Description
Changes the attributes of a Control Center object. You can change all the attributes at once or individual ones depending upon the values you pass
Syntax
ph_setccobj ( as_text, ai_x, ai_y, ai_width, ai_height, al_fcolor, al_bcolor, ai_border )
ph_setccobj ( as_tab, as_id, as_text, ai_x, ai_y, ai_width, ai_height, al_fcolor, al_bcolor, ai_border )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the button. If this parameter is omitted, system variable CCTAB will be used
as_id | String (Optional). The ID of the object on the specified CC tab. If this parameter is omitted, system variable CCOBJ will be used
as_text | String. The text to place on the object. Use "" (empty string) to remove the text. Use a single space " " to not change the text
ai_x | Integer . The x position of the object. This is the horizontal position of the upper left corner of the object. Use -1 to not change the x position
ai_y | Integer . The y position of the object. This is the vertical position of the upper left corner of the object. Use -1 to not change the y position
ai_width | Integer . The width of the object. Use -1 to not change the width
ai_height | Integer . The height of the object. Use -1 to not change the height
al_fcolor | Long. The foreground color of the object. Use -1 to not change the foreground color
al_bcolor | Long. The background color of the object. Use -1 to not change the background color
ai_border | Integer. The border of the object. 0 = No border, 2 = Box, 5 = lowered, 6 = raised, and 10 = button. Use -1 to not change the border
Return value
Integer. Returns 0
Usage
Use this function or the individual ph_setcc functions to change the appearance of Control Center objects on the fly. Using this technique, you can make Control Center objects reflect the state of items. Any changes made to the Control Center in this manner are NOT permanent. These changes will be seen in the desktop Control Center as well as the web version of the Control Center.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setccobj("MAIN","FAMRMLIGHT","On, 100%", -1, -1, -1, -1, 0,rgb(255,255,0), -1) - On Control Center tab MAIN, object FAMRMLIGHT, the displayed text is updated to "On, 100%", the foreground color is set to black, and the background color is set to yellow. Other attributes are unchanged


ph_setccobjbcolor

ph_setccobjbcolor PowerHome formula function
Description
Updates the background color for the specified Control Center object
Syntax
ph_setccobjbcolor ( al_color )
ph_setccobjbcolor ( as_tab, as_id, al_color )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
al_color | Long . The RGB color value you would like to set to the background color for the object
Return value
Long. Returns 0
Usage
Use this function to set the background color for a Control Center object on a CC tab. A typical use of this function would be to set the current background color of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to set the background color for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setccobjbcolor(rgb(255,255,0)) - If called from within a formula that was triggered by the action of a Control Center object, sets the background color for that CC object to yellow
. ph_setccobjbcolor("TV","POWER",rgb(0,255,0)) - Sets the background color for the POWER object on the TV Control Center tab to green


ph_setccobjborder

ph_setccobjborder PowerHome formula function
Description
Updates the border value for the specified Control Center object
Syntax
ph_setccobjborder ( ai_border )
ph_setccobjborder ( as_tab, as_id, ai_border )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
ai_border | Integer. The border of the object. 0 = No border, 2 = Box, 5 = lowered, 6 = raised, and 10 = button
Return value
Integer. Returns 0
Usage
Use this function to update the border value for a Control Center object on a CC tab. A typical use of this function would be to set the current border value of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to set the border value for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setccobjborder(5) - If called from within a formula that was triggered by the action of a Control Center object, sets the border value for that CC object to "lowered"
. ph_setccobjborder("TV","POWER",6) - Sets the border value for the POWER object on the TV Control Center tab to "raised"


ph_setccobjfcolor

ph_setccobjfcolor PowerHome formula function
Description
Updates the foreground color for the specified Control Center object
Syntax
ph_setccobjfcolor ( al_color )
ph_setccobjfcolor ( as_tab, as_id, al_color )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
al_color | Long. The RGB color value you would like to set to the foreground color for the object
Return value
Long. Returns 0
Usage
Use this function to set the foreground color for a Control Center object on a CC tab. A typical use of this function would be to set the current foreground color of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to set the foreground color for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setccobjfcolor(rgb(255,255,255)) - If called from within a formula that was triggered by the action of a Control Center object, sets the foreground color for that CC object to white
. ph_setccobjfcolor("TV","POWER",0) - Sets the foreground color for the POWER object on the TV Control Center tab to black


ph_setccobjgraphic

ph_setccobjgraphic PowerHome formula function
Description
Allows for the setting of both up and down graphic files associated with a Control Center graphic object
Syntax
ph_setccobjgraphic ( as_filepathup, as_filepathdown )
ph_setccobjgraphic ( as_tab, as_id, as_filepathup, as_filepathdown )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
as_filepathup | String. The full path and filename of the "up" graphic object. Used by all graphic objects
as_filepathdown | String. The full path and filename of the "down" graphic object. Used ONLY by graphic button objects
Return value
Integer. Returns a 0
Usage
Use this function to dynamically change the graphic files associated with Control Center graphic objects. Also sends the changes to Remote CC clients using the UDP broadcast server.

Use a single space character as the graphic file to leave the existing graphic file unchanged. Useful when you wish to change ONLY the up or down graphic file and not the other
Examples
The following examples demonstrate typical /syntax usage for this function.
.ph_setccobjgraphic("STATUS","[LOCAL2]","C:\powerhome\web\graphics\buttons\b1gray-d_50.gif"," ")
. ph_setccobjgraphic("STATUS","DSCN",ph_getvar_s(1,4)," ")


ph_setccobjheight

ph_setccobjheight PowerHome formula function
Description
Sets the height for the specified Control Center object.
Syntax
ph_setccobjheight ( ai_height )
ph_setccobjheight ( as_tab, as_id, ai_height )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
ai_height | Integer< /span > . The height value to set the specified CC object to< /span >
Return value
Long. Returns 0
Usage
Use this function to set the height for a Control Center object on a CC tab. A typical use of this function would be to set the current height of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to set the height for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setccobjheight("TV","POWER",200) - Sets the height for the POWER object on the TV tab to 200


ph_setccobjtext

ph_setccobjtext PowerHome formula function
Description
Updates the text for the specified Control Center object.
Syntax
ph_setccobjtext ( as_text )
ph_setccobjtext ( as_tab, as_id, as_text )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center graphic object. If this parameter is omitted, the system variable CCOBJ will be used
as_text | String . The text value to set the specified CC object to
Return value
String. Returns 0
Usage
Use this function to update the text for a Control Center object on a CC tab. A typical use of this function would be to set the current text of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to set the text for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setccobjtext ( "STATUS", "DRMT", "[LOCAL3]" )
. ph_setccobjtext ( "STATUS", "DRMT", "55" )


ph_setccobjwidth

ph_setccobjwidth PowerHome formula function
Description
Sets the width for the specified Control Center object
Syntax
ph_setccobjwidth ( ai_width )
ph_setccobjwidth ( as_tab, as_id, ai_width )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
ai_width | Integer . The width value to set the specified CC object to
Return value
Long. Returns 0
Usage
Use this function to set the width for a Control Center object on a CC tab. A typical use of this function would be to set the current width of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to set the width for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setccobjwidth("TV","POWER",200) - Sets the width for the POWER object on the TV tab to 200


ph_setccobjx

ph_setccobjx PowerHome formula function
Description
Sets the x value for the specified Control Center object
Syntax
ph_setccobjx ( ai_x )
ph_setccobjx ( as_tab, as_id, ai_x )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
ai_x | Integer . The x value to set the specified CC object to. This is the horizontal position of the upper left corner of the object
Return value
Long. Returns 0
Usage
Use this function to set the x value for a Control Center object on a CC tab. A typical use of this function would be to set the current x position of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to set the x value for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setccobjx("TV","POWER",320) - Sets the x position for the POWER object on the TV tab to 320


ph_setccobjy

ph_setccobjy PowerHome formula function
Description
Sets the y value for the specified Control Center object
Syntax
ph_setccobjy ( ai_y )
ph_setccobjy ( as_tab, as_id, ai_y )
Argument | Description
as_tab | String (Optional). The ID of the Control Center tab containing the object. If this parameter is omitted, the system variable CCTAB will be used
as_id | String (Optional). The ID of the Control Center object on the specified tab. If this parameter is omitted, the system variable CCOBJ will be used
ai_y | Integer . The y value to set the specified CC object to. This is the vertical position of the upper left corner of the object
Return value
Long. Returns 0
Usage
Use this function to set the y value for a Control Center object on a CC tab. A typical use of this function would be to set the current y position of a Control Center object that was triggered and initiated an action such as a formula or macro. In that use case scenario, you can call the function without parameters and the ID's for both the tab and object will be automatically supplied by the system variables. If you wish to set the y value for a CC object other than one that initiated an action, you must specify both the tab and object ID's
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setccobjy("TV","POWER",150) - Sets the y position for the POWER object on the TV tab to 150


ph_setcctab

ph_setcctab PowerHome formula function
Description
Changes the currently active Control Center tab.
Syntax
ph_setcctab ( n )
Argument | Description
n | The number of the Control Center tab you wish to set active. Tabs are numbered from left to right starting at 1.
Return value
Integer. Returns a 0.


ph_setcctabid

ph_setcctabid PowerHome formula function
Description
Changes the currently active Control Center tab.
Syntax
ph_setcctabid ( id )
Argument | Description
id | The ID of the tab you wish to make active.
Return value
Returns a 0. If the specified ID is not found within the Control Center, then no changes are made.


ph_xp2u

ph_xp2u PowerHome formula function
Description
Returns the equivalent PowerHome units for the specified X pixels.
Syntax
ph_xp2u ( x )
Argument | Description
x | A value representing the number of pixels (in the X axis) you wish converted to units.
Return value
Integer. Returns the X pixels converted to PowerHome units.
Usage
Within the PowerHome program, all x, y, height, and width values are stored in units. This function will convert pixels in the horizontal plane (X axis) to their equivalent PowerHome X unit value.


ph_xu2p

ph_xu2p PowerHome formula function
Description
Returns the equivalent pixels for the specified X PowerHome units.
Syntax
ph_xu2p ( x )
Argument | Description
x | A value representing the number of PowerHome units (in the X axis) you wish converted to pixels.
Return value
Integer. Returns the X PowerHome units converted to pixels.
Usage
Within the PowerHome program, all x, y, height, and width values are stored in units. This function will convert PowerHome units in the horizontal plane (X axis) to their equivalent X pixel value.


ph_yp2u

ph_yp2u PowerHome formula function
Description
Returns the equivalent PowerHome units for the specified Y pixels.
Syntax
ph_yp2u ( x )
Argument | Description
x | A value representing the number of pixels (in the Y axis) you wish converted to units.
Return value
Integer. Returns the Y pixels converted to PowerHome units.
Usage
Within the PowerHome program, all x, y, height, and width values are stored in units. This function will convert pixels in the vertical plane (Y axis) to their equivalent PowerHome Y unit value.


ph_yu2p

ph_yu2p PowerHome formula function
Description
Returns the equivalent pixels for the specified Y PowerHome units.
Syntax
ph_yu2p ( x )
Argument | Description
x | A value representing the number of PowerHome units (in the Y axis) you wish converted to pixels.
Return value
Integer. Returns the Y PowerHome units converted to pixels.
Usage
Within the PowerHome program, all x, y, height, and width values are stored in units. This function will convert PowerHome units in the vertical plane (Y axis) to their equivalent Y pixel value.


ph_ctlrcmd

ph_ctlrcmd PowerHome formula function
Description
Sends a raw command to a PowerHome controller using the internal communication structure.
Syntax
ph_ctlrcmd ( as_ctlrid, ai_command, ai_parm1, al_parm2, as_parm3, as_parm4 )
ph_ctlrcmd ( ai_type, as_ctlrid, ai_command, ai_parm1, al_parm2, as_parm3, as_parm4 )
Argument | Description
ai_type | Integer (Optional). Determines the type of data returned from the function. Valid values are 0 and 1. If this parameter is omitted, internally a value of 0 will be used
as_ctlrid | String. The ID of the controller to send commands to
ai_command | Integer. The command number to send
ai_parm1 | Integer. Parameter 1 to pass to controller
al_parm2 | Long. Parameter 2 to pass to controller
as_parm3 | String. Parameter 3 to pass to controller
as_parm4 | String. Parameter 4 to pass to controller
Return value
String. Returns the output from the function depending upon the value passed in the ai_type parameter.

If ai_type = 0, the function will return the 4 return values (i_ret1, l_ret2, s_ret3, and s_ret4) from the communication structure. These values are separated with ~255 escape characters.

If ai_type = 1, the function will return the success/failure value of the function, the 4 return values (i_ret1, l_ret2, s_ret3, and s_ret4), and the 4 parameter values (i_parm1, l_parm2, s_parm3, and s_parm4). Each value is separated with a ~255 character. The parameter values would normally just contain the data that was passed when the function was called but certain command will also populate return vaues in these fields< /p >< /p >< /p >< /p >

Usage
Use this function to pass raw commands to a connected PowerHome controller. Usually a command will be sent to a controller using an already existing standard function but some controllers provided "extra" commands that are not handled by the standard functions. If a controller supports raw commands, details of the parameters will be documented under the specific controller such as the "Elk M1 Gold"
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_ctlrcmd(1,"ELK",350,0,0,"","") - Assuming that the controller in this example is an Elk M1 Gold, this command returns the zone definition. A typical example return will look like:

"0ÿ0ÿ0ÿ4455433333333333111333333333330000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ÿÿ0ÿ0ÿÿ"

The first 0 signifies that the function was successful (a value of 0 is success, any other value is a failure). The "ÿ" characters seen throughout is the ASCII representation of the ~255 characters. The i_ret1 and l_ret2 values are both 0 with the zone definition contained in the s_ret3 parameter. The remaining return values are all either 0 or empty ""


ph_ctlrcmd1

ph_ctlrcmd1 PowerHome formula function
Description
Sends a raw command to a PowerHome controller using the internal communication structure.
Syntax
ph_ctlrcmd1 ( ctlr, command, parm1, parm2, parm3, parm4, local )
Argument | Description
ctlr | String. The ID of the controller to send the command to.
command | Integer. The command to send to the controller.
parm1 | Integer. Parameter 1 for the command.
parm2 | Long. Parameter 2 for the command.
parm3 | String. Parameter 3 for the command.
parm4 | String. Parameter 4 for the command.
local | Integer. The start of the LOCAL variable block in which the return data will be returned. Use 0 to discard the return values.
Return value
Integer. Returns 0 if successful. Returns - 1 if the controller ID does not exist.

The 4 return values will be contained within LOCAL variables if the local parameter is > 0. The return values will be returned in 4 consecutive LOCAL variables. If the local parameter is 4, then ret1 will be in [LOCAL4], ret2 will be in [LOCAL5], ret3 will be in [LOCAL6], and ret4 will be in [LOCAL7]. If not enough LOCAL variables exist, the upper return values will be discarded.
Usage
This function is nearly identical to ph_ctlrcmd except that the return values are in LOCAL variables instead of having to parse the return string. Use this command to send raw commands to PowerHome controllers.


ph_ctlrcontrol

ph_ctlrcontrol PowerHome formula function
Description
This function allows you to control (connect, disconnect, restart) a preconfigured PowerHome controller
Syntax
ph_ctlrcontrol ( ctlr, control )
Argument | Description
ctlr | String. The ID of the PowerHome controller that you wish to control.
control | String. The type of action you'd like to be performed.
Return value
Integer. Returns 0 if successful. 1 if the specified controller ID does not exist. 2 if PowerHome is not registered. 3 if the control string is invalid.
Usage
Valid control strings are:

  • "connect"
  • "disconnect"
  • "restart"

    This function replaces the deprecated functions ph_connect and ph_disconnect
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    ph_ctlrcontrol("ELK","disconnect") This call will cause the controller "ELK" to be disconnected.


ph_ctlrsq

ph_ctlrsq PowerHome formula function
Description
Adds an item to a PowerHome controllers internal send queue using the internal communication routines.
Syntax
ph_ctlrsq ( as_ctlrid, ai_command, as_parm1, ai_parm2, al_parm3 )
ph_ctlrsq ( as_ctlrid, ai_command, as_parm1, ai_parm2, al_parm3, as_parm4, ai_parm5, al_parm6 )
Argument | Description
as_ctlrid | String . The ID of the controller to queue the command to
ai_command | Integer. The type of command to queue. Common queued commands are 10 for IR play, 20 for X10 send, 30 for send Insteon direct, 31 for send Insteon group, 32 for send Insteon group cleanup, 1201 for Set digital out, and 8001 for Set analog out
as_parm1 | String . Parameter 1
ai_parm2 | Integer . Parameter 2
al_parm3 | Long . Parameter 3
as_parm4 | String (Optional). Parameter 4. If this parameter is omitted, an empty string "" will be used internally
ai_parm5 | Integer (Optional). Parameter 5. If this parameter is omitted, a value of -1 will be used internally
al_parm6 | Long (Optional). Parameter 6. If this parameter is omitted, a value of -1 will be used internally
Return value
Returns 0 if the function succeeds. Returns -1 if the controller does not exist or isn't active.
Usage
This function exposes the very base level of PowerHome controller communications and is provided to achieve the maximum level of control. Most actions can be achieved using the higher level PowerHome functions such as ph_x10, ph_ir, and ph_insteon.

Most queued controller commands can be accomplished using just parameter 1 thru 3 so the shorter syntax of the function can be used. For commands that require more than just 3 parameters, the longer syntax version must be used

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_ctlrsq("X10CTLRID",20,"C",102,0) - Returns 0 if successful. This example queues a request to send an X10 "On" command to housecode C


ph_devicebtn

ph_devicebtn PowerHome formula function
Description
Controls a device that appears on the Device Status Screen (X10, Digital Out, Analog Out, Insteon). Expanded version of ph_x10btn formula.
Syntax
ph_devicebtn ( type, id, cmd, level )
Argument | Description
type | Integer. The type of device to control. Use 0 for X10 devices, 1 for Digital Outputs, 2 for Analog Outputs, 3 for Insteon Devices, 4 for Insteon Groups, 5 for UPB Devices, and 6 for UPB Links. You may also use the enumerated values: X10, DO, AO, INSTEON, INSTEONGROUP, UPB, and UPBLINK
id | String. The ID of the device to control. Use the respective ID defined in the X10 Devices, Insteon Devices, Insteon Groups, UPB Devices, UPB Links, Digital Outputs, and Analog Outputs screens.
cmd | Integer. The control command to send. See ph_x10btn for valid values for X10 Devices. For Digital Outputs, use 1 to set the device and 0 to clear the device. Use 0 for Analog Outputs. For X10 devices you may use the enumerated values: xon, xoff, xdim, xbright, adim. For Insteon Devices and Groups, you may use these enumerated values: ion, ioff, ifaston, ifastoff, idim, ibright, adim (Insteon Devices only). For UPB Devices and UPB Links you may use the enumerated values: ugoto, ufadestart, ufadestop, ublink, uindicate, adim. For UPB Links you may also use the enumerated values: uactlink and udeactlink.
level | String. Use a value from 0 to 100 when using ADIM with X10 and Insteon Devices (Enclose value in single or double quotes). Use "0" for Digital Outputs. Use a CALCULATED value string for Analog Outputs. For UPB Devices and UPB Links, use a value of 0 to 100 with the UGOTO and UFADESTART commands. Use a value of of 0 to 101 with the ADIM command. 101 will make the UPB devices blink. You may also include a UPB rate value (from 0 to 255) by following the level with a comma (Example: 75,3)
Return value
Integer. Returns - 200 if an invalid type is specified. For Digital Outputs, see the return values for ph_setdigitalout. For Analog Outputs, see the return values for ph_setanalogout. For X10 devices, see the return values for ph_x10btn. For Insteon, see the return values for ph_insteon. For Insteon Groups, see the return values for ph_insteongroup. For UPB Devices, see the return values for ph_upb. For UPB Links, see the return values for ph_upblink.
Usage
See ph_x10btn for details concerning absolute dimming and X10 device control.


ph_devicecontrol

ph_devicecontrol PowerHome formula function
Description
Allows the user to pass a standard Device Control String and have it performed.
Syntax
ph_devicecontrol ( as_control )
Argument | Description
as_control | String. A valid Device Control String.
Return value
Integer. Returns the result of the Device Control Evaluation.
Usage
See the Device Control Strings produced by the Device Control String builder for examples on valid strings. You also have the option of performing multiple device control action but separating the Device Control strings with a '|'
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_devicecontrol("INSTEON+KITCHENFANLIGHT+ON")
The next example demontrates multiple Device Control strings (3) to be executed sequentially.
ph_devicecontrol("INSTEON+KITCHENFANLIGHT+ON|INSTEON+FRONTCOACH+ON|X10+HTPC+OFF")


ph_genctlrtrigger

ph_genctlrtrigger PowerHome formula function
Description
Calls the Generic Controller Trigger (Trigger type 26).
Syntax
ph_genctlrtrigger ( id, number, value, dim, command, data, formula, auxvalue )
Argument | Description
id | The trigger ID to call. Within the Generic Controller Trigger, this is the ID of the controller.
number | The trigger number to call. This will be a value from 1 to 256.
value | The trigger value to call. This will be a value from 1 to 256.
dim | A double representing the dim value. This value will simply be passed to the trigger in the [TEMP2] variable.
command | An unsigned long representing the command. This value will be passed to the [TEMP3] variable.
data | A long representing the data. This value will be passed to the [TEMP4] variable.
formula | A string representing the formula. This value will be passed to the [TEMP5] variable.
auxvalue | A string representing the auxillary value. This value will be passed to the [TEMP10] variable.
Return value
Integer. The return value is the binary addition of the four individual trigger calls. This sum consists of 1 if the first check returns no rows, 2 if the second check returns no rows, 4 if the third check returns no rows, and 8 if the fourth check returns no rows.
Usage
This function is very similar to the ph_checktrigger function except that it only calls trigger types of 26 (Generic Controller Trigger). It is provided as a simple interface for controllers and future controller plugins to fire the generic controller trigger. Using a single function call, 4 individual trigger checks will be made. The first will be made for [Any], [Any], the second for [Any], Specific Value, the third for Specific Number, [Any], and the fourth for Specific Number, Specific Value.


ph_getanalog

ph_getanalog PowerHome formula function
Description
Retrieves the value of an analog input / output defined in the Analog I/O screen.
Syntax
ph_getanalog ( id )
Argument | Description
id | The ID of the analogl I/O as defined within the Analog I/O screen.
Return value
String. Returns the CALCULATED value of the analog I/O if successful. Returns "- 100" if the ID cannot be found. When this function is executed, the controller, unit, and point is looked up within the Analog I/O table and these values are then passed to the controller. If these values are entered improperly in the Analog I/O screen, then the following errors may be returned: " - 1" is returned if the controller is not available, "- 2" is returned if an error ocurred while retrieving the analog value, "- 3" is returned if the controller does not support analog I/O, "- 4" is returned if the unit is out of range, "- 5" is returned if the point is out of range.
Usage
This function is similar to the ph_getotheranalog function except that the point MUST be defined within the Analog I/O screen. Note that this function returns the CALCULATED value whereas the ph_getotheranalog function returns the RAW value.


ph_getanalogcalcstat

ph_getanalogcalcstat PowerHome formula function
Description
Retrieves the current calculated value of a Analog device in the Device Status Screen. This function DOES NOT cause the controller to retrieve the values and only returns what is currently stored within PowerHome.
Syntax
ph_getanalogcalcstat ( )
ph_getanalogcalcstat ( as_id )
Argument | Description
as_id | String (Optional). The ID of the analog device to retrieve the calculated value for. If this parameter is omitted, the system variable ANALOG will be used for the ID
Return value
String. Returns the currently stored calculated value for the specified analog device.
Usage
This function does not cause the controller to query the value. Use ph_getanalog to have the controller query the current raw value and calculate a new calculated value.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getanalogcalcstat("TEMPERATURE") - Returns the calculated value for the TEMPERATURE Analog I/O device. This value will be the same as that displayed in the Device Status screen


ph_getanalogstat

ph_getanalogstat PowerHome formula function
Description
Retrieves the current raw value of an Analog device in the Device Status Screen. This function DOES NOT cause the controller to retrieve the values and only returns what is currently stored within PowerHome.
Syntax
ph_getanalogstat ( )
ph_getanalogstat ( as_id )
Argument | Description
as_id | String (Optional). The ID of the analog device to retrieve the raw value for. If this parameter is omitted, the system variable ANALOG will be used for the ID
Return value
Long. Returns the currently stored raw value for the specified analog device.
Usage
This function does not cause the controller to query the value. Use ph_getotheranalog to have the controller query the current actual value.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getanalogstat("TEMPERATURE") - Returns the raw value for the TEMPERATURE Analog I/O device.


ph_getdevicestat

ph_getdevicestat PowerHome formula function
Description
This function retrieves an internally stored device status for the specified device. It does not cause PowerHome to query the device for its current status.
Syntax
ph_getdevicestat ( type, id, data, flags)
Argument | Description
type | Integer. The device type whose status you're trying to retrieve. See Usage below.
id | String. The ID of the device you're retrieving the status of.
data | Integer. The specific piece of data you'd like to retrieve. See Usage below.
flags | Integer. This parm is currently unused and is reserved for future enhancements. Use a 0 until this parm is implemented.
Return value
Return Info
Usage
Use this function to retrieve values concerning a device that is internally tracked by PowerHome.
The type argument must be a number from 0 to 6. The meaning if each is detailed below:
0 | X10
1 | Digital Input/Output
2 | Analog
3 | Insteon
4 | Insteon group
5 | UPB
6 | UPB link

The data argument is a string that must be chosen from the list below:
0 | Returns the stat_msg column which is the status message for the device as displayed on the Device Status screen
1 | Returns the value1 from the view. This will typically be the status of the device with 0 = unknown, 1 = off, 2 = on (in the case of X10).
2 | Returns the value2. This will typically be the level for a device
3 | Returns the value3. This will be string representation of value1 (status) of the device
4 | Returns the lastchange column which is the datetime for when the status was last updated by PowerHome
5 | Returns the stat_textcolor column. This is the numeric color value for the text of the status (this will match what is displayed on the Device Status screen)
6 | Returns the stat_backcolor column. This is the numeric background color value for the status field
7 | Returns the stat_graphic column. This is the path and filename for the status graphic that is being displayed..
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_getdevicestat(3,"KITCHEN",0,0)
This example will return the status message for KITCHEN which is an Insteon device. The value returned during testing was "On"


ph_getdeviceval

ph_getdeviceval PowerHome formula function
Description
Returns data associated with specific columns for a particular device.
Syntax
ph_getdeviceval ( type, id, parm)
Argument | Description
type | Integer. A numeric value equating to the type of device whose values are being retrieved. See usage below.
id | String. The ID for the device you're retrieving.
parm | String. The particular parameter you're retrieving the value of. See usage below.
Return value
Double. Returns the numeric value from the column specified in the parm parameter. - 1.0 is returned for invalid types. -2.0 is returned if there is an error retrieving the data from the database. -3.0 is returned if the parm parameter is invalid. -4.0 is returned if the type parameter is one that is currently reserved (0,2,4,6,21)
Usage
Use this function to retrieve specific values for a device directly from the PowerHome database without having to write SQL statements.
The type parameter specifies the device type and is a numeric value as defined below:
0 | Reserved for X10 device types. Not yet implemented.
2 | Reserved for Digital Input/Output types. Not yet implemented.
4 | Reserved for Analog device types. Not yet implemented.
5 | Insteon device type
6 | Reserved for Insteon Groups. Not yet implemented.
20 | UPB device type
21 | Reserved for UPB links. Not yet implemented.

The parm parameter is a string representing the database column you'd like returned.

Below are the allowed values for Insteon (type 5) device types:
commcnt
ackcnt
nakcnt
timeoutcnt
ttacnt
xcommcnt
xackcnt
xnakcnt
xtimeoutcnt
xttacnt
failedmatch
xfailedmatch
iengine
usexaldb
firmware
activeflag

Below are the allowed values for UPB (type 20) device types:
commcnt
ackcnt
nakcnt
avgss
firmware
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_getdeviceval(5,"KITCHEN","commcnt")
The above example will return the total commcnt for Insteon device KITCHEN.


ph_getdigital

ph_getdigital PowerHome formula function
Description
Retrieves the value of an digital input / output defined in the Digital I/O screen.
Syntax
ph_getdigital ( id )
Argument | Description
id | The ID of the digital I/O as defined within the Digital I/O screen.
Return value
Integer. Returns the status of the digital I/O if successful (0 = off, 1 = on). Returns - 100 if the ID cannot be found. When this function is executed, the controller, unit, and point is looked up within the Digital I/O table and these values are then passed to the controller. If these values are entered improperly in the Digital I/O screen, then the following errors may be returned: - 1 is returned if the controller is not available, - 2 is returned if the controller does not support digital I/O, - 3 is returned if the unit is out of range, - 4 is returned if the point is out of range.
Usage
This function is similar to the ph_getotherdigital function except that the point MUST be defined within the Digital I/O screen.


ph_getdigitalstat

ph_getdigitalstat PowerHome formula function
Description
Retrieves the current status of a Digital device in the Device Status Screen. This function DOES NOT cause the controller to retrieve the values and only returns what is currently stored within PowerHome.
Syntax
ph_getdigitalstat ( id )
Argument | Description
id | String. The ID of the digital device to retrieve the status for.
Return value
Integer. Returns 0 if the device is clear. Returns 1 if the device is set. If PowerHome cant retrieve the status -100 will be returned.
Usage
This function does not cause the controller to query the status. Use ph_getdigital or ph_getotherdigital to have the controller query the status.


ph_getinsteonctrl

ph_getinsteonctrl PowerHome formula function
Description
Retrieves operating parameters for the Insteon SDM controller.
Syntax
ph_getinsteonctrl ( id, parm )
Argument | Description
id | String. The ID of the Insteon SDM controller.
parm | String. The parameter you wish to set.
Return value
Integer. Returns the value of the parameter if successful. Returns - 1 if the controller ID cannot be found, returns - 100 if the parm parameter is not valid.
Usage
Use this function to retrieve the current operating parameters of the specified Insteon SDM controller. Parameters must be a string (enclosed by single or double quotes). Valid parameters are:

pollinterval - Poll Interval. Returned value is the poll interval in seconds.
statusscan - Status Scan. Returned value is 0 for disabled and 1 for enabled.
lrxscan - Level / Ramprate / X10 Scan. Returned value is 0 for disabled and 1 for enabled.
lrxwrite - Level / Ramprate / X10 Write. Returned value is 0 for disabled and 1 for enabled.
linkscan - Link Scan. Returned value is 0 for disabled and 1 for enabled.
maxfailures - Max Failures. Returned value is the maximum number of failures allowed before a device is flagged as failed.
plcgroupcu - PLC Group Cleanup messages. Returned value is 0 for disabled and 1 for enabled.
ackupdate - Update on ACK's. Returned value is 0 for disabled and 1 for enabled.
linkspider - Allow Link Spidering. Returned value is 0 for disabled and 1 for enabled.
echofile - Echo raw log to File. Returned value is 0 for disabled and 1 for enabled.


ph_getinsteondt

ph_getinsteondt PowerHome formula function
Description
Retrieves the datetime of the last status change for the specifed Insteon Device ID.
Syntax
ph_getinsteondt ( id )
Argument | Description
id | String containing the ID of the Insteon Device from which you wish to retrieve the datetime of the last status change.
Return value
Datetime. Returns the datetime value (eg, "11/21/2013 13:07:32") of the last status change associated with the specified Insteon Device ID that PowerHome currently has stored.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_getinsteondt ("SOFA LITE")
• ph_getinsteondt ("[TEMP1]")


ph_getinsteonlevel

ph_getinsteonlevel PowerHome formula function
Description
Retrieves the current level (dim / bright) value of the specifed Insteon ID.
Syntax
ph_getinsteonlevel ( id )
Argument | Description
id | String representing the ID of the Insteon Device from which you wish to retrieve the level.
Return value
Double. Returns the level associated with the specified Insteon Device ID that PowerHome currently has stored. This value will be from 0 to 255 corresponding with actual Insteon levels. To convert to a 0 to 100% range, use the following formula: X * 100 / 255 where X is the current level from 0 to 255.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_getinsteonlevel ("SOFA LITE ")
• ph_getinsteonlevel ("[TEMP1]")
• ph_getinsteonlevel("[LOCAL1]")/255*100,0)


ph_getinsteonlevelrt

ph_getinsteonlevelrt PowerHome formula function
Description
Retrieves the current status (level) of an Insteon device and retrieve the actual current status. This function may have a slight delay while the device is queried.
Syntax
ph_getinsteonlevelrt ( id )
Argument | Description
id | String. The ID of the Insteon device whose status/level you wish to retrieve.
Return value
Double. Returns the current level of the specified Insteon device. 0 means that the Insteon device is off. 1 to 255 means that the device is on and indicates the current Insteon level.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_getinsteonlevelrt ("UP BED HEAT")
• ph_getinsteonlevelrt ("[TEMP1]") {Where TEMP1 contains the Device ID.}
• if(ph_getinsteonlevelrt ("UP BED HEAT")>0,"OUT","nextLINE")
{The above example used in the Formula Field of a Goto Label Command sets the next execution line to be "OUT" if bed heat >0, else the "nextLine"}
HINT: if a label is not defined then the Goto Label command just goes to the next line, so a fake undefined lable of "nextLine" is both descriptive and functional.


ph_getinsteonseconds

ph_getinsteonseconds PowerHome formula function
Description
Retrieves the number of seconds elapsed since the last status change for the specifed Insteon Device ID.
Syntax
ph_getinsteonseconds ( s )
Argument | Description
s | A string representing the Insteon Device ID from which you wish to retrieve the seconds elapsed since last status change.
Return value
Long. Returns the number of elapsed seconds since the last status change associated with the specified Insteon Device ID that PowerHome currently has stored.


ph_getinsteonstat

ph_getinsteonstat PowerHome formula function
Description
Retrieves the current status of the specifed Insteon Device ID.
Syntax
ph_getinsteonstat ( id )
Argument | Description
id | String. The Insteon Device ID from which you wish to retrieve the status.
Return value
Integer. Returns the status associated with the specified Insteon Device ID that PowerHome currently has stored. Valid values are 0 for Unknown, 1 for Off, and 2 for On. If the ID does not exist, then -1 is returned.


ph_getupbdt

ph_getupbdt PowerHome formula function
Description
Returns the last modified DateTime for the specified UPB device.
Syntax
ph_getupbdt ( id )
Argument | Description
id | String. The ID of the UPB device whose last modified datetime you wish returned.
Return value
DateTime. The DateTime that the specified UPB device was last modified.


ph_getupblevel

ph_getupblevel PowerHome formula function
Description
Returns the level for the specified UPB device.
Syntax
ph_getupblevel ( id )
Argument | Description
id | String. The ID of the UPB device whose level you wish returned.
Return value
Double. The level of the specified UPB device.


ph_getupblevelrt

ph_getupblevelrt PowerHome formula function
Description
Returns the level for the specified UPB device in realtime.
Syntax
ph_getupblevelrt ( id )
Argument | Description
id | String. The ID of the UPB device whose level you wish returned.
Return value
Integer. The level of the specified UPB device (0 thru 100) if successful. Otherwise, these error values are returned:
- 100 | Could not find ID in database
- 1 | Controller not found
- 2 | Internal error
- 3 | Controller not connected
- 4 | Could not communicate with device
This function will actually query the specified UPB device in realtime waiting for the device to return its level.


ph_getupbseconds

ph_getupbseconds PowerHome formula function
Description
Returns the number of seconds since the UPB device had its level or status last modified.
Syntax
ph_getupbseconds ( id )
Argument | Description
id | String. The ID of the UPB device.
Return value
Long. Calculates the number of seconds between now and the last modified timestamp for the specified UPB device.


ph_getupbstat

ph_getupbstat PowerHome formula function
Description
Returns the status of the specified UPB device.
Syntax
ph_getupbstat ( id )
Argument | Description
id | String. The ID of the UPB device.
Return value
Integer. Returns the current status of the UPB device. 0 for Unknown, 1 for Off, 2 for On/Dimmed, 3 for Blinking.


ph_huerawcmd

ph_huerawcmd PowerHome formula function
Description
Sends raw command directly to a Philips Hue bridge
Syntax
ph_huerawcmd ( as_ctlr, as_method, as_command, as_data, ai_rettype )
Argument | Description
as_ctlr | String. The controller ID of the Hue Bridge you wish to send commands to
as_method | String. The HTTP method to use. Valid values are "GET", "PUT", "POST", and "DELETE". See the Hue API for more details on these methods
as_command | String. The raw Hue command you wish to send
as_data | String. Additional data that may be required for the specific command
ai_rettype | Integer. Specifies how the return data should be formatted
Return value
String. Returns the resultant HTTP data from the raw command request based upon the ai_rettype
Usage
Use this function to easily format and send commands to a Philips Hue bridge controller that is defined and active within PowerHome. This function ultimately uses the ph_httprequest function with a timeout of 5000 and uses the C# HttpWebRequest object ignoring SSL certificate errors. This function will automatically format the HTTP request using the IP and username defined in the Hue controller ID specified in the as_ctlr parameter.

Valid values for the ai_rettype parameter are:

  • 0 - Return the raw JSON data unformatted
  • 1 - Flattens the JSON data using the ph_flattenjson( ) function with an ai_type parameter of 0
  • 2 - Flattens the JSON data using the ph_flattenjson( ) function with an ai_type parameter of 1
  • 3 - Flattens the JSON data using the ph_flattenjson( ) function with an ai_type parameter of 2
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_huerawcmd("HUE","GET","/lights","",2) - This example will construct an HTTP request using the IP and username defined in the PowerHome HUE controller that looks like this: "https://<ip>/api/<username>/lights". Assuming the command works, the example will return flattened JSON containing all of the lights currently defined in the specified HUE controller.


ph_insteon

ph_insteon PowerHome formula function
Description
Send a standard length Insteon command.
Syntax
ph_insteon ( id, cmd1, cmd2 )
Argument | Description
id | String. The ID of the Insteon device to send commands to.
cmd1 | Integer. The command 1 value. { decimal 17-20 or "i" value tags (see Usage below) can be used}
cmd2 | Integer. The command 2 value. {0=off; 255=max brightness}
Return value
Integer. Returns a 0 if successful. Returns - 100 if the ID cannot be found. -1 is returned if the controller is not available, -2 is returned if the controller does not support Insteon.
Usage
Use this funciton to send Insteon commands directly to a single device. Valid commands are 17 for on, 18 for fast on, 19 for off, 20 for fast off, 21 to brighten, 22 to dim, and 25 for status. You can also use the enumerated values: ion, ifaston, ioff, ifastoff, ibright, idim, istatus. Set cmd2 to 0 for all cmd1 values except on (17). When sending an "on" command, set the cmd2 value to an integer between 0 and 255 for the level to go to.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_insteon("MID CHANDELIER",ifaston,0) --> NOTE: With 'ifaston' the cmd2 value can be anything.
• ph_insteon("MID CHANDELIER",17,0.25*255) --> NOTE: Math can be used in the cmd2 field. Thus 0.25*255 equals 25% brightness.
• ph_insteon("[LOCAL4]",ifastoff,0)
• ph_insteon("{LAST-LITE}",ion,[LOCAL1]*2.55)


ph_insteonclearfailed

ph_insteonclearfailed PowerHome formula function
Description
Zeroes the "Failed Match" column of a specific Insteon device or all Insteon devices.
Syntax
ph_insteonclearfailed ( id )
Argument | Description
id | String. The ID of the Insteon device whose failed match column will be set to 0. Use empty string ("") to reset ALL Insteon devices.
Return value
Integer. Returns a 0.


ph_insteonctrl

ph_insteonctrl PowerHome formula function
Description
Sets the operating parameters for the Insteon controller.
Syntax
ph_insteonctrl ( ctlrid, parm, data )
Argument | Description
ctlrid | String. The ID of the Insteon controller.
parm | String. The specific parameter you would like to change. See usage below for valid values.
data | Double. The value to be set to the parameter.
Return value
Integer. Returns 0 if successful. Returns - 1 if the controller ID cannot be found, returns - 100 if the parameter is not valid.
Usage
Use this function to on-the-fly programmatically change the operating parameters of the specified Insteon controller. Parameters must be a string (enclosed by single or double quotes). Valid parameters are:

pollinterval - Poll Interval. Data should contain the poll interval in seconds.
statusscan - Status Scan. Data should be 0 to disable status scan and 1 to enable.
lrxscan - Level / Ramprate / X10 Scan. Data should be 0 to disable and 1 to enable.
lrxwrite - Level / Ramprate / X10 Write. Data should be 0 to disable and 1 to enable.
linkscan - Link Scan. Data should be 0 to disable and 1 to enable the scanning of links.
maxfailures - Max Failures. Data should be an integer representing the maximum number of COMM failures before a device is flagged as failed.
plcgroupcu - PLC Group Cleanup messages. Data should be 0 to disable and 1 to enable.
ackupdate - Update on ACK's. Data should be 0 to disable and 1 to enable.
linkspider - Allow Link Spidering. Data should be 0 to disable and 1 to enable.
echofile - Echo Raw Log to File. Data should be 0 to disable and 1 to enable.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_insteonctrl("PLM","echofile",1)
The above example will enable the Echo Raw Log to File option for the Insteon controller identifed by PLM.


ph_insteongroup

ph_insteongroup PowerHome formula function
Description
Sends commands to an Insteon PLC group using the group ID.
Syntax
ph_insteongroup ( id, cmd1, cmd2 )
Argument | Description
id | String. The ID of PLC Insteon Group.
cmd1 | Integer. The command 1 to send to the group.
cmd2 | Integer. The command 2 to send to the group.
Return value
Integer. Returns a 0 if successful. -1 is returned if the controller is not available, -2 is returned if the controller does not support Insteon, -100 is returned if the group ID cannot be found.
Usage
Use this funciton to send Insteon commands to a PLC group. Valid commands are 17 for on, 18 for fast on, 19 for off, 20 for fast off, 21 to brighten, 22 to dim, 23 to Start Manual Change, and 24 to Stop Manual Change. You can also use the enumerated values: ion, ifaston, ioff, ifastoff, ibright, idim for commands 17 thru 22 respectively. Set cmd2 to 0 for all cmd1 values except 23 (Start Manual Change). For a cmd1 value of 23, set cmd2 to 1 for brighten and cmd2 to 0 for dim. Using a cmd1 value of 17 will cause the group to turn on to their individual group values using their individual ramprates. An 18 command (ifaston) causes all devices in the group to go full on ignoring the ramprate. Add 1000 to the standard Insteon commands to always force a group cleanup regardless of the controller setting. Add 2000 to the standard Insteon commands to never send a group cleanup regardless of the controller setting.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_insteongroup("ROOM OFF", ifastoff, 0)
• ph_insteongroup("ROOM ON", ion, 0)
• ph_insteongroup("ROOM ON", 23, 1)
• ph_insteongroup("[TEMP1]", 17, 0)


ph_insteongroupcu

ph_insteongroupcu PowerHome formula function
Description
Sends group cleanup commands to a device within an Insteon PLC group.
Syntax
ph_insteongroupcu ( id, deviceid, cmd1 )
Argument | Description
id | String. The ID of the PLC Insteon Group.
deviceid | String. The ID of the device within the PLC group you are controlling.
cmd1 | Integer. The command 1 to send to the group.
Return value
Integer. Returns a 0 if successful. -1 is returned if the controller is not available, -2 is returned if the controller does not support Insteon, -100 is returned if the group ID cannot be found, -101 if the device ID cannot be found.
Usage
Use this funciton to send Insteon group cleanup commands to a device within a PLC group. This function differs from the ph_insteongroup command by sending group cleanup commands (direct commands to a specific device) rather than group broadcast commands (commands to all members of a group) like the ph_insteongroup function. Using this function in association with Insteon Explorer>PLC/PLM Groups you can achieve a very fine degree of control over your Insteon devices by creating groups with specific on levels and ramprates amongst all your devices, even if you never intend to send a group command (so that all devices respond together). and then just control one, or more, specific devices.

Using the groupcu commands with individual devices, you can achieve, for instance, a variable ramprate for only that specific device. This method is also used to control the light status on individual KPL keypad buttons. For instance, to turn on the a KPL's button 3 light where that button has been assigned group number 103 in the Insteon Explorer PLC/PLM Groups tab, the following could be used: ph_insteongroupcu("BUT3","DOOR_OPEN",ifaston)

See also ".FAQs-KPL Linking.Button.Ctrl Groups" for additional help information.

Valid commands are 17 for on, 18 for fast on, 19 for off, 20 for fast off, 21 to brighten, and 22 to dim. You can also use the enumerated values: ion, ifaston, ioff, ifastoff, ibright, idim. Set cmd2 to 0 for all cmd1 values. Using a cmd1 value of 17 will cause the group to turn on to their individual group values using their individual ramprates. An 18 command (ifaston) causes all devices in the group to go full on ignoring the ramprate.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_insteongroupcu("KPL-B6","DWN SCONCE KPL",18)


ph_insteonraw

ph_insteonraw PowerHome formula function
Description
Send a standard length Insteon command.
Syntax
ph_insteonraw ( ctlr, address, cmd1, cmd2 )
Argument | Description
ctlr | String. The ID of the controller from which to send Insteon commands.
address | String. The Insteon address of the device you wish to send commands to.
cmd1 | Integer. The command 1 value.
cmd2 | Integer. The command 2 value.
Return value
Integer. Returns a 0 if successful. -1 is returned if the controller is not available, -2 is returned if the controller does not support Insteon.
Usage
Use this funciton to send Insteon commands directly to a single device. Valid commands are 17 for on, 18 for fast on, 19 for off, 20 for fast off, 21 to brighten, 22 to dim, and 25 for status. You can also use the enumerated values: ion, ifaston, ioff, ifastoff, ibright, idim, istatus. Set cmd2 to 0 for all cmd1 values except on (17). When sending an "on" command, set the cmd2 value to an integer between 0 and 255 for the level to go to.


ph_insteonrawbcast

ph_insteonrawbcast PowerHome formula function
Description
Allows for the transmission of Insteon Broadcast messages (different from Group Broadcast messages).
Syntax
ph_insteonrawbcast ( ctlr, address, cmd1, cmd2 )
Argument | Description
ctlr | String. The ID of the Insteon Controller that will send the broadcast message.
address | String. A properly formatted Insteon address string consisting of 3 pairs of hex digits separated by periods.
cmd1 | Integer. The CMD1 value to send. An integer from 0 to 255.
cmd2 | Integer. The CMD2 value to send. An integer from 0 to 255.
Return value
Integer. Returns a 0 if successful. -1 is returned if the controller is not available, -2 is returned if the controller does not support Insteon.
Usage
Use this funciton to send Insteon broadcast messages. This type of message is used by the SimpleHomeNet range of devices and allows PowerHome to send the same type of message.


ph_insteonrawgroup

ph_insteonrawgroup PowerHome formula function
Description
Sends commands to an Insteon PLC's groups.
Syntax
ph_insteonrawgroup ( ctlr, group, cmd1, cmd2 )
Argument | Description
ctlr | String. The ID of the Insteon controller.
group | Integer. An Insteon PLC group number from 1 to 254.
cmd1 | Integer. The command 1 to send to the group.
cmd2 | Integer. The command 2 to send to the group.
Return value
Integer. Returns a 0 if successful. -1 is returned if the controller is not available, -2 is returned if the controller does not support Insteon.
Usage
Use this funciton to send Insteon commands to a PLC group. Valid commands are 17 for on, 18 for fast on, 19 for off, 20 for fast off, 21 to brighten, and 22 to dim. You can also use the enumerated values: ion, ifaston, ioff, ifastoff, ibright, idim. Set cmd2 to 0 for all cmd1 values. Using a cmd1 value of 17 will cause the group to turn on to their individual group values using their individual ramprates. An 18 command (ifaston) causes all devices in the group to go full on ignoring the ramprate. Add 1000 to the standard Insteon commands to always force a group cleanup regardless of the controller setting. Add 2000 to the standard Insteon commands to never send a group cleanup regardless of the controller setting.


ph_insteonrawgroupcu

ph_insteonrawgroupcu PowerHome formula function
Description
Sends group cleanup commands to a device within an Insteon PLC group.
Syntax
ph_insteonrawgroupcu ( id, group, address, cmd1 )
Argument | Description
id | String. The ID of the controller to use.
group | Integer. The PLC group number.
address | String. The address of the device within the group to control.
cmd1 | Integer. The command 1 to send to the device.
Return value
Integer. Returns a 0 if successful. -1 is returned if the controller is not available, -2 is returned if the controller does not support Insteon.
Usage
Use this funciton to send Insteon group cleanup commands to a device within a PLC group. This function differs from the ph_insteonrawgroup command by sending group cleanup commands (direct commands to a specific device) rather than group broadcast commands (commands to all members of a group) like the ph_insteonrawgroup function. Using this function, you can achieve a very fine degree of control over your Insteon devices by creating a groups with specific on levels and ramprates amongst all your devices and never intending to send a group command (so that all devices respond together) and then just send group cleanup commands to individual devices to achieve a variable ramprate.

Valid commands are 17 for on, 18 for fast on, 19 for off, 20 for fast off, 21 to brighten, and 22 to dim. You can also use the enumerated values: ion, ifaston, ioff, ifastoff, ibright, idim. Set cmd2 to 0 for all cmd1 values. Using a cmd1 value of 17 will cause the group to turn on to their individual group values using their individual ramprates. An 18 command (ifaston) causes all devices in the group to go full on ignoring the ramprate.


ph_insteonwithret

ph_insteonwithret PowerHome formula function
Description
Send a standard length Insteon command and waits for the return value. The value returned will be the CMD2 value in the standard Insteon return string.
Syntax
ph_insteonwithret ( id, cmd1, cmd2 )
Argument | Description
id | String. The ID of the Insteon device to send commands to.
cmd1 | Integer. The command 1 value. Use standard 0 to 255 for Insteon Direct commands. Add 1000 to the cmd1 value to send Group Cleanup commands.
cmd2 | Integer. The command 2 value.
Return value
Integer. Returns the CMD2 value from the Insteon acknowledgement if successful (a positive value). Returns - 100 if the ID cannot be found. -1 is returned if the controller is not found, -2 is returned if the command fails due to timeout, -3 is returned if the controller is not connected, -4 is returned if the command fails due to NAK..
Usage
Use this funciton to send Insteon commands directly to a single device and retrieve the answering response. This is useful for working with non-lighting devices such as the EZIO8.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_insteonwithret ("MID CHANDELIER",16,0)
. ph_insteonwithret ("OUT GDR EZIO2X4", 73, 0 )
. ph_insteonwithret("DWN-STAT",107,4)


ph_ir

ph_ir PowerHome formula function
Description
Sends an Infrared command.
Syntax
ph_ir ( s, n )
Argument | Description
s | A string identifying the equipment ID whose IR you wish to send.
n | An integer representing the key number of the IR you wish to send.
Return value
Integer. Returns a 1 if an error occurs while retrieving the IR data from the database. Otherwise a 0 is returned.


ph_irchain

ph_irchain PowerHome formula function
Description
Allows you to specify a chain of Infrared commands to be played sequentially for a specific piece of equipment.
Syntax
ph_irchain ( id, commands )
Argument | Description
id | The ID of the equipment whose IR chain you wish to play
commands | A string containing the Key Descriptions of the IR commands you wish to play for the specified ID. Separate the key descriptions with a tab character (~t in PowerHome)
Return value
Integer. Returns a 0.


ph_irdesc

ph_irdesc PowerHome formula function
Description
Plays the Infrared code associated with the specified Equipment ID and Key Description.
Syntax
ph_irdesc ( id, point )
Argument | Description
id | The ID of the equipment whose IR you wish to play
point | The Key Description of the IR you wish to play. If the same Key Description exists for multiple buttons, then only 1 will be played.
Return value
Integer. Returns a 1 if an error occurs while retrieving the IR data from the database. Returns a 2 if the ID / KeyDesc cannot be found. Otherwise a 0 is returned.


ph_irnumseq

ph_irnumseq PowerHome formula function
Description
Sends a sequence of IR "number" commands.
Syntax
ph_irnumseq ( id, sequence, start )
Argument | Description
id | The ID of a piece of IR Equipment
sequence | A string representing a sequence of numeric IR codes.
start | The starting location of the IR digits. This will be shown in the Explorer as the "Key #" of the "1" IR code. Divide this number by 10 for the "Start" value.
Return value
Integer. Returns a 0.
Usage
Use this function to easily send a sequence of IR "numbers". For example, if you want to change the channel on a Dish Satellite system to Fox News on channel 205, and the sequence of the "1" IR key is 12, then use: ph_irnumseq("DISH","205",12)


ph_mqttpub (General)

ph_mqttpub (General syntax) PowerHome formula function
Description
Publishes an MQTT topic/message using an MQTT controller actively setup and configured within PowerHome. For topics already defined in the MQTT->MQTT Publish section of PowerHome Explorer, please see this version of the ph_mqttpub function: ph_mqttpub (MQTT table)
Syntax
ph_mqttpub ( as_ctlr, as_topic, as_message, ai_qos, ai_retain, ai_type )
Argument | Description
as_ctlr | String. The ID of the MQTT controller within PowerHome
as_topic | String. The MQTT topic to publish to
as_message | String. The message for the MQTT topic
ai_qos | Integer. The MQTT QOS (Quality Of Service). Valid values are 0, 1, and 2. Any other value will be treated as 0
ai_retain | Integer. The MQTT retain message flag. Use 0 to not retain the message, any other value to retain this message
ai_type | Integer. Specifies how the message is to be published. A value of 0 will send the message to the controller queue where it is executed after other queued messages. Any other value causes the controller to send the message immediately with feedback if an error occurs
Return value
Integer. Returns 0 if message was queued successfully when ai_type = 0. Returns 0 if message was published successfully when ai_type <> 0. Returns -1 if the controller ID is not found. Returns -51 if the command is not supported by the controller. Returns -11 if an error occurs during publish when ai_type <> 0
Usage
Use this function to publish MQTT messages to a topic using a currently connected PowerHome MQTT controller. This particular syntax for ph_mqttpub( ) is to publish general topics/messages that are not currently defined within the Analog I/O screen or the MQTT Publish screen. For more information concerning MQTT, the protocol, and how it is used, a very good reference can be found here: https://www.hivemq.com/mqtt-essentials/
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_mqttpub("MQTT","home/1stfloor/familyrm/temperature","78.3",0,0,0) - Returns a 0 if the topic/message was successfully queued. This example will publish a message of "78.3" to the "home/1stfloor/familyrm/temperature" topic with a QOS level of 0. The message will not be retained.


ph_mqttpub (MQTT table)

ph_mqttpub (MQTT Table syntax) PowerHome formula function
Description
Publishes an MQTT message to a topic that is currently defined and setup within the MQTT->MQTT Publish section of the PowerHome Explorer. For syntax for a more general version of MQTT publishing, please see this function: ph_mqttpub (General)
Syntax
ph_mqttpub ( as_id, as_message, ai_type )
Argument | Description
as_id | String. The ID of the MQTT Publish topic you wish to send a message to
as_message | String. The message you wish to publish
ai_type | Integer. Specifies how the message is to be published. A value of 0 will send the message to the controller queue where it is executed after other queued messages. Any other value causes the controller to send the message immediately with feedback if an error occurs
Return value
Integer. Returns 0 if message was queued successfully when ai_type = 0. Returns 0 if message was published successfully when ai_type <> 0. Returns -100 if the ID specified in as_in is not found in the MQTTPUB table. Returns -1 if the controller associated with the MQTT Publish topic specified by as_id is not found. Returns -51 if the command is not supported by the controller. Returns -11 if an error occurs during publish when ai_type <> 0
Usage
Use this function to publish MQTT messages to a previously defined MQTT topic in the MQTTPUB table. These definitions are maintained within the PowerHome Explorer under the MQTT->MQTT Publish screen. If you wish to publish a message to a topic not currently defined, then use the other syntax for this function under ph_mqttpub (General) . For more information concerning MQTT, the protocol, and how it is used, a very good reference can be found here: https://www.hivemq.com/mqtt-essentials/
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_mqttpub("FAMRMLIGHT","On, 75%",0) - Returns a 0 if the topic/message was successfully queued. This example will publish a message of "On, 75%" to the topic defined for the "FAMRMLIGHT" ID in the MQTTPUB table. The QOS and retain values will also be pulled from the "FAMRMLIGHT" table entry


ph_mqttsub

ph_mqttsub PowerHome formula function
Description
Allows the specified PowerHome MQTT controller to subscribe to MQTT topics
Syntax
ph_mqttsub ( as_ctlr, as_topic, ai_qos, ai_type )
Argument | Description
as_ctlr | String. The ID of the PowerHome MQTT controller
as_topic | String. The MQTT topic to subscribe to. Wildcards are allowed
ai_qos | Integer. The QOS (Quality of Service) level. Valid values are 0, 1, and 2
ai_type | Integer. Specifies how the subscription request is handled within PowerHome. A value of 0 will queue the request with the specified controller. Any other value will cause the the controller to immediately send the request and receive feedback of success/failure
Return value
Integer. Returns 0 if request for subscription was queued successfully when ai_type = 0. Returns 0 if subscription to topic was successful when ai_type <> 0. Returns -1 if the controller ID is not found. Returns -51 if the command is not supported by the controller. Returns -11 if an error occurs during subscription when ai_type <> 0
Usage
Use this function to subscribe to MQTT topics using a currently connected PowerHome MQTT controller. The PowerHome MQTT controller allows you to declare Analog I/O devices with a Publish Topic and a Subscribe Topic and will already be subscribed by the controller. The PH MQTT controller also supports Subscribed topics delcared in the PowerHome Explorer under PowerHome->MQTT->MQTT Subscribe. You would typically use this function to subscribe to topics that are NOT already subscribed to with the Analog I/O section or the MQTT Subscribe section (doing so would be redundant). If you subscribe to a topic using this function that is not already subscribed via Analog I/O or MQTT Subscribe, then the MQTT controller will fire a Generic Controller trigger for the controller on Command 1, Option 1 whenever a published message matching the topic is received. The trigger variables will hold the topic, the message, the QOS, the retain flag, and whether or not the message is a duplicate
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_mqttsub("MQTT","home/1stfloor/+/temperature",0,1) - Returns a 0 if the topic subscription was successful. Returns -11 if an error occurred. This example subscribes to a wildcard topic for all temperatures on the 1st floor


ph_mqttunsub

ph_mqttunsub PowerHome formula function
Description
Allows the specified PowerHome MQTT controller to unsubscribe from topics
Syntax
ph_mqttunsub ( as_ctlr, as_topic, ai_type )
Argument | Description
as_ctlr | String. The ID of the PowerHome MQTT controller
as_topic | String. The topic you wish to unsubscribe from
ai_type | Integer. Specifies how the unsubscription request is handled within PowerHome. A value of 0 will queue the request with the specified controller. Any other value will cause the the controller to immediately send the unsubscribe request and receive feedback of success/failure
Return value
Integer. Returns 0 if request to unsubscribe was queued successfully when ai_type = 0. Returns 0 if topic unsubscribe was successful when ai_type <> 0. Returns -1 if the controller ID is not found. Returns -51 if the command is not supported by the controller. Returns -11 if an error occurs during unsubscribing from topic when ai_type <> 0
Usage
Use this function to unsubscribe from MQTT topics using a currently connected PowerHome MQTT controller. You should only use this function to unsubscribe from topics that were previously subscribed to with the ph_mqttsub( ) function.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_mqttunsub("MQTT","home/1stfloor/+/temperature",0) - Returns a 0 if the unsubscribe topic was successfully queued.


ph_reinitialize

ph_reinitialize PowerHome formula function
Description
Reinitializes the PowerHome environment.
Syntax
ph_reinitialize ( )
Return value
Integer. Returns a 0. Reinitializes the PowerHome environment similar to shutting down and restarting PowerHome. Causes controllers and other system variables to be re-read from the database.


ph_setanalogout

ph_setanalogout PowerHome formula function
Description
Sets the value of an analog output defined in the Analog I/O screen.
Syntax
ph_setanalogout ( id, value )
Argument | Description
id | String. The ID of the analog output as defined within the Analog I/O screen.
value | String. The value to set the analog output to. This value MUST be a string and in the format of a CALCULATED value as defined within the Analog I/O screen. This value will be converted to the appropriate RAW value using the formula defined in the Analog I/O screen. This RAW value will then be sent to the controller. See usage below for valid values for special Analog I/O devices such as Insteon devices that have functionality extended as an analog device.
Return value
Integer. Returns a 0 if successful. Returns - 100 if the ID cannot be found. When this function is executed, the controller, unit, and point is looked up within the Analog I/O table and these values are then passed to the controller. If these values are entered improperly in the Analog I/O screen, then the following errors may be returned: - 1 is returned if the controller is not available, - 2 is returned if the controller does not support analog outputs, - 3 is returned if the unit is out of range, - 4 is returned if the point is out of range. - 5 is returned if the value is out of range.
Usage
This function is similar to the ph_setotheranalogout function except that the output MUST be defined within the Analog I/O screen. Also, this function requires the CALCULATED value while the ph_setotheranalogout function only works with RAW values.

This function also allows you to set special Analog devices. For these parameters, you can either use the Calculated to Raw formula to convert to a raw value or the built in commands that are listed below:
For GarageHawk devices you can specify a value of "close" to trigger the garage door close command.
For EZRain/EZFlora devices you can specify values of "off","v1" ,"v2" ,"v3" ,"v4" ,"v5", "v6", "v7", "v8", "pgm1", "pgm2", "pgm3", "pgm4", "next", and "prev" to control the valves.
For IOLinc devices you can specify a value of either "open" or "closed" to control the relay output.
For Insteon Thermostat Mode valid values are: "off", "heat", "cool", "auto", "fanon", "fanoff", "pgm", "pgm ht", and "pgm cl".
For Elk M1 Thermostat Mode valid values are: "off", "heat", "cool", "auto", "emgheat".
For Elk M1 Thermostat Fan you can specify "auto" or "on".
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setanalogout("HOME MOTION","{HOME-MOTION}")


ph_setanalogoutraw

ph_setanalogoutraw PowerHome formula function
Description
Sets the value of an Analog I/O device using a RAW value vs using a CALC value like the ph_setanalogout( ) function
Syntax
ph_setanalogoutraw ( as_id, al_value )
Argument | Description
as_id | String. The ID of the Analog I/O device you wish to set the value for
al_value | Long. The RAW value you would like assigned to the Analog I/O device
Return value
Integer. Returns 0 if the command to set the Analog I/O device is successfully queued with the associated controller. Returns -100 if the ID in the as_id parameter is not valid. Returns -1 if the associated controller is not found or active. Returns -51 if the command is not supported by the controller.
Usage
Use this function to queue a request to change an Analog I/O device with its associated controller using a RAW value vs using a CALC value. Most of the time you will want to use the ph_setanalogout( ) to set Analog I/O devices using a CALC value. If for some reason a CALC value is not desired or available, then you can use this function to set a RAW value instead
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setanalogoutraw("FLOOR1TSTATCOOLSP",76) - Returns 0 if the command was successfully queued with the controller


ph_setanalogvalue

ph_setanalogvalue PowerHome formula function
Description
Allows the setting of the raw value, the calc value, and the calc message along with the optional firing of any triggers of Analog device types.
Syntax
ph_setanalogvalue ( al_value, as_calcvalue, as_calcmsg, al_flags )
ph_setanalogvalue ( as_id, al_value, as_calcvalue, as_calcmsg, al_flags )
Argument | Description
as_id | String (Optional). The ID of the analog device type. If this parameter is omitted, the system variable ANALOG will be used for the ID
al_value | Long. The raw value to set the analog device type to
as_calcvalue | String. The calc value to set for the specified analog device
as_calcmsg | String. The calc message to set for the analog device
al_flags | Long. The flags for controlling which values are used and how the function performs
Return value
Integer. Returns 0 if successful. Returns 1 if the ID cant be found and 2 if an error occurs while updating the analogio table
Usage
Use this function to directly set the values of an analog device type without using a controller

The al_flags parameter is the sum of individual flag values. These flag values are:

1 - Update the raw value with the supplied al_value raw value. This flag will override a flag 32
2 - Update the calc value with the supplied as_calcvalue value. This flag will override a flag 64
4 - Update the calc message with the supplied as_calcmsg message
8 - Update the Device Status screen and any Remote DS clients with the new values
16 - Fire any triggers associated with the updating of the specified analog device type
32 - Apply the calctoraw formula to the supplied as_calcvalue and set the raw value to the result. A flag 1 will override this flag
64 - Apply the rawtocalc formula to the supplied al_value and set the calc value to the result. A flag 2 will override this flag
128 - Apply the averaging settings for the Analog device to the supplied al_value parameter. This happens before flags 1, 64, and 256 take effect
256 - If the Analog device has a user range specified, this flag will take the supplied al_value parameter and do a lookup in the range table and update the as_calcvalue parameter will this value
512 - Set the raw value to the original raw value currently stored in the Analog I/O table
1024 - Set the calc value to the original calc value currently stored in the Analog I/O table
2048 - Set the raw value to the value in system variable RAW
4096 - Set the calc value to the value in system variable CALC
8192 - Set the foreground color for the Analog device to the value in system variable FORECOLOR
16384 - Set the background color for the Analog device to the value in system variable BACKCOLOR
32768 - Set system variable ORIGRAW to the original Analog raw value currently stored for the Analog device. If this flag is not set, system variable ORIGRAW will be set to the supplied al_value parameter
65536 - Update the raw value with the value in system variable ORIGRAW

Certain flags will counteract other flags and some combinations of flags will not make sense. Understanding the order in which the flags are applied will allow you to combine flags to achieve the desired results. The flags are executed in the following order: 32768, 128, 256, 32, 64, 512, 1024, 2048, 4096, 65536, 8192, 16385, 1, 2, 4, 8, 16

The proper flags value to update an analog device's raw value, calc value, and update the Device Status screen would be 11 (1 + 2 + 8). No triggers will be fired and the calc message will be unchanged.

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setanalogvalue("TEMPERATURE",78,"","degrees F",1 + 4 + 8 + 16 + 64 + 32768) - This example updates the TEMPERATURE Analog I/O device by first storing the original analog I/O raw value in system variable ORIGRAW. The new raw value is set to 78. The rawtocalc formula is executed using the raw value of 78 and the new calc value is set to the result. The calcmsg is set to "degrees F". The Device Status screen is updated and triggers are fired


ph_setdeviceval

ph_setdeviceval PowerHome formula function
Description
Allows the user to set certain device value parameters within the PowerHome database without having to resort to using SQL
Syntax
ph_setdeviceval ( type, id, parm, value )
Argument | Description
type | Integer. The type of data you'd like to update. Current valid values are 5 for Insteon devices and 20 for UPB devices. Any other type will cause the function to return either a 1 or 4.
id | String. The ID of the device whose value you'd like to update.
parm | String. The specific value for the device that you'd like to update. See usage below.
value | Double. The actual value to be written into the column identified by the parm parameter.
Return value
Integer. Returns the result of the operation. Success will return a 0. An invalid type will be either 1 or 4. If an error occurs in SQL during the update, 2 will be returned. If an invalid parm is specified, 3 will be returned.
Usage
Use this function to update specific device parameter values within the PowerHome database without having to know or write SQL.

For type = 5 (Insteon), the following values are valid for the parm parameter. Each value will match an appropriate column in the Insteon device table.
commcnt
ackcnt
nakcnt
timeoutcnt
ttacnt
xcommcnt
xackcnt
xnakcnt
xtimeoutcnt
xttacnt
failedmatch
iengine
firmware
activeflag

For type = 20 (UPB), the following values are valid for the parm parameter. Each value will match an appropriate column in the UPB device table.
commcnt
ackcnt
nakcnt
avgss
firmware
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_setdeviceval(5,"KITCHEN","commcnt",0)
The above example will set the commcnt for the Insteon KITCHEN device to 0.


ph_setdigitalout

ph_setdigitalout PowerHome formula function
Description
Sets or clears a digital output defined in the Digital I/O screen.
Syntax
ph_setdigitalout ( id, value )
Argument | Description
id | The ID of the digital output as defined within the Digital I/O screen.
value | The value to set the digital output to. 1 will turn the digital output on. 0 will turn the digital output off.
Return value
Integer. Returns a 0 if successful. Returns - 100 if the ID cannot be found. When this function is executed, the controller, unit, and point is looked up within the Digital I/O table and these values are then passed to the controller. If these values are entered improperly in the Digital I/O screen, then the following errors may be returned: - 1 is returned if the controller is not available, - 2 is returned if the controller does not support digital outputs, - 3 is returned if the unit is out of range, - 4 is returned if the point is out of range.
Usage
This function is similar to the ph_setotherdigitalout function except that the output MUST be defined within the Digital I/O screen.


ph_upb

ph_upb PowerHome formula function
Description
Control a UPB device.
Syntax
ph_upb ( id, cmd, arg1, arg2 )
Argument | Description
id | String. The ID of the UPB device to control.
cmd | Integer. The UPB command to perform on the device.
arg1 | Integer. Argument 1 for the command.
arg2 | Integer. Argument 2 for the command.
Return value
Integer. Returns a 0 if successful. Returns - 100 if the ID cannot be found. -1 is returned if the controller is not available, -2 is returned if the controller does not support UPB.
Usage
Use this funciton to send UPB commands directly to a single device. Valid commands are 34 for Goto (arg1 is level, arg2 is ramp), 35 for Fade Start (arg1 is level, arg2 is ramp), 36 for Fade Stop (arg1 and arg2 ignored), 37 for Blink (arg2 is blink rate), 38 for Indicate (arg1 is level, arg2 is ramp). You can also use the enumerated values ugoto, ufadestart, ufadestop, ublink, and uindicate.


ph_upblink

ph_upblink PowerHome formula function
Description
Control a set of linked UPB devices.
Syntax
ph_upblink ( id, cmd, arg1, arg2 )
Argument | Description
id | String. The ID of the UPB link to control.
cmd | Integer. The UPB command to send to the linked devices.
arg1 | Integer. Argument 1 for the command.
arg2 | Integer. Argument 2 for the command.
Return value
Integer. Returns a 0 if successful. Returns - 100 if the ID cannot be found. -1 is returned if the controller is not available, -2 is returned if the controller does not support UPB.
Usage
Use this funciton to send UPB commands to a group of linked devices. Valid commands are 32 for Activate Link (arg1 and arg2 are ignored), 33 for Deactivate Link (arg1 and arg2 are ignored), 34 for Goto (arg1 is level, arg2 is ramp), 35 for Fade Start (arg1 is level, arg2 is ramp), 36 for Fade Stop (arg1 and arg2 ignored), 37 for Blink (arg2 is blink rate), 38 for Indicate (arg1 is level, arg2 is ramp). You can also use the enumerated values uactlink, udeactlink, ugoto, ufadestart, ufadestop, ublink, and uindicate.


ph_upbraw

ph_upbraw PowerHome formula function
Description
Send raw UPB commands to a single UPB device.
Syntax
ph_upbraw ( ctlr, nid, uid, chan, cmd, arg1, arg2 )
Argument | Description
ctlr | String. The ID of the UPB controller to use.
nid | Integer. The Network ID to send to.
uid | Integer. The Unit ID to send to.
chan | Integer. The channel to send to.
cmd | Integer. The command to send.
arg1 | Integer. Argument 1 for the command.
arg2 | Integer. Argument 2 for the command.
Return value
Integer. Returns a 0 if successful, -1 is returned if the controller is not available, -2 is returned if the controller does not support UPB.
Usage
Use this funciton to send raw UPB commands to single UPB device. Valid commands are 34 for Goto (arg1 is level, arg2 is ramp), 35 for Fade Start (arg1 is level, arg2 is ramp), 36 for Fade Stop (arg1 and arg2 ignored), 37 for Blink (arg2 is blink rate), 38 for Indicate (arg1 is level, arg2 is ramp). You can also use the enumerated values ugoto, ufadestart, ufadestop, ublink, and uindicate.


ph_upbrawlink

ph_upbrawlink PowerHome formula function
Description
Send raw UPB commands to a group of linked UPB devices.
Syntax
ph_upbrawlink ( ctlr, nid, lid, cmd, arg1, arg2 )
Argument | Description
ctlr | String. The ID of the UPB controller to use.
nid | Integer. The Network ID to send to.
lid | Integer. The Link ID to send to.
cmd | Integer. The command to send.
arg1 | Integer. Argument 1 for the command.
arg2 | Integer. Argument 2 for the command.
Return value
Integer. Returns a 0 if successful, -1 is returned if the controller is not available, -2 is returned if the controller does not support UPB.
Usage
Use this funciton to send raw UPB commands to group of linked UPB devices. Valid commands are 32 for Activate Link (arg1 and arg2 are ignored), 33 for Deactivate Link (arg1 and arg2 are ignored), 34 for Goto (arg1 is level, arg2 is ramp), 35 for Fade Start (arg1 is level, arg2 is ramp), 36 for Fade Stop (arg1 and arg2 ignored), 37 for Blink (arg2 is blink rate), 38 for Indicate (arg1 is level, arg2 is ramp). You can also use the enumerated values uactlink, udeactlink, ugoto, ufadestart, ufadestop, ublink, and uindicate.


ph_x10

ph_x10 PowerHome formula function
Description
Sends an X10 command to the specified controller.
Syntax
ph_x10 ( s, s, n, n )
Argument | Description
s | The ID of the controller you wish to send the X10 command to.
s | A string representing the housecode portion of the X10 command. If you are sending a preset dim command, set this string to "PRESET DIM"
n | An integer representing the unitcode portion of the X10 command. If you are addressing a specific unitcode, use the unitcode number. If this is a standard command, add 100 to the command. An on command is normally 2 so you would encode it as 102. If this is an extended command, then add 200 to the unitcode. If you were sending an extended command to unit 5, then encode it as 205. If this is a preset dim command, then add 300 to the preset dim level. If you were sending a preset dim command as level 26 then encode it as 326.
n | The dim/bright or extended command data. If this is an addressing command or a standard command, use a value of 0. If this is a standard dim/bright command (unitcode value of 104 or 105) place a value between 0 and 100 inclusive here as the dim/bright percentage. A value of 30 would cause the level to be changed by 30% from its current level. If this is an extended command (200 added to the unitcode), place the extended data in this field.
Return value
Integer. Returns a 0.


ph_x10btn

ph_x10btn PowerHome formula function
Description
Sends a full X10 standard command including addressing.
Syntax
ph_x10btn ( s, n, n )
Argument | Description
s | A string representing the ID of the X10 unit you wish to control.
n | The command you would like sent to the specified X10 ID. Valid values are 2 for on, 3 for off, 4 for dim, 5 for brighten, and 100 for absolute level. You may also use the enumerated types: xon, xoff, xdim, xbright, adim
n | The level you would like to use for commands 4, 5, and 100. Use a 0 for commands 2 and 3.
Return value
Integer. Returns a 0 if successful and 1 if an error occurred while retrieving information for the specified ID. This function requires that you have already defined an X10 device ID in the X10 Devices screen. In that screen, you will associate a controller with a particular housecode/unitcode. If you want to send raw X10 commands regardless of whether you've defined them in the X10 Device screen, use the ph_x10 function. This function is also handy when you want to set a light to a specific level. By setting the command to 100, PowerHome will attempt to set the lamp to the specified level. It will do this by using 1 of 3 available methods in the following order based upon the flag settings of the X10 device type. If the lamp supports extended commands, then a direct to level extended command will be generated. If the lamp supports preset dim, then the corresponding preset dim command will be sent. If extended and preset dim is not supported, then PowerHome will lookup the level it currently has stored and calculate the appropriate dimming or brightening necessary to set the light at the requested level.


asc

asc PowerHome formula function
Description
Converts the first character of a string to its Unicode integer value.
Syntax
asc ( string )
Argument | Description
string | The string for which you want the Unicode value of the first character
Return value
Integer. Returns the Unicode value of the first character in string.
Usage
Use Asc to test the case of a character or manipulate text and letters.

To find out the case of a character, you can check whether its Unicode value is within the appropriate range.


asca

asca PowerHome formula function
Description
Converts the first character of a string to its ASCII integer value.
Syntax
asca ( string )
Argument | Description
string | The string for which you want the ASCII value of the first character
Return value
Integer. Returns the ASCII value of the first character in string.
Usage
Use AscA to test the case of a character or manipulate text and letters.

To find out the case of a character, you can check whether its ASCII value is within the appropriate range.


b2d

b2d PowerHome formula function
Description
Converts a binary string to a decimal number.
Syntax
b2d( binnum )
Argument | Description
binnum | String. The binary string to convert to a decimal number.
Return value
Unsigned Long. Returns the converted decimal number
Usage
None
Examples
The following examples demonstrate typical syntax/usage for this function.
b2d("110101111100")
The above example returns the decimal number 3452


char

char PowerHome formula function
Description
Converts an integer to a Unicode character.
Syntax
char ( n )
Argument | Description
n | The integer you want to convert to a Unicode character
Return value
String. Returns the character whose Unicode value is n.


chara

chara PowerHome formula function
Description
Converts an integer to an ASCII character.
Syntax
chara ( n )
Argument | Description
n | The integer you want to convert to an ASCII character
Return value
String. Returns the character whose ASCII value is n.


d2b

d2b PowerHome formula function
Description
Converts decimal number into binary string
Syntax
d2b( number, length )
Argument | Description
number | Unsigned Long. The decimal number to be converted.
length | Integer. Specifies the desired length of the binary string.
Return value
String. Returns the converted binary string
Usage
Set the length parameter to 0 to have the function return the significant digits of the conversion (no leading zeros).
Examples
The following examples demonstrate typical syntax/usage for this function.
d2b(3452,0)
The above example will return a string value of "110101111100".


d2h

d2h PowerHome formula function
Description
Converts decimal number into hexadecimal string
Syntax
d2h( number, length )
Argument | Description
number | Unsigned Long. The decimal number to be converted.
length | Integer. Specifies the desired length of the hexadecimal string.
Return value
String. Returns the converted hexadecimal string
Usage
Set the length parameter to 0 to have the function return the significant digits of the conversion (no leading zeros).
Examples
The following examples demonstrate typical syntax/usage for this function.
d2h(3452,0)
The above example will return a string value of "D7C".


date

date PowerHome formula function
Description
Converts a string whose value is a valid date to a datatype value of date.
Syntax
date ( string )
Argument | Description
string | A string containing a valid date (such as "Jan 1, 1998", or "12-31-99") that you want returned as a date
Return value
Date. Returns the date in string as a date. If string does not contain a valid date, Date returns NULL.
Usage

The value of the string must be a valid date.

Valid dates can include any combination of day (1-31), month (1-12 or the name or abbreviation of a month), and year (two or four digits). Leading zeros are optional for month and day. If the month is a name or an abbreviation, it can come before or after the day; if it is a number, it must be in the month location specified in the Windows control panel. A 4-digit number is assumed to be a year.

An expression has a more limited set of data types than the functions that can be part of the expression.

Although the Date function returns a date value, the whole expression is promoted to a DateTime value. Therefore, if your expression consists of a single Date function, it will appear that Date returns the wrong data type.

Examples
The following examples demonstrate typical syntax/usage for this function.
• date("1-23-15") --> evaluates to: 01/13/2015
• date("Jan 23 2015") --> evaluates to: 01/13/2015
• date(month(today())+"-1-"+year(today())) --> returns: the first day of the current month eg, 01/01/2015
• relativedate(date(year(today()),if(month(today())=12,1,month(today())+1),1), -1) --> returns: the last day of the current month eg, 01/31/2015


datetime

datetime PowerHome formula function
Description
Combines separate date and a time values into a DateTime value.

The function supports two different types of data syntax; either a separate date and optional time value or a single string containing a valid date and optional time.

See the Date / Time Functions section for detailed information concerning date / time formats.

Syntax 1: A Date and optional Time datatypes. This syntax expects a date datatype and an optional time datatype. If the optional time datatype is specified, the values MUST be seperated with a comma.

Syntax 2: A string containing a valid date and optionally a valid time. The date and time formats supported are the same as those in the date() and time() functions respectively. You can separate the date and time values by either a comma or a space.

Syntax 1 (Separate date and time datatypes)
datetime ( date {, time } )
Argument | Description
date | A valid date value (function output eg, date() or a date 'literal' value such as 2010-12-15)
time (optional) | A valid time value (function output eg, time() or time 'literal' such as 10:25:23:456).

Syntax 2 (A single string)
datetime ( dtstring )
Argument | Description
dtstring | A string containing a valid date or datetime. This string can contain the date in a variety of formats and can have the optional time separated by a comma or a space character. See the date() and time() functions for valid formats

Return value
Returns a DateTime value based on the values passed in the function parameters. If time is omitted, 00:00:00.000000 (midnight) is used by default.

Examples
The following examples demonstrate typical syntax/usage for this function.
Syntax 1
• datetime(relativedate(today(),5),17:00:00) --> evaluates to: 01/18/2015 17:00:00
• datetime(date("01/01/2015")) --> evaluates to: 01/01/2015 00:00:00
• datetime(today(),08:15:00:0000) --> evaluates to: 01/11/2015 08:15:00 (Note the seconds are rounded off without fractional seconds.)
• datetime(2010-12-15, 10:49:00) --> evaluates to: 12/15/2010 10:49:00

Syntax 2
• datetime("01/14/2015,08:15:00") --> evaluates to: 01/14/2015 08:15:00
• datetime("01-14-15 08:15:05") --> evaluates to: 01/14/2015 08:15:05
• datetime("2015/01/14,08:15:00") ---> evaluates to: 01/14/2015 08:15:00
• datetime("01-10-2015, 14:08:32") ---> evaluates to: 01/10/2015 14:08:32
• datetime("jan 10 2015 17:00:00") ---> evaluates to: 01/10/2015 17:00:00
• datetime("01/10/2015") ---> evaluates to: 01/10/2015 00:00:00

At first inspection one might think that Syntax 2 is easier and much more flexible so why even bother with Syntax 1?

However, using Syntax 2, the following function would have to be written as: datetime(string(relativedate(today(),5),"mm/dd/yyyy") + " 17:00:00")

Using syntax 1, the same function looks like this: datetime(relativedate(today(),5),17:00:00)


dec

dec PowerHome formula function
Description
Converts a string to a decimal number using the currently defined region settings.
Syntax
dec ( s )
Argument | Description
s | A string whose value you want returned as a decimal value.
Return value
Decimal. Returns the value of the string as a decimal. If the string is not a valid number or if it contains an incompatible datatype, Dec returns 0.
Usage
The dec function is region aware. This function will work with the string representation of a number using the current region settings specified within the OS. This function is very useful for regions where the period character is used as the thousands separator and the comma character is used as a decimal point. Without this function, PowerHome interprets numbers using the standard region settings for the United States.


double

double PowerHome formula function
Description
Converts a string to a double number.
Syntax
double ( s )
Argument | Description
s | A string whose value you want returned as a double value.
Return value
Double. Returns the value of the string as a double. If the string is not a valid number or if it contains an incompatible datatype, Double returns 0.
Usage
To distinguish between a string whose value is the number 0 and a string whose value is not a number, use the IsNumber function before calling the Double function.


h2d

h2d PowerHome formula function
Description
Converts a hexadecimal string to a decimal number.
Syntax
h2d( hexnum )
Argument | Description
hexnum | String. The hexadecimal string to convert to a decimal number.
Return value
Unsigned Long. Returns the converted decimal number
Usage
None
Examples
The following examples demonstrate typical syntax/usage for this function.
h2d("D7C")
The above example returns the decimal number 3452


h2s

h2s PowerHome formula function
Description
Decodes a hex-encoded string to its non hex-encoded form with option to save directly to a file
Syntax
h2s ( as_input, as_file, ai_type )
Argument | Description
as_input | String. The hex-encoded data contained within a string. Ex: "54455354" which is the ANSI hex-encoded value for "TEST"
as_file | String. The full path and filename that you want the decoded hex to be saved to. If not saving to a file use an empty string ""
ai_type | Integer. The type of output to be returned by the function. See Usage below.
Return value
String. Returns the decoded data as a string if the ai_type parameter is 0 or 1. For ai_types 2 thru 6, returns "*SUCCESS" if successful and "*ERROR" if an error occurs.
Usage
Use this function to convert hex-encoded data back to its original format. If you use ai_type = 0, the function expects the encoded hex string to be in ANSI format (1 byte = 2 hex digits = 1 character). If you use ai_type = 1, the hex encoded string should be in UTF8 format (2 bytes = 4 hex digits = 1 character). You should not use ai_type 0 or 1 for binary encoded hex data. The following ai_type values are available:
  • 1 - Return the decoded hexadecimal string from the function. The hex string should contain UTF8 encoded data.
  • 2 - Save the decoded hexadecimal string in the file specified in the second parameter. The file will be appended to and the encoding will be what currently exists in the file.
  • 3 - Save the decoded string in the specified file. This operation will overwrite the file if it already exists and will save with ANSI encoding.
  • 4 - Save the decoded string in the specified file. This operation will overwrite the file if it already exists and will save with UTF8 encoding.
  • 5 - Save the decoded string in the specified file. This operation will overwrite the file if it already exists and will save with UTF16LE encoding.
  • 6 - Save the decoded string in the specified file. This operation will overwrite the file if it already exists and will save with UTF16BE encoding.
  • 0 - or any other value will return the decoded hexadecimal string from the function. The hex string should contain ANSI encoding.
Examples
The following examples demonstrate typical syntax/usage for this function.
. h2s("54455354","",0) - Returns the string "TEST"
. h2s("54455354","c:\powerhome\test.txt",2) - Appends the string "TEST" to the c:\powerhome\test.txt file
. h2s("5400650073007400","",1) This call will return the string "Test".
. h2s("5400650073007400","c:\output.txt",4) This call will create the file c:\output.txt with UTF8 encoding and write the string "Test" to it. The function will return "*SUCCESS" if succesful and will return "*ERROR" if it fails.


integer

integer PowerHome formula function
Description
Converts the value of a string to an integer.
Syntax
integer ( string )
Argument | Description
string | The string you want returned as an integer
Return value
Integer. Returns the contents of string as an integer if it succeeds and 0 if string is not a number.


long

long PowerHome formula function
Description
Converts the value of a string to a long.
Syntax
long ( string )
Argument | Description
string | The string you want returned as a long
Return value
Long. Returns the contents of string as a long if it succeeds and 0 if string is not a valid number.


lower

lower PowerHome formula function
Description
Converts all the characters in a string to lowercase.
Syntax
lower ( string )
Argument | Description
string | The string you want to convert to lowercase letters
Return value
String. Returns string with uppercase letters changed to lowercase if it succeeds and the empty string ("") if an error occurs.


number

number PowerHome formula function
Description
Converts a string to a number.
Syntax
number ( string )
Argument | Description
string | The string you want returned as a number
Return value
A numeric data type. Returns the contents of string as a number. If string is not a valid number, Number returns 0.


ph_base64decode

ph_base64decode PowerHome formula function
Description
Converts a base64 string back to its normal representation.
Syntax
ph_base64decode ( as_input )
ph_base64decode ( as_input, ai_type )
ph_base64decode ( as_input, as_output, ai_type )
Argument | Description
as_input | String. The base64 string to decode
as_output | String (Optional). A full path and filename to write the decoded output to (only used if ai_type = 3)
ai_type | Integer (Optional). Determines how the decoded bytes are returned. Valid values are 0, 1, 2, and 3. If parameter is not included, a value of 0 is assumed. See Usage below
Return value
String. Returns the decoded base64 input as determined by the ai_type parameter. If ai_type = 3, then the return value will be "*SUCCESS*".
Usage
Use this function to decode base64 encoded data. When used to decode authorization via a webpage, the format is the userid, a colon, and then the password.

The allowed values for the ai_type parameter are:

  • 0 - Return the decoded bytes as ASCII encoding
  • 1 - Return the decoded bytes as UTF8 encoding
  • 2 - Return the decoded bytes as a hex encoded string
  • 3 - Write the decoded bytes to the path/filename contained in as_output. Returns "*SUCCESS*"
  • Any other value will return an empty string ""
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_base64decode("dXNlcm5hbWU6cGFzc3dvcmQ=") - Returns the decoded text "username:password"
    . ph_base64decode("dXNlcm5hbWU6cGFzc3dvcmQ=",2) - Returns the decoded text as the hex encoded string: "757365726E616D653A70617373776F7264"


ph_base64encode

ph_base64encode PowerHome formula function
Description
Converts a string to its base64 representation.
Syntax
ph_base64encode ( as_input )
ph_base64encode ( as_input, ai_type )
Argument | Description
as_input | String. A string of data or full path and filename of data you wish to base64 encode
ai_type | Integer (Optional). Determines how the base64 encoding is to be done. Valid values are 0, 1, 2, and 3. If parameter is not included, then a value of 0 is assumed. See Usage below
Return value
String. Returns the base64 representation of the data.
Usage
Use this function to base64 encode a supplied string of data or a specified path/filename. When used to validate authorization via a webpage, the format is the userid, a colon, and then the password.

Valid values for ai_type are:

  • 0 - Interpret the data in as_input as an ASCII string
  • 1 - Interpret the data in as_input as a UTF-8 string
  • 2 - Decode the hex encoded string in as_input and then encode as base64
  • 3 - Interpret as_input as a path/filename. Open the specified file and encode its contents
  • Any other value will result in an empty string "" being returned
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_base64encode("username:password") - Returns the base64 encoded string: "dXNlcm5hbWU6cGFzc3dvcmQ= "
    . ph_base64encode()


ph_ctof

ph_ctof PowerHome formula function
Description
Converts a temperature value in Celcius to Farenheight
Syntax
ph_ctof ( temp )
Argument | Description
temp | Integer. The temperature value in Celcius
Return value
Double. Returns the converted temperature in degrees Farenheight.


ph_fixhtmlquotes

ph_fixhtmlquotes PowerHome formula function
Description
Replaces single and double quotes embedded within a string with the HTML escape code equivalent.
Syntax
ph_fixhtmlquotes ( s )
Argument | Description
s | The string in which you wish to replace single and double quotes.
Return value
String. Returns the string with single and double quotes replaced with their HTML escape code equivalent. Single quotes will be replace with ' and double quotes will be replaced with "


ph_fixjsquotes

ph_fixjsquotes PowerHome formula function
Description
Takes a string of text and add's escape characters appropriate for Javascript to single and double quotes.
Syntax
ph_fixjsquotes ( text )
Argument | Description
text | String. The text to be escaped.
Return value
String. Returns the text with single and double quotes properly escaped. All single quotes will be replaced with \' and double quotes will be replaced with \".


ph_flattenjson

ph_flattenjson PowerHome formula function
Description
Takes a string containing valid JSON data and flattens it into a list of name/value pairs with the specified separator
Syntax
ph_flattenjson ( as_json, as_sep, ai_flags, ai_type )
Argument | Description
as_json | String. A string containing valid JSON
as_sep | String. The separator character(s) you would like to use for the name/value pairs
ai_flags | Integer. Flags controlling how the JSON is flattened. See Usage below
ai_type | Integer. The particular method to use for the flattening of JSON data. Valid values are 0, 1, and 2
Return value
String. Returns the JSON data flattened into a name/value pair string with 1 name/value pair per line. If an error occurs, returns a string starting with "*ERROR*" followed by a description of the error
Usage
Use this function to "flatten" JSON data into name/value pairs such that other functions within PowerHome (such as ph_extractval or the regular expression functions) can be used to extract specific data.

The ai_type parameter controls the specific method used to flatten the JSON data with each method returning potentially different results. Type 0 uses a character by character parsing routine to flatten the JSON data. Type 1 uses a C# dictionary and JTokens to flatten the JSON. Type 2 uses a C# dictionary and JObjects to deserialize and flatten the JSON.

Each of the 3 types (0, 1, 2) allow different ai_flag parameters to be specified to control the operation. Not all flags are supported in all types. The supported flag values and which types they apply to are listed below. The desired flag values are added together to achieve the final result to be passed in the ai_flags parameter:

  • 1 - Encloses the flattened JSON NAME in double quotes. Supported by types 0, 1, and 2.
  • 2 - Encloses the flattened JSON VALUE in double quotes. Supported by types 0, 1, and 2.
  • 4 - Strip commas contained within a JSON NAME. Supported by type 0.
  • 8 - Strip commas contained within a JSON VALUE. Supported by type 0.
  • 16 - Strip double quotes contained with a JSON VALUE. Supported by type 0.
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    Assume the file named c:\powerhome\json.txt contains the following JSON data: {"people":[{"name":"John","age":31,"city":"New York","phones":["4075551212","3215551212","8885551212"]}]}

    . ph_flattenjson(ph_readfile("c:\powerhome\json.txt"),":",0,0) will return:
    people.name:John
    people.age:31
    people.city:New York
    people.phones:[4075551212,3215551212,8885551212]

    . ph_flattenjson(ph_readfile("c:\powerhome\json.txt"),":",0,1) will return:
    people.0.name:John
    people.0.age:31
    people.0.city:New York
    people.0.phones.0:4075551212
    people.0.phones.1:3215551212
    people.0.phones.2:8885551212

    . ph_flattenjson(ph_readfile("c:\powerhome\json.txt"),":",0,2) will return:
    people[0].name:John
    people[0].age:31
    people[0].city:New York
    people[0].phones[0]:4075551212
    people[0].phones[1]:3215551212
    people[0].phones[2]:8885551212


ph_flattenxml

ph_flattenxml PowerHome formula function
Description
This function takes a string in XML format and flattens it to a carriage return linefeed separated list of name/value pairs
Syntax
ph_flattenxml ( as_xml, as_sep, ai_flags, ai_type )
Argument | Description
as_xml | String. The XML data to be flattened
as_sep | String. The separator character(s) to be used to separate the name/value pairs in the output
ai_flags | Integer. Flags controlling how the flattened data is returned. See Usage below
ai_type | Integer. The type of flattening to be performed. Valid values are 0 and 1
Return value
String. The flattened XML data is returned as a carriage return linefeed separated list of name/value pairs if successful. If an error occurs, the string "*ERROR*" followed by the error details will be returned.
Usage
Use this function to "flatten" XML data into name/value pairs to make it easier for other PowerHome functions to extract specific data.

The ai_type parameter controls the specific method used to flatten the XML data with each the two methods returning potentially different results. Both methods (ai_type = 0 and ai_type = 1) use C# XDocuments to parse the XML.

Both type 0 and type 1 allow different ai_flag parameters to be specified to control the operation. Not all flags are supported in both types. The supported flag values and which types they apply to are listed below. The desired flag values are added together to achieve the final result to be passed in the ai_flags parameter:

  • 1 - Encloses the flattened XML NAME in double quotes. Supported by both types 0 and 1.
  • 2 - Encloses the flattened XML VALUE in double quotes. Supported by both types 0 and 1.
  • 4 - Preceed XML array numbers with a period character instead of an open bracket. Supported only by type 1.
  • 8 - Append XML array numbers with a period character instead of a close bracket. Supported only by type 1.
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    Assume that the file named c:\powerhome\xmldata.txt contains the following XML data: <XMLROOT><people><name>John</name><age>31</age><city>New York</city><phones>4075551212</phones><phones>3215551212</phones><phones>8885551212</phones></people></XMLROOT>

    . ph_flattenxml(ph_readfile("c:\powerhome\xmldata.txt"),0,0) will return:
    XMLROOT.people.name:John
    XMLROOT.people.age:31
    XMLROOT.people.city:New York
    XMLROOT.people.phones:4075551212
    XMLROOT.people.phones:3215551212
    XMLROOT.people.phones:8885551212

    . ph_flattenxml(ph_readfile("c:\powerhome\xmldata.txt"),0,1) will return:
    XMLROOT.people.name:John
    XMLROOT.people.age:31
    XMLROOT.people.city:New York
    XMLROOT.people.phones[0]:4075551212
    XMLROOT.people.phones[1]:3215551212
    XMLROOT.people.phones[2]:8885551212


ph_fromunixtime

ph_fromunixtime PowerHome formula function
Description
Converts a longlong value in standard Unix time (number of seconds past midnight, Jan 1, 1970) into a standard PowerHome datetime value
Syntax
ph_fromunixtime ( al_unixtime, ai_utcoffset )
Argument | Description
al_unixtime | Longlong. The Unix time to convert (a number equal to the number of seconds past midnight Jan 1, 1970)
ai_utcoffset | Integer. The offset from UTC (Coordinated Universal Time) in minutes to be applied to the calculation (Unix time is stored as UTC)
Return value
Datetime. Converts the Unix time value in al_unixtime (applying the current timezone offset in ai_utcoffset) to a PowerHome DateTime value.
Usage
Use this function to convert Unix time values into DateTime values for use in other PowerHome functions
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_fromunixtime(1588887692, -300) - Returns a DateTime value equivalent to 05/07/2020 16:41:32. The actual UTC Unix time value is 05/07/2020 21:41:32 and the offset of -300 assumes being in the Eastern US timezone


ph_ftoc

ph_ftoc PowerHome formula function
Description
Converts a temperature value in Farenheight to Celcius
Syntax
ph_ftoc ( temp, round )
Argument | Description
temp | Double. The temperature value in Farenheight
round | Integer. The number of decimal places for the result to be rounded.
Return value
Double. Returns the converted temperature in degrees Celcius.


ph_hextonum

ph_hextonum PowerHome formula function
Description
Converts a hexadecimal number contained within a string to its decimal representation.
Syntax
ph_hextonum ( hexnum )
Argument | Description
hexnum | A string containing a hexadecimal number
Return value
Long. Returns the decimal representation of the hexadecimal number.


ph_htmlcolor

ph_htmlcolor PowerHome formula function
Description
Returns the HTML hexadecimal equivalent of a combined RGB color.
Syntax
ph_htmlcolor ( n )
Argument | Description
n | A long value representing a color. This color value is determined by combining Red, Green, and Blue values ranging from 0 to 255 using the following formula: Red + (Green * 256) + (Blue * 65536).
Return value
String. Returns the HTML hexadecimal equivalent of the combined RGB color in the form of #RRGGBB
Usage
Use this function to quickly convert RGB color values into their HTML equivalent.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_htmlcolor(255) - Returns a value of "#FF0000" which is the HTML color value for red


ph_htmlescape

ph_htmlescape PowerHome formula function
Description
Returns the passed string with appropriate HTML escape characters.
Syntax
ph_htmlescape ( s )
Argument | Description
s | String. A string which you want any non-safe characters properly escaped for HTML purposes.
Return value
String. Returns the passed string properly escaped for HTML.


ph_htmlunescape

ph_htmlunescape PowerHome formula function
Description
Returns the passed string with HTML escape characters removed.
Syntax
ph_htmlunescape ( s )
Argument | Description
s | String. A string containing HTML escape characters.
Return value
String. Returns the passed string with HTML escape characters converted and removed.


ph_huergbtoxy

ph_huergbtoxy PowerHome formula function
Description
Converts an RGB color value into Philips Hue XY values
Syntax
ph_huergbtoxy ( al_rgb, as_xy, as_gamut, ad_rx, ad_ry, ad_gx, ad_gy, ad_bx, ad_by )
Argument | Description
al_rgb | Long. The RGB color value you wish to convert. Ex: rgb(255,120,170)
as_xy | String. Specifies whether to return the X or the Y value. Valid values are "X" or "Y"
as_gamut | String. Specifies the gamut to be used for the conversion. See Usage below
ad_rx | Double. The gamut X value to use for Red
ad_ry | Double. The gamut Y value to use for Red
ad_gx | Double. The gamut X value to use for Green
ad_gy | Double. The gamut Y value to use for Green
ad_bx | Double. The gamut X value to use for Blue
ad_by | Double. The gamut Y value to use for Blue
Return value
Double. Returns either the X or Y value for the specified RGB color in al_rgb
Usage
Use this function calculate Philips Hue X and Y color values from a standard RGB color value.

Valid values for as_gamut are:

  • "a" - Use the Philips Hue A gamut values
  • "b" - Use the Philips Hue B gamut values
  • "c" - Use the Philips Hue C gamut values
  • "full" - Use full range gamut values

    If you specify one of the gamut values above (a, b, c, or full), you do NOT need to specify ANY of the ad_rx, ad_ry, ad_gx, ad_gy, ad_bx, or ad_by values (set all of these values to 0). If you wish to specify your own gamut ranges, set the as_gamut parameter to blank ("") and then specify the six gamut values in ad_rx thru ad_by. Gamut values should be a positive number between 0 and 1 inclusive.

    See the Philips Hue API for more details on color conversions and the actual gamut values that are used

    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_huergbtoxy(rgb(255,120,170),"x","a",0,0,0,0,0,0) - Returns 0.474956426332266 which is the X value using gamut A
    . ph_huergbtoxy(rgb(255,120,170),"y","",0.704,0.296,0.2151,0.7106,0.138,0.08) - Returns 0.26833168907959 which is the Y value using the manually specified gamut values (which in this example are the same values as the Philips Hue gamut A)


ph_huexytorgb

ph_huexytorgb PowerHome formula function
Description
Takes Philips Hue XY color values and converts them to an RGB color value
Syntax
ph_huexytorgb ( ad_x, ad_y )
Argument | Description
ad_x | Double. A Philips Hue X color value (should be a value between 0 and 1 inclusive)
ad_y | Double. A Philips Hue Y color value (should be a value between 0 and 1 inclusive)
Return value
Long. Returns a standard RGB color value
Usage
Use this function to convert Philips Hue XY color values to standard RGB color values
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_huexytorgb(0.4750,0.2683) - Returns 11106302 which is the equivalent to rgb(254,119,169)


ph_jsontoxml

ph_jsontoxml PowerHome formula function
Description
Converts JSON data to equivalent XML data
Syntax
ph_jsontoxml ( as_json )
Argument | Description
as_json | String. A string containing properly formatted JSON data
Return value
String. Returns the supplied JSON converted into XML data
Usage
Use this function to convert JSON data to XML data. The conversion is done using a C# JsonConvert object
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_jsontoxml('{"people":[{"name":"John","age":31,"city":"New York","phones":["4075551212","3215551212","8885551212"]}]}') - Returns "<XMLROOT><people><name>John</name><age>31</age><city>New York</city><phones>4075551212</phones><phones>3215551212</phones><phones>8885551212</phones></people></XMLROOT>"


ph_jsontoyaml

ph_jsontoyaml PowerHome formula function
Description
Converts JSON data to YAML
Syntax
ph_jsontoyaml ( as_json )
Argument | Description
as_json | String. A string containing properly formatted JSON data
Return value
String. Returns the supplied JSON data converted to YAML data
Usage
Use this function to convert JSON data to YAML (YAML Ain't Markup Language)...a text based markup language with heirarchy represented by indentation (see http://yaml.org). The conversion is done using a C# YamlDotNet object
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_jsontoyaml('{"people":[{"name":"John","age":31,"city":"New York","phones":["4075551212","3215551212","8885551212"]}]}')') - Returns the following YAML string: "people:~r~n- name: John~r~n age: 31~r~n city: New York~r~n phones:~r~n - 4075551212~r~n - 3215551212~r~n - 8885551212~r~n"


ph_n2b

ph_n2b PowerHome formula function
Description
Converts a numeric value to a logical true or logical false
Syntax
ph_n2b ( al_num )
Argument | Description
al_num | Long. The number to interpret as either true or false
Return value
Boolean. Returns FALSE if al_num = 0. Any other value for al_num will return TRUE
Usage
Use this function convert numeric values into logical true/false for use in if( ) and case( ) functions (or anywhere else a boolean value is allowed)
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_n2b(ph_and(3248,32)) - Returns TRUE. This example tests whether the 6th bit from the lefmost least significant bit is set in the number 3248. The binary representation for 3248 is 110010110000


ph_numtohex

ph_numtohex PowerHome formula function
Description
Returns the hexadecimal representation of an unsigned integer as a string.
Syntax
ph_numtohex ( value )
Argument | Description
value | The decimal value you wish converted to hexadecimal. Valid values are 0 thru 65535.
Return value
String. The hexadecimal representation of value.


ph_numtohex1

ph_numtohex1 PowerHome formula function
Description
Converts an unsigned integer to a hexadecimal string and specify the returned length.
Syntax
ph_numtohex1 ( value, len )
Argument | Description
value | Unsigned Integer. The integer whose value you wish returned in hex. Valid values are from 0 to 65535.
len | Integer. The number of hex digits that should be returned. Valid values are 1 thru 4.
Return value
String. Returns the number as a hexadecimal string of the specified length.
Usage
This function is essentially the same as the ph_numtohex() function coupled with the right() function.


ph_rgb2milight

ph_rgb2milight PowerHome formula function
Description
Converts an RGB color value to an appropriate color value suitable for sending to a MiLight controller
Syntax
ph_rgb2milight ( ai_r, ai_g, ai_b )
Argument | Description
ai_r | Integer. The Red component. Valid values are 0 to 255
ai_g | Integer. The Green component. Valid values are 0 to 255
ai_b | Integer. The Blue component. Valid values are 0 to 255
Return value
Integer. Returns a MiLight color value in the range of 0 to 255
Usage
Unlike Philips Hue bulbs, MiLight bulbs have a rather limited color range supporting a total of only 255 color values (a limited version of Hue and Saturation color values combined). Use this function to convert RGB color values into a value representing the closest MiLight approximation
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_rgb2milight(255,0,255) - Returns 220 which when sent to a MiLight controller will result in a violet color for the bulb


ph_rtne

ph_rtne PowerHome formula function
Description
Takes any value and returns an empty string.
Syntax
ph_rtne ( any )
Argument | Description
any | Any value (numeric, string, datetime, date, time, etc).
Return value
String. This function will always return an empty string. It is very handy within formulas within Send Keys commands and PSP pages when you are running a sequence of functions that return a value. You can place all the functions added together within a ph_rtne function so that no extra keys or HTML is generated in the output.


ph_rtnes

ph_rtnes PowerHome formula function
Description
Takes any string value and returns an empty string.
Syntax
ph_rtnes ( s )
Argument | Description
s | Any string value
Return value
String. This function will always return an empty string.


ph_texttojson

ph_texttojson PowerHome formula function
Description
Converts a flattened JSON string back into JSON
Syntax
ph_texttojson ( as_text, as_segsep, as_valsep, ai_flags )
Argument | Description
as_text | String. The flattened JSON string or other properly formatted text data
as_segsep | String. The character that is used to separate the JSON segments in the formatted text
as_valsep | String. The character that is used to separate segments from the value in the formatted text
ai_flags | Integer. A flags parameter controlling how the conversion is to be performed. See Usage below
Return value
String. Returns the previously flattened JSON or properly formatted text as a JSON string
Usage
Use this function to create JSON data from previously flattened JSON such as the output from the ph_flattenjson( ) function or to create JSON from properly formatted text. A sample of properly formatted text appears below:

Lights.FamilyRoom.status=On
Lights.Kitchen.status=Off
Temperature.FamilyRoom=76.6
Doors.value[0]=5
Doors.value[1]=6
Doors.value[2]=8

The ai_flags parameter currently only supports values of 0 or 1. A value of 0 will NOT try to interpret JSON arrays in the formatted data. A value of 1 will look for JSON arrays in the format of "[indice]" appearing at the end of a JSON segment. In the example formatted text above, you can see a properly formatted JSON array in the "Doors.value" segments.

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_texttojson("Lights.FamilyRoom.status=On~r~nLights.Kitchen.status=Off~r~nTemperature.FamilyRoom=76.6~r~nDoors.value[0]=5~r~nDoors.value[1]=6~r~nDoors.value[2]=8~r~n",".","=",1) - Returns the following JSON data: {"Lights": {"FamilyRoom": {"status": "On"}, "Kitchen": {"status": "Off"}}, "Temperature": {"FamilyRoom": "76.6"}, "Doors": {"value": [ "5", "6", "8"]}} This example has the ai_flags parameter set to 1 so the Doors.value segment is converted to a JSON array. The next example is the same data with the ai_flags parameter = 0

. ph_texttojson("Lights.FamilyRoom.status=On~r~nLights.Kitchen.status=Off~r~nTemperature.FamilyRoom=76.6~r~nDoors.value[0]=5~r~nDoors.value[1]=6~r~nDoors.value[2]=8~r~n",".","=",0) - Returns the following JSON data: {"Lights": {"FamilyRoom": {"status": "On"}, "Kitchen": {"status": "Off"}}, "Temperature": {"FamilyRoom": "76.6"}, "Doors": {"value[0]": "5", "value[1]": "6", "value[2]": "8"}}


ph_tounixtime

ph_tounixtime PowerHome formula function
Description
Converts a PowerHome datetime value to a standard Unix time value (number of seconds past midnight, Jan 1, 1970)
Syntax
ph_tounixtime ( adt_datetime, ai_utcoffset )
Argument | Description
adt_datetime | Datetime. The PowerHome DateTime value you wish to convert to Unix time
ai_utcoffset | Integer. The offset from UTC (Coordinated Universal Time) in minutes to be applied to the calculation (Unix time is stored as UTC)
Return value
Double. Converts the PowerHome DateTime value in adt_datetime to a standard Unix time value and applying the current timezone offset in ai_utcoffset so that the resulting value is the number of seconds past midnight, Jan 1, 1970 UTC
Usage
Use this function to convert a PowerHome DateTime value to a standard Unix time value
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_tounixtime(datetime(date("05/07/2020"),time("16:41:32")), -300) - Returns a standard Unix time value of 1588887692. The ai_utcoffset value of -300 assumes being in the Eastern US timezone


ph_xmltojson

ph_xmltojson PowerHome formula function
Description
Converts an XML string to equivalent JSON using a C# JsonConvert object
Syntax
ph_xmltojson ( as_xml )
Argument | Description
as_xml | String. A string containing the XML data you wish to convert to JSON
Return value
String. Returns the XML data converted to a JSON string. Returns "*ERROR* - " followed by details of the error if an exception occurs
Usage
Use this function to convert XML data to equivalent JSON data
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_xmltojson(ph_readfile("c:\powerhome\phdata.xml")) - Returns the XML data contained in the c:\powerhome\phdata.xml file as an equivalent JSON string. If the XML is not properly formatted and valid XML, then a string starting with "*ERROR* - " will be returned followed by the error details


ph_yamltojson

ph_yamltojson PowerHome formula function
Description
Converts YAML data into an equivalent JSON string
Syntax
ph_yamltojson ( as_yaml )
Argument | Description
as_yaml | String. A string containing the YAML data you wish to convert to JSON
Return value
String. Returns a JSON string after conversion from YAML. Returns "*ERROR* - " followed a description of the error if an exception occurs
Usage
Use this function to convert YAML data to equivalent JSON data. This functions uses YamlDotNet and Newtonsoft.Json to perform the conversion
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_yamltojson(ph_readfile("c:\powerhome\phdata.yml")) - Returns the YAML data in c:\powerhome\phdata.yml converted into an equivalent JSON string. Returns "*ERROR* - " followed by an error description if the data in the file is not properly formatted YAML


ph_zero

ph_zero PowerHome formula function
Description
Accepts a parameter of ANY datatype and returns a 0.
Syntax
ph_zero ( any )
Argument | Description
any | Any. Any valid PowerHome datatype including numeric, date, time, or string
Return value
Integer. Returns a 0.
Usage
Use this function within numeric formulas to quickly convert strings and/or any other values to a numeric 0.


real

real PowerHome formula function
Description
Converts a string value to a real data type.
Syntax
real ( string )
Argument | Description
string | The string whose value you want to convert to a real
Return value
Real. Returns the contents of a string as a real. If string is not a valid number, Real returns 0.


rgb

rgb PowerHome formula function
Description
Calculates the long value that represents the color specified by numeric values for the red, green, and blue components of the color.
Syntax
rgb ( red, green, blue )
Argument | Description
red | The integer value of the red component of the color
green | The integer value of the green component of the color
blue | The integer value of the blue component of the color
Return value
Long. Returns the long that represents the color created by combining the values specified in red, green, and blue. If an error occurs, RGB returns NULL.

Usage

The formula for combining the colors is:?

Red + (256 * Green) + (65536 * Blue)

The value of a component color is an integer between 0 and 255 that represents the amount of the component that is required to create the color you want. The lower the value, the darker the color; the higher the value, the lighter the color.


string

string PowerHome formula function
Description
Formats data as a string according to a specified display format mask. You can convert and format date, DateTime, numeric, and time data. You can also apply a display format to a string.
Syntax
string ( data {, format } )
Argument | Description
data | The data you want returned as a string with the specified formatting. Data can have a date, DateTime, numeric, time, or string data type
format (optional) | A string of the display masks you want to use to format the data. The masks consist of formatting information specific to the data type of data. If data is type string, format is requiredThe format string can consist of more than one mask, depending on the data type of data. Each mask is separated by a semicolon. See Usage for details on each data type
Return value
String. Returns data in the specified format if it succeeds and the empty string ("") if the data type of data does not match the type of display mask specified or format is not a valid mask.
Usage
For date, DateTime, numeric, and time data, the system's default format is used for the returned string if you don't specify a format. For numeric data, the default format is the [General] format.

For string data, a display format mask is required. (Otherwise, the function would have nothing to do.)

The format can consist of one or more masks:?

Formats for date, DateTime, string, and time data can include one or two masks. The first mask is the format for the data; the second mask is the format for a null value.

Formats for numeric data can have up to four masks. A format with a single mask handles both positive and negative data. If there are additional masks, the first mask is for positive values, and the additional masks are for negative, zero, and NULL values.

Unpredictable results will occur if the mask does not match the data type.


time

time PowerHome formula function
Description
Converts a string to a time data type.
Syntax
time ( string )
Argument | Description
string | A string containing a valid time (such as 8 am or 10:25) that you want returned as a time data type. Only the hour is required; you do not have to include the minutes, seconds, or microseconds of the time or am or pm. The default value for minutes and seconds is 00 and for microseconds is 000000. am or pm is determined automatically
Return value
Time. Returns the time in string as a time data type. If string does not contain a valid time, Time returns 00:00:00.


upper

upper PowerHome formula function
Description
Converts all characters in a string to uppercase letters.
Syntax
upper ( string )
Argument | Description
string | The string you want to convert to uppercase letters
Return value
String. Returns string with lowercase letters changed to uppercase if it succeeds and the empty string ("") if an error occurs.


wordcap

wordcap PowerHome formula function
Description
Sets the first letter of each word in a string to a capital letter and all other letters to lowercase (for example, ROBERT E. LEE would be Robert E. Lee).
Syntax
wordcap ( string )
Argument | Description
string | A string or expression that evaluates to a string that you want to display with initial capital letters (for example, Monday Morning)
Return value
String. Returns string with the first letter of each word set to uppercase and the remaining letters lowercase if it succeeds and NULL if an error occurs.


s2h

s2h PowerHome formula function
Description
Encodes either a string or file into a hex encoded string
Syntax
s2h ( as_input, ai_type )
Argument | Description
as_input | String. The string or a full path and filename containing the data you would like to encode
ai_type | Integer. A flag that determines how the as_input parameter is to be interpreted. A value of 1 indicates to interpret the data in as_input as a string using the default (UTF8) encoding. A value of 2 indicates to interpret as_input as a path and filename to read. A value of 0 (or any other value different from 1 or 2) will result in as_input being interpreted as a string using ANSI encoding
Return value
String. Returns the data as a hex encode string
Usage
Use this function convert string data or string/binary data contained within a file into a hex encoded string
Examples
The following examples demonstrate typical syntax/usage for this function.
. s2h("This is a test",0) - Returns "5468697320697320612074657374"


ph_backupdb

ph_backupdb PowerHome formula function
Description
Makes a copy of the PowerHome database.
Syntax
ph_backupdb ( target, replace )
Argument | Description
target | String representing the full path and filename to copy the database file to. This value must be a fully qualified path and file name and cannot be a relative path.
replace | Integer representing whether to overwrite the file if it already exists. Use 0 to keep an existing file, any other value to overwrite.
Return value
Integer. Returns a 0 if the datbase file copy was successful. Returns 1 if the target is not a fully qualified path and filename. Returns 2 if the DBF path in the pwrhome.ini file is not a fully qualified path and filename. Returns 3 if the target already exists and the replace parameter is 0. Returns 4 if the SQL backup command fails. Returns 5 if the backup file rename operation fails.
Notes
In order for this function to execute, the SALOGDIR environment variable must be defined on the machine that PowerHome is running on. This environment variable should be set to a directory where the BACKUP.SYB temporary file that this function creates can reside.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_backupdb("C:\phdbabckup.db", 1)
Writes a backup file at the same location, overwriting the prior file

. ph_backupdb("C:\powerhome\Database\dbAutoBaks\ph-"+string(today(),"yymmdd")+".db",0)
Creates a file named "PH-" plus a date string, thus >> "ph-130611.db".
This results in unique individual files that must be trimmed occasionally to prevent runaway file clutter!


ph_createglobal

ph_createglobal PowerHome formula function
Description
Creates and initializes a PowerHome global variable on the fly.
Syntax
ph_createglobal ( id, value )
Argument | Description
id | String. The ID of the global variable to create.
value | String representing the initial value to assign to the global variable
Return value
Integer. Returns 0 if successful. Returns a 1 if an error occurred such as the ID already existing.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_createglobal("MOTIONCOUNT","0")
• ph_createglobal("MOTIONCOUNT", "[LOCAL1]")
• ph_createglobal("CAMERA_NAME","DrvCam")


ph_dbwhereused

ph_dbwhereused PowerHome formula function
Description
Dynamically creates a SQL string that will search for the specified search string with the option to execute the SQL and return all instances where the search string is found
Syntax
ph_dbwhereused ( as_search, ai_flags )
Argument | Description
as_search | String. The search parameter to looked for within the PowerHome database. Use the "%" character as a wildcard.
ai_flags | Integer. Flags controlling how the data is to be returned.
Return value
String. Returns either a string containing the dynamically generated SQL statements to search the database or the actual results of executing the SQL statements against the PowerHome database
Usage
Use this function to build SQL statements that allow you to search the PowerHome database for a specific search term and optionally perform the search and return the results. This function will use the PowerHome database dictionary to build appropriate SQL statements to search tables and character based columns for the search term. This function will not search numeric column datatypes or date datatypes and will only include character based columns in the generated SQL. This function is used by the menu item "Database Where Used" option under the "Reports" menu.

Note: Most of the time your search term will be surrounded by the "%" wildcard character to make partial matches. Without wildcards, the search string must EXACTLY match the entire contents of the searched column

Valid values for the ai_flags parameter (multiple desired values are added together to get a final value) are:

  • 1 - SQL will include text descriptions of returned values
  • 2 - Exclude generating SQL for tables in the DBWUEXCLUDE table
  • 4 - Include searching tables that don't have a primary key
  • 8 - Return the result of actually executing the search SQL rather than the SQL itself
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
  • ph_dbwhereused("%email%",15) - Generates SQL searching for the word "email" within PowerHome tables that have a primary key and are not excluded in the DBWUEXCLUDE table. The data returned will be the results of actually running the generated SQL and will include text identifiers for the returned column values


ph_deletedata

ph_deletedata PowerHome formula function
Description
Allows you to delete retrieved data in the specified Data Retrieval Area
Syntax
ph_deletedata ( ai_dsvar, al_row )
Argument | Description
ai_dsvar | Integer. The Data Retrieval Area number you wish to delete data from. Valid values are 1 thru 20
al_row | Long. The row number in the specified data retrieval area that you wish to delete
Return value
Integer. Returns 0 if successful. Returns -1 if ai_dsvar is < 1 or > 20. Returns -2 if ai_dsvar is not valid (contains previously retrieved data). Returns -3 if al_row < 1 or > the number of rows in the data retrieval area. Returns -4 if the deletion fails.
Usage
Use this function to delete data has been previously retrieved in one of the 20 data retrieval areas
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_deletedata(1,5) - Deletes row number 5 from Data Retrieval Area number 1


ph_deleteglobal

ph_deleteglobal PowerHome formula function
Description
Deletes a PowerHome global variable on the fly.
Syntax
ph_deleteglobal ( id )
Argument | Description
id | String. The ID of the global variable to delete.
Return value
Integer. Returns 0 if successful. Returns a 1 if an error occurred such as the ID not existing.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_deleteglobal("MOTIONCOUNT")


ph_directsql

ph_directsql PowerHome formula function
Description
Execute SQL directly against the PowerHome database.
Syntax
ph_directsql ( sql )
Argument | Description
sql | String containing a valid SQL statement. Inserts, Updates, and Deletes are all valid. See ph_sqlselect to perform Selects against the database.
Return value
Integer. Returns a 0 if the SQL was successfully executed. Otherwise a value equivalent to the SQL error when attempting to execute the SQL is returned.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_directsql("delete from timedevents where id = 'SHOPDOOR ALERT'")


ph_disabletrigger

ph_disabletrigger PowerHome formula function
Description
Disables an enabled PowerHome trigger.
Syntax
ph_disabletrigger ( )
ph_disabletrigger ( as_id )
Argument | Description
as_id | String (Optional). The ID of the trigger you wish to disable. If this parameter is omitted, the system variable TRIGGER will be used for ID
Return value
Integer. Returns a 0
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_disabletrigger("LIVROOM_OFF")


ph_enabletrigger

ph_enabletrigger PowerHome formula function
Description
Enables a disabled PowerHome trigger.
Syntax
ph_enabletrigger ( )
ph_enabletrigger ( as_id )
Argument | Description
as_id | String (Optional). The ID of the trigger you wish to enable. If this parameter is omitted, the system variable TRIGGER will be used for ID
Return value
Integer. Returns a 0
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_enabletrigger("LIVROOM_OFF")
. ph_enabletrigger("[TEMP2]") --> where TEMP2 contains a valid trigger ID


ph_exportdata

ph_exportdata PowerHome formula function
Description
Exports data from a specified Data Retrieval Area
Syntax
ph_exportdata ( i_dsvar, ai_exporttype, ai_colheading, as_filename )
Argument | Description
i_dsvar | Integer. The number of the data retrieval area to export. Valid values are 1 thru 20.
ai_exporttype | Integer. The type of export to be performed. See Usage below for valid values.
ai_colheading | Integer. Specifies whether to include column headings in the export or not. Use 0 to not include headings. Any other value to include headings.
as_filename | String. The full path and filename to save the exported data to.
Return value
Integer. Returns 0 if successful. Returns -1 if the specified data retrieval area in i_dsvar is out range (less than 1 or greater than 20). Returns -2 if data retrieval area is not valid (has not been declared). Returns -3 if the export operation fails.
Usage
Use this function to export retrieved data in the specified data retrieval area to a file.

Valid values for ai_exporttype are:

  • 0 - Microsoft Excel format
  • 1 - Tab separated text
  • 2 - Comma separated text
  • 3 - Microsoft Multiplan format
  • 4 - Lotus 1 2 3
  • 5 - Lotus 1 2 3
  • 6 - Data Interchange format
  • 7 - dBASE-II
  • 8 - dBASE-III
  • 9 - SQL Insert statements
  • 10 - Tab separated text saved to clipboard instead of a file (as_filename can be empty string "")
  • 11 - Powersoft Report format
  • 12 - Windows Metafile format
  • 13 - HTML table
  • 14 - Excel 5
  • 15 - XML
  • 16 - XSL
  • 17 - PDF
  • 18 - Excel 8
  • 19 - Enhanced Metafile format
  • 24 - Excel XLSX format
  • 25 - Excel XLSB format
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_exportdata(1,13,1,"c:\powerhome\dra1.htm") - Exports the data in data retrieval area 1 as an HTML table and saves the data to file c:\powerhome\dra1.htm


ph_filterdata

ph_filterdata PowerHome formula function
Description
Filters retrieved data in the specified Data Retrieval Area
Syntax
ph_filterdata ( ai_dsvar, as_filter )
Argument | Description
ai_dsvar | Integer. The data retrieval area you wish to filter. Valid values are 1 thru 20.
as_filter | String. The string containing the filter critera. This string would be in the format that is typically used in a SQL "where" clause.
Return value
Long. Returns the number of rows that were "filtered" out of the data retrieval area if successful. Returns -1 if ai_dsvar is not in the range of 1 thru 20. Returns -2 if the data retrieval area is not valid. Returns -3 if the filter string (as_filter) is not valid. Returns -4 if the filter operation fails.
Usage
Use this function to filter data in a data retrieval area. This is similar to specifying filter critera within the where clause of the data retrieval areas SQL statement but allows you to apply filters after retrieval rather than during retrieval.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_filterdata(1,"ddtype=8") - Assuming data retrieval area 1 contains data from SQL "select * from dropdowns", filters ALL rows except those where the DDTYPE column contains the value 8
. ph_filterdata(1,"lower(#2) like '%email%'") - Filters ALL rows in data retrieval area 1 except those that contain the string "email" in the second column


ph_finddata

ph_finddata PowerHome formula function
Description
Finds data in a data retrieval area that was selected from an SQL Select.
Syntax
ph_finddata ( n, s, start, end )
Argument | Description
n | The number of the data retrieval area (1 - 5)
s | A string whose value is a boolean expression that you want to use as the search criterion. The expression includes column names
start | A long identifying the row location at which to begin the search.
end | A long identifying the row location at which to end the search. To search backward, make end less than start
Return value
Long. Returns the number of the first row that meets the search criteria within the search range. Returns 0 if no rows are found and a negative number if an error occurs. If any argument's value is NULL, Find returns NULL.


ph_getcolcount

ph_getcolcount PowerHome formula function
Description
Returns the number of columns in the specified data retrieval area.
Syntax
ph_getcolcount ( n )
Argument | Description
n | The number of the data retrieval area (1 - 10)
Return value
Long. Returns the number of columns the last SQL Select retrieved from the specified data retrieval area.


ph_getcolname

ph_getcolname PowerHome formula function
Description
Returns the name of the specified column number in the specified data retrieval area.
Syntax
ph_getcolname ( n, n )
Argument | Description
n | The number of the data retrieval area (1 - 10)
n | The number of the column you wish to get the name of.
Return value
String. Returns the name of the specified column the last SQL Select retrieved from the specified data retrieval area.


ph_getcoltype

ph_getcoltype PowerHome formula function
Description
Returns the data type of the specified column number in the specified data retrieval area.
Syntax
ph_getcoltype ( n, n )
Argument | Description
n | The number of the data retrieval area (1 - 10)
n | The number of the column you wish to get the data type of.
Return value
String. Returns the data type of the specified column the last SQL Select retrieved from the specified data retrieval area as a string.


ph_getdata

ph_getdata PowerHome formula function
Description
Gets data from a data retrieval area that was selected from an SQL Select.
Syntax
ph_getdata ( n, row, col )
Argument | Description
n | The number of the data retrieval area (1 - 20)
row | A long identifying the row you wish to retrieve from.
col | A long identifying the column number you wish to retrieve from.
Return value
String. The data stored within data retrieval area n at row, col.


ph_getdata_cn

ph_getdata_cn PowerHome formula function
Description
Gets data from a data retrieval area that was selected from an SQL Select.
Syntax
ph_getdata_cn ( n, row, colname )
Argument | Description
n | The number of the data retrieval area (1 - 10)
row | A long identifying the row you wish to retrieve from.
colname | A string identifying the column name you wish to retrieve from.
Return value
String. The data stored within data retrieval area n at row, colname.


ph_getdatawithmask

ph_getdatawithmask PowerHome formula function
Description
Gets data from a data retrieval area that was selected from an SQL Select and applies a mask.
Syntax
ph_getdatawithmask ( n, row, col, mask )
Argument | Description
n | The number of the data retrieval area (1 - 10)
row | A long identifying the row you wish to retrieve from.
col | A long identifying the column number you wish to retrieve from.
Mask | A string representing the mask to apply.
Return value
String. The data stored within data retrieval area n at row, col with mask applied. If data is of a date type, you could use a mask of "yyyy-mm-dd" to have the date returned in that format. You can also format numeric and time data types.


ph_gethtmldata

ph_gethtmldata PowerHome formula function
Description
Retrieves the rows from a data retrieval area and formats it into an HTML table.
Syntax
ph_gethtmldata ( n )
Argument | Description
n | An integer identifying the data retrieval area you wish to have converted into an HTML table (1 - 10).
Return value
String. The rows and columns in the specified data retrieval converted into an HTML table.


ph_getsqlrows

ph_getsqlrows PowerHome formula function
Description
Returns the current number of rows in the specified data retrieval area.
Syntax
ph_getsqlrows ( ai_id )
ph_getsqlrows ( ai_id, ai_type )
Argument | Description
ai_id | Integer. The data retrieval area you wish to get the number of rows (1 - 20).
ai_type | Integer (Optional). The type of row counts you would like returned for the Data Retrieval area. If this parameter is omitted, 0 will be used. See Usage below for details
Return value
Long. Returns the number of rows currently within the data retrieval area for the specified ai_type value. Returns -1 if parameter ai_id is out of range. Returns -2 if the specified Data Retrieval area is not valid. Returns -3 if parameter ai_type is out of range
Usage
Use this function to retrieve the number of rows associated with a specific area within a Data Retrieval Area.

The valid values for the ai_type parameter are:

  • 0 - Return the count of rows in the primary section of the Data Retrieval area. This is equivalent to the system variables SQLROWS1 thru SQLROWS20
  • 1 - Return the count of rows that have been filtered in the Data Retrieval area
  • 2 - Return the count of rows that have been modified in the Data Retrieval area
  • 3 - Return the count of rows that have been deleted in the Data Retrieval area
  • Any other value will return -3
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_getsqlrows(5) - Returns the number of rows in the primary data section of Data Retrieval area 5. This is the same value as system var SQLROWS5


ph_importdata

ph_importdata PowerHome formula function
Description
Imports data into a Data Retrieval area
Syntax
ph_importdata ( i_dsvar, as_data, ai_datatype, ai_importtype )
Argument | Description
i_dsvar | Integer. The Data Retrieval area number. Valid values are 1 thru 20
as_data | String. The raw data to be imported or a full path and filename of a file to be imported
ai_datatype | Integer. The type of data to import. 0 is for tab separated text. 1 is for CSV (comma separated values). 2 is for XML formatted data. Any other value will return an error
ai_importtype | Integer. The type of data in the as_data parameter. A value of 0 indicates raw data. Any other value indicates a filename
Return value
Long. Returns the number of rows imported if the function is successful.

Returns one of the negative numbers below if an error occurs:

  • -1 No rows to import
  • -2 Empty file
  • -3 Invalid argument
  • -4 Invalid input. This is the most common error and can result from the import data not matching the columns or the import data exceeds the internal column length
  • -5 Could not open file
  • -6 Could not close file
  • -7 Error reading file text
  • -8 Unsupported file name suffix (must be *.txt, *.csv, *.dbf or *.xml)
  • -11 XML parsing error
  • -12 XML template does not exist or does not match
  • -13 Unsupported style for import
  • -14 Error resolving nesting
  • -15 File size exceeds limit
  • -100 The i_dsvar parameter is out of range
  • -101 The Data Retrieval area is undefined
  • -102 An invalid ai_datatype value was specified
    • Usage
    Use this function to import formatted data into a Data Retrieval area for further processing
    Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_importdata(1,"Test Data 1~tSecond column~t14~r~nTest Data 2~tSecond column 2~t15~r~n",0,0) - Returns 2 for the two rows of three columns of tab separated data in the as_data parameter. The example assumes that Data Retrieval area 1 has already been defined with a ph_sqlselect( ) function such as: ph_sqlselect(1,"select space(255),space(255),0 from dummy where 1 = 0")


ph_insertdata

ph_insertdata PowerHome formula function
Description
Inserts a blank row into a Data Retrieval area
Syntax
ph_insertdata ( ai_dsvar, al_row )
Argument | Description
ai_dsvar | Integer. The number of the previously defined Data Retrieval you wish to insert a row. Valid values are 1 thru 20
al_row | Long. The number of an existing row that you want to insert the new row before. Use 0 to add a row to the end
Return value
Long. Returns the row number of the new row.

Returns one of the negative numbers below if an error occurs

  • -1 The ai_dsvar value is out of range (must be 1 thru 20)
  • -2 The specified ai_dsvar number is not initialized
  • -3 the specified row is not valid. The row must be 1 thru the current number of rows in the Data Retrieval area or 0 to insert at the end
    • Usage
    Use this function to insert blank rows into an existing Data Retrieval area. If the Data Retrieval area currently contains 5 rows and you insert a new row 3, the current row 3 will become row 4 and the Data Retrieval area will now contain 6 rows. In this case, the function will return the number 3. If you insert at row 0 into the same Data Retrieval area that currently contains 6 rows, the new row will become row 7 and the number 7 will be returned
    Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_insertdata(1,5) - Returns the number 5 if Data Retrieval area 1 is initialized and has at least 5 existing rows


ph_setdata

ph_setdata PowerHome formula function
Description
Sets the data value for a specified row and column in a Data Retrieval area
Syntax
ph_setdata ( i_dsvar, l_row, l_col, aa_data )
Argument | Description
i_dsvar | Integer. The Data Retrieval area that holds the data you want to set. Valid values are 1 thru 20
l_row | Long. The row number for the data you want to set
l_col | Long. The column number for the data you want to set
aa_data | Any. The data value that you would like to set to the specified row/column. The datatype supplied must match the column datatype
Return value
Long. Returns 0 if successful. Returns -1 if the i_dsvar parameter is out of range (1 - 20). Returns -2 if the specified Data Retrieval area is not initialized. Returns -3 if the specified row does not exist in the Data Retrieval area. Returns -4 if the specified column does not exist in the Data Retrieval area. Returns -5 if function fails
Usage
Use this function to update and set data in a Data Retrieval area
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setdata(1,5,2,"FAMILYRM") - Returns 0 if successful. Sets row 5, column 2 in Data Retrieval area 1 to the string value "FAMILYRM". The datatype for column 2 in Data Retrieval 1 must also be a string or character datatype


ph_sortdata

ph_sortdata PowerHome formula function
Description
Sorts the data in a Data Retrieval area
Syntax
ph_sortdata ( ai_dsvar, as_sort )
Argument | Description
ai_dsvar | Integer. The Data Retrieval area number you wish to sort. Valid values are 1 thru 20
as_sort | String. The sort description to be performed. See Usage below
Return value
Long. Returns 0 if successful. Returns -1 if the ai_dsvar parameter is out of range (1 - 20). Returns -2 if the Data Retrieval area is not initialized. Returns -3 if the specified sort is not valid. Returns -4 if the sort fails.
Usage
Use this function sort previously retrieved data in a Data Retrieval area

The as_sort parameter is a string containing 1 or more columns that you would like to sort by with the option of specifying either an ascending or descending sort. You can use either the column name or a column number. If you use a column number, prefix the number with the pound "#" sign. If you don't specify "a" (ascending) or "d" (descending) the default will be ascending. Sample sort strings are below:

  • "#1 a, #2 d"
  • "ddtype, dddisplay"
  • "address d"
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_sortdata(1,"#1 a, dddisplay d") - Returns 0 if successful. Sorts Data Retrieval area 1 first by the 1st column ascending and then by the column named "dddisplay" descending


ph_sql

ph_sql PowerHome formula function
Description
Executes a SQL statement against the PowerHome database and return the resultset as a string.
Syntax
ph_sql ( type, sql )
Argument | Description
type | Integer. The format in which you want the data returned. 0 for tab separated columns with cr/lf separated lines, 1 for comma separated columns and rows, 2 for XML data, and 3 for HTML table.
sql | String. A string containing the SQL select statement to run.
Return value
String. Returns the data formatted based upon the type parameter.


ph_sql_d

ph_sql_d PowerHome formula function
Description
Executes a SQL statement against the PowerHome database and returns the result as a date.
Syntax
ph_sql_d ( sql )
Argument | Description
sql | String. A string containing the SQL select statement to run.
Return value
Date. Returns the result as a date value. The SQL may return multiple rows, but only data from the first row will be returned by the function. The SQL should only return a single column of data.


ph_sql_dt

ph_sql_dt PowerHome formula function
Description
Executes a SQL statement against the PowerHome database and returns the result as a datetime.
Syntax
ph_sql_dt ( sql )
Argument | Description
sql | String. A string containing the SQL select statement to run.
Return value
DateTime. Returns the result as a datetime value. The SQL may return multiple rows, but only data from the first row will be returned by the function. The SQL should only return a single column of data.


ph_sql_n

ph_sql_n PowerHome formula function
Description
Executes a SQL statement against the PowerHome database and returns the result as a numeric
Syntax
ph_sql_n ( sql )
Argument | Description
sql | String. A string containing the SQL select statement to run.
Return value
Double. Returns the result as a numeric value. The SQL may return multiple rows, but only data from the first row will be returned by the function. The SQL should only return a single column of data.


ph_sql_s

ph_sql_s PowerHome formula function
Description
Executes a SQL statement against the PowerHome database and returns the result as a string.
Syntax
ph_sql_s ( sql )
Argument | Description
sql | String. A string containing the SQL select statement to run.
Return value
String. Returns the result as a string value. The SQL may return multiple rows, but only data from the first row will be returned by the function. The SQL should only return a single column of data.


ph_sql_t

ph_sql_t PowerHome formula function
Description
Executes a SQL statement against the PowerHome database and returns the result as a time.
Syntax
ph_sql_t ( sql )
Argument | Description
sql | String. A string containing the SQL select statement to run.
Return value
Time. Returns the result as a time value. The SQL may return multiple rows, but only data from the first row will be returned by the function. The SQL should only return a single column of data.


ph_sqldestroy

ph_sqldestroy PowerHome formula function
Description
Destroys a data retrieval area that was previously defined.
Syntax
ph_sqldestroy ( n )
Argument | Description
n | The number of the data retrieval area you would like to destroy. Valid values are 1 thru 10.
Return value
Integer. Returns a 0.


ph_sqlselect

ph_sqlselect PowerHome formula function
Description
Selects data from the PowerHome database into a data retrieval area.
Syntax
ph_sqlselect ( n, s )
Argument | Description
n | The number of the data retrieval area you would like to create and select into. Valid values are 1 thru 20.
s | A string representing a valid SQL select statement.
Return value
Integer. Returns a 0 if successful. A 1 will be returned if an invalid data retrieval area is specified. A 2 will be returned if selects against the REGINFO table are performed. A 3 is returned if the SQL code is not valid. A 4 is returned if an error occurs while trying to create the query. If the function is successful, the system variable SQLROWS# will be updated with the number of rows the select returned. You can then use the other PowerHome functions such as ph_getdata to access the data in the data retrieval area. Be sure and destroy a data retrieval area when you are done using it so that the memory will be released.


ph_sqlselectinto

ph_sqlselectinto PowerHome formula function
Description
Executes a SQL query and returns the values of the first row into the appropriate LOCAL? system variables.
Syntax
ph_sqlselectinto ( n, s )
Argument | Description
n | The number of the starting LOCAL system variable to retrieve data into. This value must be between 1 and 10 inclusive. The first column of the SQL statement will be retrieved into the LOCAL system variable identified by n. Subsequent columns will be retrieved into subsequent LOCAL varaibles.
s | String representing a valid SQL statement. Multiple rows are allowed to be returned by the SQL select but only the first row as determined by the SQL order by will be returned.
Return value
Integer. Returns a 0 if successful. Returns 1 if n is outside of the range 1 to 10. Returns 2 if queries are against the REGINFO table. Returns 3 if the SQL is invalid. Returns 4 if an error occurs while creating the query.
Usage
Use this function to quickly retrieve data from the PowerHome database when you only need a single row of data. If you need to step thru multiple rows, use the ph_sqlselect function instead. If you declare a query that returns 3 columns and specify a value of 6 for n, then column 1 will go into LOCAL6, column 2 will go into LOCAL7, and column 3 will go into LOCAL8. If your query returns columns greater than what will fit into the LOCAL variables (LOCAL10 maximum), the extra columns will be discarded.


Date / Time

Date / Time Functions
PowerHome supports a number of functions that return date, time, or datetime datatypes as well as functions that accept these data types as parameters. This has sometimes been a source of confusion as to exactly what these datatypes are. Details concerning these unique types are below.
All 3 datatypes (date, time, datetime) support a "literal" representation. This is essentially a hard-coded representation of the value (similar to a string but without quotes). Its not often used as most of the time you'll pass date, time, and datetime parameters within a string to a conversion function before using as a parameter in a function that requires a date, time, or datetime value.

Functions that return these datatypes, if not used as an input to another function that requires these datatypes, will have the value converted to a string for storage within a global, local, or temp variable. PowerHome has no concept of date, time, or datetime variables and stores ALL values as a string datatype.

Literal values for these three datatypes must appear in the same format as specified in the Windows Region and Language Localization control panel. In the US, this is typically yyyy-mm-dd for date values and hh:mm:ss for time values. In a different country or region, its likely to be something different.

Date
The date datatype contains only date values. You can use a date literal such as 2015-01-15 (see literal format above) or a function that returns a date value such as date() or relativedate()

Time
The time datatype contains only time values. You can use a time literal such as 22:15:45 (see literal format above) or a function that returns a time value such as time() or relativetime()

Datetime
The datetime datatype contains both a date and a time value. A datetime literal is made by combining a date literal with a time literal and separating the two with a space (see literal formats above). A valid datetime literal would look like this:
2014-07-15 17:40:00
You can also get a datetime value by using a function that returns a datetime value such as datetime() or ph_relativedatetime()

Examples
Examples of valid date, time, and datetime functions can be seen below:

. date("1-23-15") --> evaluates to: 01/13/2015
. date("Jan 23 2015") --> evaluates to: 01/13/2015
. datetime(today(),08:15:00:0000) --> evaluates to: 01/11/2015 08:15:00
. datetime(2010-12-15, 10:49:00) --> evaluates to: 12/15/2010 10:49:00
. dayname(2010-12-15) --> evaluates to: Wednesday
. month(2014-12-15) --> evaluates to: 12
. month(date("02/14/2015")) --> evaluates to: 2
. ph_relativedatetime(today(), 10) --> evaluates to: 01/15/2015 14:37:08


day

day PowerHome formula function
Description
Obtains the day of the month from a date value (either the output of a function eg, today() or a date 'literal' value).

See the Date / Time Functions section for detailed information concerning date / time formats.

Syntax
day ( date )
Argument | Description
date | The date value (function output or literal) from which you want the day

Return value
Integer. Returns an integer (1-31) representing the day of the month in date.

Examples
The following examples demonstrate typical syntax/usage for this function.
. day(today()) --> evaluates to: 15
. day(2010-12-15) --> evaluates to: 15
. day(relativedate(date(year(today()),if(month(today())=12,1,month(today())+1),1), -1)) -->Finds the last day of the current month.
. day(12-15-2010) --> Fails (improper literal syntax)
. day("2010-12-15") -->Fails (String value instead of date value)


dayname

dayname PowerHome formula function
Description
Given a valid date value (either the output of a function eg, today() or a date 'literal' value such as 2010-12-15) this function returns the name of the weekday.

See the Date / Time Functions section for detailed information concerning date / time formats.

Syntax
dayname ( date )
Argument | Description
date | The date value for which you want the name of the day

Return value
String. Returns a string whose value is the name of the weekday (Sunday, Monday, and so on) for date.

Examples
The following examples demonstrate typical syntax/usage for this function.
• dayname(today()) --> evaluates to: Thursday
• dayname(2010-12-15) --> evaluates to: Wednesday
• dayname("2010-12-15") --> Fails (string value vs date value. Use dayname(date("2010-12-15")) for this format)


daynumber

daynumber PowerHome formula function
Description
Gets the week day number (Sun=1, Sat=7) of a valid date value (either the output of a function eg, today() or a date 'literal' value such as 2010-12-15) and returns the number of the weekday.

See the Date / Time Functions section for detailed information concerning date / time formats.

Syntax
daynumber ( date )
Argument | Description
date | The date value from which you want the number of the day of the week

Return value
Integer. Returns an integer (1-7) representing the day of the week of date. Sunday is day 1, Monday is day 2, and so on.

Examples
The following examples demonstrate typical syntax/usage for this function.
• daynumber(today()) --> evaluates to: 5
• daynumber(2010-12-15) --> evaluates to: 4
• daynumber("2010-12-15") --> Fails (string value vs date value. Use daynumber(date("2010-12-15")) for this format)


daysafter

daysafter PowerHome formula function
Description
Given a valid date value (either the output of a function eg, today() or a date 'literal' value such as 2010-12-15) this function determines the number of days one date occurs after another.

See the Date / Time Functions section for detailed information concerning date / time formats.

Syntax
daysafter ( date1, date2 )
Argument | Description
date1 | A date value that is the start date of the interval being measured
date2 | A date value that is the end date of the interval

Return value
Long. Returns a long containing the number of days date2 occurs after date1. If date2 occurs before date1, DaysAfter returns a negative number.

Examples
The following examples demonstrate typical syntax/usage for this function.
• daysafter(date(today()), date("2015-1-17")) --> evaluates to: 2
• daysafter(2015-01-15, date("2015-1-17")) --> evaluates to: 2
• dayafter(2015-01-15,2015-01-17) --> evaluates to: 2


hour

hour PowerHome formula function
Description
Obtains the hour in a time value. The hour is based on a 24-hour clock.
Syntax
hour ( time )
Argument | Description
time | The time value from which you want the hour
Return value
Integer. Returns an integer (00-23) containing the hour portion of time.


isdate

isdate PowerHome formula function
Description
Tests whether a string value is a valid date.
Syntax
isdate ( datevalue )
Argument | Description
datevalue | A string whose value you want to test to determine whether it is a valid date
Return value
Boolean. Returns TRUE if datevalue is a valid date and FALSE if it is not.


istime

istime PowerHome formula function
Description
Reports whether the value of a string is a valid time value.
Syntax
istime ( timevalue )
Argument | Description
timevalue | A string whose value you want to test to determine whether it is a valid time
Return value
Boolean. Returns TRUE if timevalue is a valid time and FALSE if it is not.


minute

minute PowerHome formula function
Description
Obtains the number of minutes in the minutes portion of a time value.
Syntax
minute ( time )
Argument | Description
time | The time value from which you want the minutes
Return value
Integer. Returns the minutes portion of time (00 to 59).


month

month PowerHome formula function
Description
Given a valid date value (either the output of a function eg, today() or a date 'literal' value such as 2010-12-15) this function extracts the month.

See the Date / Time Functions section for detailed information concerning date / time formats.

Syntax
month ( date )
Argument | Description
date | The date value from which you want the month

Return value
Integer. Returns an integer (1 to 12) whose value is the month portion of date.

Examples
The following examples demonstrate typical syntax/usage for this function.
• month(today()) --> evaluates to: 1
• month(2014-12-15) --> evaluates to: 12
• month(date("02/14/2015")) --> evaluates to: 2
• month("2014-12-15") --> Fails


now

now PowerHome formula function
Description
Obtains the current time as a time value, based on the system time of the client machine.

The time is expressed as hh:mm:ss:nnn (where 'nnn' are milliseconds)

See the Date / Time Functions section for detailed information concerning date / time formats.

Syntax
now ( )

Return value
Time. Returns the current time based on the system time of the client machine.

Examples
The following examples demonstrate typical syntax/usage for this function.
• now() --> evaluates to: 13:49:25:102
• string(now(),"hh:mm:ss") --> evaluates to: 13:49:25


ph_datetime

ph_datetime PowerHome formula function
Description
Takes date and time values stored within a string and returns it as a datetime variable.

Syntax
ph_datetime ( s )
Argument | Description
s | A string containing a date and/or time value.

Return value
Datetime. Returns the string parameter as a datetime value. This parameter should contain a date in the format of mm/dd/yyyy or mm-dd-yyyy or yyyy-mm-dd without spaces followed by a space and then the time value in hh:mm:ss format. If you pass only a time value, then the returned datetime will be Today's date plus the passed time. If the parameter only contains a date, you'll get a datetime with a date value of the passed date and a time value of 00:00:00. If the data cannot be interpreted as a datetime, then a datetime value of 1900-01-01 00:00:00 will be returned.

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_datetime("2014-12-11 20:54:38") --> evaluates to: 12/11/2014 20:54:38
. ph_datetime("2014-12-11") --> evaluates to: 12/11/2014 00:00:00
. ph_datetime("20:54:38") --> evaluates to: 01/14/2015 20:54:38 {today() is implied}
. ph_datetime("1/14/2015") --> evaluates to: 1/14/2015 00:00:00


ph_getglobal_d

ph_getglobal_d PowerHome formula function
Description
Retrieves a global variable and returns the data as a date.
Syntax
ph_getglobal_d ( id )
Argument | Description
id | String identifying the global variable you wish to retrieve. NOTE: Should be all uppercase.
Return value
Date. The data stored within the global variable will be returned as a date. You should only use this function if you know that the data stored within the global variable can be properly converted to a date.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_getglobal_d("LAST_MOTION")
• ph_getglobal_d("[TEMP4]") --> where TEMP4 contains a Global variable name.


ph_getglobal_dt

ph_getglobal_dt PowerHome formula function
Description
Retrieves a global variable and returns the data as a datetime.
Syntax
ph_getglobal_dt ( globalname )
Argument | Description
globalname | String identifying the global variable you wish to retrieve. NOTE: Should be all uppercase.
Return value
Datetime. The data stored within the global variable will be returned as a datetime. You should only use this function if you know that the data stored within the global variable can be properly converted to a datetime.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_getglobal_dt("LAST_TRIGGER")


ph_getglobal_t

ph_getglobal_t PowerHome formula function
Description
Retrieves a global variable and returns the data as a time.
Syntax
ph_getglobal_t ( id )
Argument | Description
id | String identifying the global variable you wish to retrieve. NOTE: Should be all uppercase.
Return value
Time. The data stored within the global variable will be returned as a time. You should only use this function if you know that the data stored within the global variable can be properly converted to a time.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_getglobal_t("LAST_MOTION_TIME")


ph_getsuntime

ph_getsuntime PowerHome formula function
Description
Returns the time of the specified sun calculation on the specified date.
Syntax
ph_getsuntime ( dt, type )
Argument | Description
dt | The date that you wish to retrieve the sun time for.
type | The type of sun calculation you wish returned. Use 1 for Sunrise, 2 for Sunset, 3 for Dawn (start of civil twilight), and 4 for Dusk (end of civil twilight).
Return value
Time. The time of the specified sun calculation for the specified date.


ph_getvar_d

ph_getvar_d PowerHome formula function
Description
Retrieves the specified system variable as a date.
Syntax
ph_getvar_d ( type, num )
Argument | Description
type | Integer. The type of system variable you wish to retrieve. Valid values are 1, 2, 3, and 4. A 1 specifies that you wish to retrieve LOCAL variables (the same as system variables LOCAL1 thru LOCAL10), a 2 specifies that you wish to retrieve TEMP variables (the same as system variables TEMP1 thru TEMP10), and a 3 specifies that you wish to retrieve GLOBAL variables (the same as system variables GLOBAL1 thru GLOBAL20). A value of 4 is a special case and represents data that is only available during the execution of Analog I/O formulas (the Calculated to Raw and Raw to Calculated formulas). Use a num value of 2 to return the calc value of the Analog device as a date. This would look like ph_getvar_d(4,2).
num | Integer. The number of the specified system variable type you wish to retrieve. To retrieve system variable TEMP7 use ph_getvar_d(2,7).
Return value
Date. The data stored within the specified system variable returned as a date. You should be certain that the system variable contains data that can be properly converted to a date value.
Examples
The following examples demonstrate typical syntax/ usage for this function.
. ph_getvar_d (1,2) --> get the date from LOCAL2. The result is returned in a datetime format with zero time values, eg --> 01/23/2014 00:00:00
. ph_getvar_d (2,4) --> get the date from TEMP4. The result is returned in a datetime format with zero time values, eg --> 01/23/2014 00:00:00


ph_getvar_dt

ph_getvar_dt PowerHome formula function
Description
Retrieves the specified system variable as a datetime.
Syntax
ph_getvar_dt ( type, num )
Argument | Description
type | Integer. The type of system variable you wish to retrieve. Valid values are 1, 2, 3, and 4. A 1 specifies that you wish to retrieve LOCAL variables (the same as system variables LOCAL1 thru LOCAL10), a 2 specifies that you wish to retrieve TEMP variables (the same as system variables TEMP1 thru TEMP10), and a 3 specifies that you wish to retrieve GLOBAL variables (the same as system variables GLOBAL1 thru GLOBAL20). A value of 4 is a special case and represents data that is only available during the execution of Analog I/O formulas (the Calculated to Raw and Raw to Calculated formulas). Use a num value of 2 to return the calc value of the Analog device as a datetime. This would look like ph_getvar_dt(4,2).
num | Integer. The number of the specified system variable type you wish to retrieve. To retrieve system variable TEMP7 use ph_getvar_dt(2,7).
Return value
Datetime. The data stored within the specified system variable returned as a datetime. You should be certain that the system variable contains data that can be properly converted to a datetime value.
Examples
The following examples demonstrate typical syntax/ usage for this function.
. ph_getvar_dt (1,2) --> get the datetime from LOCAL2. The result is returned in a datetime format, eg --> 01/23/2014 14:31:25:583
. ph_getvar_dt (2,4) --> get the datetime from TEMP4. The result is returned in a datetime format, eg --> 01/23/2014 14:31:25:583


ph_getvar_t

ph_getvar_t PowerHome formula function
Description
Retrieves the specified system variable as a time.
Syntax
ph_getvar_t ( type, num )
Argument | Description
type | Integer. The type of system variable you wish to retrieve. Valid values are 1, 2, 3, and 4. A 1 specifies that you wish to retrieve LOCAL variables (the same as system variables LOCAL1 thru LOCAL10), a 2 specifies that you wish to retrieve TEMP variables (the same as system variables TEMP1 thru TEMP10), and a 3 specifies that you wish to retrieve GLOBAL variables (the same as system variables GLOBAL1 thru GLOBAL20). A value of 4 is a special case and represents data that is only available during the execution of Analog I/O formulas (the Calculated to Raw and Raw to Calculated formulas). Use a num value of 2 to return the calc value of the Analog device as a time. This would look like ph_getvar_t(4,2).
num | Integer. The number of the specified system variable type you wish to retrieve. To retrieve system variable TEMP7 use ph_getvar_t(2,7).
Return value
Time. The data stored within the specified system variable returned as a time. You should be certain that the system variable contains data that can be properly converted to a time value.
Examples
The following examples demonstrate typical syntax/ usage for this function.
. ph_getvar_t (1,2) --> get the time value from LOCAL2. The result is returned in a time format, eg --> 16:49:04:25
. ph_getvar_t (2,4) --> get the time value from TEMP4.


ph_getx10dt

ph_getx10dt PowerHome formula function
Description
Retrieves the datetime of the last status change for the specifed X10 Device ID.
Syntax
ph_getx10dt ( s )
Argument | Description
s | A string containing the ID of the X10 Device from which you wish to retrieve the datetime of the last status change.
Return value
Datetime. Returns the datetime value of the last status change associated with the specified X10 Device ID that PowerHome currently has stored.


ph_getx10seconds

ph_getx10seconds PowerHome formula function
Description
Retrieves the number of seconds elapsed since the last status change for the specifed X10 Device ID.
Syntax
ph_getx10seconds ( s )
Argument | Description
s | A string representing the X10 Device ID from which you wish to retrieve the seconds elapsed since last status change.
Return value
Long. Returns the number of elapsed seconds since the last status change associated with the specified X10 Device ID that PowerHome currently has stored.


ph_isdaylightsavings

ph_isdaylightsavings PowerHome formula function
Description
Returns whether or not the passed date is under daylight savings time or not.
Syntax
ph_isdaylightsavings ( d )
Argument | Description
d | A date value you wish to check for whether or not it falls under daylight savings time.
Return value
Integer. Returns a 1 if the date falls within daylight savings time. Returns 0 if it does not. The method used to determine daylight savings time is the standard algorithm for North America and is not dependant upon region settings configured within the machine.


ph_minutesafter

ph_minutesafter PowerHome formula function
Description
Returns the number of minutes that have elapsed between two datetimes.
Syntax
ph_minutesafter ( dt, dt )
Argument | Description
dt | A datetime representing the start datetime.
dt | A datetime representing the end datetime.
Return value
Double. Returns the number of minutes that have elapsed between the start and end datetimes. Partial minutes are represented in decimal format. If the end date is earlier than the start date, the returned value will be negative.


ph_minutestostring

ph_minutestostring PowerHome formula function
Description
Use this function to convert a numeric representation of minutes into a string.
Syntax
ph_minutestostring ( minutes, flags )
Argument | Description
minutes | Double. A decimal number representing the minutes to conver. For one hour, three and a half minutes, the value would be 63.5
flags | Integer. This parameter controls how to structure the output string. See usage below.
Return value
String. The minutes converted into a string representation is returned.
Usage
Details of the flags parameter is in the table below:
1 | Add 1 to the flags parameter to include milliseconds in the string output.
2 | Add 2 to the flags parameter to include seconds in the string output.
4 | Add 4 to the flags parameter to include minutes in the string output.
8 | Add 8 to the flags parameter to include hours in the string output.
16 | Add 16 to the flags parameter to include days in the string output.
32 | Add 32 to the flags parameter to include weeks in the string output.
64 | Add 64 to the flags parameter to include months in the string output.
128 | Add 128 to the flags parameter to include years in the string output.
256 | Add 256 to the flags parameter to include all other specified values in the output even if they are blank.
Add individual values together to get the flags value.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_minutestostring(63.5,14)
The above example will take 63 and a half minutes and will convert it into hours, minutes, and seconds (flags = 14). The returned output will be: 1 hour, 3 minutes, 30 seconds


ph_multixtime

ph_multixtime PowerHome formula function
Description
Gets values from a previous incoming X10 time buffer.
Syntax
ph_multixtime ( s, start )
Argument | Description
s | A string identifying the buffer you wish to access. Use "" for the global buffer. Use "EXT" for the extended buffer. Use "A" for housecode A, etc.
start | An integer identifying the number of the command whose time you wish returned. 1 is the most recent and 20 is the oldest.
Return value
String. The time is returned as a string in the format of "hh:mm:ss".


ph_powerhomeuptime

ph_powerhomeuptime PowerHome formula function
Description
Returns the number of seconds that PowerHome has been running.
Syntax
ph_powerhomeuptime ( )
Return value
Unsignedlong. Returns the number of seconds that PowerHome has been running.


ph_powerhomeuptime_s

ph_powerhomeuptime_s PowerHome formula function
Description
Returns a string representing how long PowerHome has been running.
Syntax
ph_powerhomeuptime_s ( )
Return value
String. Returns how long PowerHome has been running in the format of: XX Days XX Hours XX Minutes XX Seconds.


ph_relativedatetime

ph_relativedatetime PowerHome formula function
Description
Given a valid datetime value (either the output of a function eg, datetime() or a datetime 'literal' value such as 2010-12-15 12:30:00 ) and a number representing the number of minutes to be calculated in the future (positive number) or in the past (negative number) this function determines a new datetime value. Partial minutes are expressed as decimal numerbs (eg 2 minutes and 30 seconds would be 2.5). If only a date is given in the first argument, the time is assumed to be 00:00:00.

See the Date / Time Functions section for detailed information concerning date / time formats.

Returns a new datetime value relative to the passed datetime and offset values.

If greater time accuracy is needed, see the ph_relativedtprecise() function.

Syntax
ph_relativedatetime ( dt, n )
Argument | Description
dt | A datetime value which is the starting datetime.
n | A double value representing the number of minutes (partial minutes are in decimal format) in the future (positive values) or the past (negative values) that the new datetime should be offset from the starting datetime.

Return value
Datetime. Returns a new datetime value relative to the starting datetime.

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_relativedatetime(2015-01-15 00:00:00, 10)--> evaluates to: 12/15/2015 00:10:00
. ph_relativedatetime(today(), 10) --> evaluates to: 01/15/2015 14:37:08


ph_relativedtprecise

ph_relativedtprecise PowerHome formula function
Description
Returns a datetime value relative to the passed offset and datetime value (either the output of a function eg, datetime() or a datetime 'literal' value such as 2010-12-15 12:30:00 ).

The returned time value will be to millisecond precision.

See the Date / Time Functions section for detailed information concerning date / time formats.

Similar to the ph_relativedatetime() function but with greater time accuracy.

Syntax
ph_relativedtprecise ( dt, n )
Argument | Description
dt | A datetime value which is the starting datetime.
n | A double value representing the number of seconds (partial seconds are in decimal format) in the future (positive values) or the past (negative values) that the new datetime should be offset from the starting datetime.

Return value
Datetime. Returns a new datetime value relative to the starting datetime with the time component to millisecond precision.

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_relativedtprecise(2015-01-15 00:00:00, 10.167)--> evaluates to: 12/15/2015 00:10:167
. ph_relativedtprecise(today(), 10.33) --> evaluates to: 01/15/2015 16:30:05:375


ph_relativetime

ph_relativetime PowerHome formula function
Description
Obtains a time that occurs a specified number of seconds after or before another time within a 24-hour period.
Syntax
ph_relativetime ( time, n )
Argument | Description
time | A time value
n | A long number of seconds
Return value
Time. Returns the time that occurs n seconds after time if n is greater than 0. Returns the time that occurs n seconds before time if n is less than 0. The returned time is in milliseconds precision.
Usage
This function is similar to the relativetime function whose time is returned in microsecond precision. Use this function when trying to save the resulting time to the PowerHome database since the database does not support microsecond precision.


ph_seconds

ph_seconds PowerHome formula function
Description
Returns the current system time as a double number representing the number of seconds past midnight.
Syntax
ph_seconds ( )
Return value
Double. Returns the system time as the number of seconds past midnight. This funciton will return up to 3 decimal places of precision.


ph_secondsafter

ph_secondsafter PowerHome formula function
Description
Returns the number of seconds one time occurs after another.
Syntax
ph_secondsafter ( time1, time2 )
Argument | Description
time1 | A time value that is the start time of the interval being measured
time2 | A time value that is the end time of the interval
Return value
Double. Returns the number of seconds time2 occurs after time1. If time2 occurs before time1, a negative value is returned. Partial seconds are represented in decimal format.


ph_secondsdiff

ph_secondsdiff PowerHome formula function
Description
Returns the number of seconds one time occurs after another.
Syntax
ph_secondsdiff ( time1, time2 )
Argument | Description
time1 | A time value that is the start time of the interval being measured
time2 | A time value that is the end time of the interval
Return value
Double. Returns the number of seconds time2 occurs after time1. This function always assumes that time2 occurs after time1. If time1 is 23:59:59 and time2 is 00:00:01 then the returned value will be 2 even though time2 is less than time1. Partial seconds are returned in decimal format.


ph_secondsdiffsec

ph_secondsdiffsec PowerHome formula function
Description
Returns the difference between two times (represented as a double number containing the number of seconds past midnight)
Syntax
ph_secondsdiffsec ( time1, time2 )
Argument | Description
time1 | Double representing the earlier time.
time2 | Double representing the later time.
Return value
Double. Returns the difference between the two times. If time2 happens to be less than time1 (such as when crossing midnight), then 86400.0 will be added to time2 to account for the extra day.


ph_windowsuptime_s

ph_windowsuptime_s PowerHome formula function
Description
Returns a string representing how long Windows has been running.
Syntax
ph_windowsuptime_s ( )
Return value
String. Returns how long Windows has been running in the format of: XX Days XX Hours XX Minutes XX Seconds. The data for this function is obtained from the ph_gettickcount function.


relativedate

relativedate PowerHome formula function
Description
Obtains either a date or datetime that occurs a specified number of days after or before a given date or datetime.

See the Date / Time Functions section for detailed information concerning date / time formats.

If only a date value is given the returned value will be only a date (see first example below), but if a datetime value is given then the retuned value will also be a datetime. (See examples 2-3 below).

Syntax
relativedate ( date, n )
Argument | Description
date | A date or datetime value
n | An integer indicating the number of days

Return value
Date or DateTime. Returns the date or datetime that occurs n days after date if n is greater than 0. Returns the date/datetime that occurs n days before date if n is less than 0.

Examples
The following examples demonstrate typical syntax/usage for this function.
. relativedate(2015-01-15, 2) --> evaluates to: 01/17/2015
• relativedate(2015-01-15 10:05:00, 2) --> evaluates to: 01/17/2015 10:05:00
. relativedate(today(), 2) --> evaluates to: 01/17/2015 10:12:31:654


relativetime

relativetime PowerHome formula function
Description
Obtains a time that occurs a specified number of seconds after or before another time within a 24-hour period.

See the Date / Time Functions section for detailed information concerning date / time formats.

Syntax
relativetime ( time, n )
Argument | Description
time | A time value
n | A long number of seconds {Fractional seconds are not supported}
Return value
Time. Returns the time that occurs n seconds after time if n is greater than 0. Returns the time that occurs n seconds before time if n is less than 0. The maximum return value is 23:59:59.

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_relativetime(now(), 10)--> evaluates to: 16:43:21:173
. ph_relativetime(15:00:00, 20) --> evaluates to: 15:00:20


second

second PowerHome formula function
Description
Obtains the number of seconds in the seconds portion of a time value.
Syntax
second ( time )
Argument | Description
time | The time value from which you want the seconds
Return value
Integer. Returns the seconds portion of time (00 to 59).


secondsafter

secondsafter PowerHome formula function
Description
Gets the number of seconds one time occurs after another.
Syntax
secondsafter ( time1, time2 )
Argument | Description
time1 | A time value that is the start time of the interval being measured
time2 | A time value that is the end time of the interval
Return value
Long. Returns the number of seconds time2 occurs after time1. If time2 occurs before time1, SecondsAfter returns a negative number.


today

today PowerHome formula function
Description
Obtains the current date and time based on the system time of the client machine.
Syntax
today ( )
Return value
DateTime. Returns the current datetime based on the system time of the client machine.
Examples
The following examples demonstrate typical syntax/usage for this function.
• today() --> 09/26/2013 18:38:15:306


year

year PowerHome formula function
Description
Gets the year of a date value.
Syntax
year ( date )
Argument | Description
date | The date value from which you want the year
Return value
Integer. Returns an integer whose value is a 4-digit year adapted from the year portion of date if it succeeds and 1900 if an error occurs.

If the year is two digits, then the century is chosen as follows. If the year is between 00 to 49, PowerHome assumes 20 as the first two digits; if it is between 50 and 99, PowerHome assumes 19.
Usage
Obtains the year portion of date. PowerHome handles years from 1000 to 3000 inclusive.

If your data includes dates before 1950, such as birth dates, always specify a 4-digit year so that year and other functions interpret the date as intended


ph_copyfile

ph_copyfile PowerHome formula function
Description
Makes a copy of the specified file.
Syntax
ph_copyfile ( sourcefilespec, targetfilespec, writemode )
Argument | Description
sourcefilespec | String representing the full path and filename of the source file.
targetfilespec | String representing the full path and filename of the target file.
writemode | Integer representing whether to overwrite the file if it already exists. Use 0 to keep an existing file, any other value to overwrite.
Return value
Integer. Returns a 0 if the source file was successfully copied. Returns -1 if an error occurred opening the source file. Returns -2 if an error occurred opening the target file.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_copyfile("C:/powerhome/powerhome.db","C:/Documents/BakUps/powerhome.db",1)


ph_createdirectory

ph_createdirectory PowerHome formula function
Description
Creates the specified directory.
Syntax
ph_createdirectory ( filespec )
Argument | Description
filespec | String representing the directory path/name you wish to have created. This function will only create a single directory at a time.
Return value
Integer. Returns a 0 if successful and 1 if an error occurs.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_createdirectory("C:/SprinklerTimes")


ph_deletefile

ph_deletefile PowerHome formula function
Description
Deletes the specified file.
Syntax
ph_deletefile ( targetfilespec )
Argument | Description
targetfilespec | String representing the full path and filename of the file to delete.
Return value
Integer. Returns a 0 if the file was successfully deleted. Returns 1 if an error occurred.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_deletefile("C:/powerhome/Bak/powerhome.db")


ph_fileexists

ph_fileexists PowerHome formula function
Description
Checks whether the specified file exists or not.
Syntax
ph_fileexists ( filespec )
Argument | Description
filespec | String representing the full path and filename of the file to check.
Return value
Integer. Returns a 1 if the file exists. Returns 0 if the file is not found.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_fileexists("C:/powerhome/myalerts.txt")


ph_filelength

ph_filelength PowerHome formula function
Description
Returns the length of the specified file in bytes.
Syntax
ph_filelength ( sourcefilespec )
Argument | Description
sourcefilespec | String representing the full path and filename of the source file.
Return value
Long. Returns the length of the specified file in bytes.

Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_filelength("C:/powerhome/MotionDetection.txt")


ph_filelist

ph_filelist PowerHome formula function
Description
Retrieves a list of files/directories from a specified drive and location.
Syntax
ph_filelist ( filespec, include, exclude, sorted, outputtype )
Argument | Description
filespec | String. The file search specification for the returned filelist. Wildcards are allowed. Ex: "c:\program files\powerhome\*.pbd"
include | Long. Only include files with the specified attributes. Use 0 to include all files. Individual attributes should be added together. Typical values are: 1 - ReadOnly, 2 - Hidden, 4 - System, 16 - Directory, 32 - Archive, 2048 - Compressed, 16384 - Encrypted.
exclude | Long. Exclude files with these attributes. Use 0 to not exclude files. Individual attributes should be added together. Typical values are: 1 - ReadOnly, 2 - Hidden, 4 - System, 16 - Directory, 32 - Archive, 2048 - Compressed, 16384 - Encrypted.
sorted | Integer. Use 0 to return an unsorted list. Any other value to sort.
outputtype | Integer. How the output should be returned. Use 0 to return the list as values separted by cr/lf, 1 to return as comma separated values, 2 to return as XML, and 3 to return as an HTML Table.
Return value
String. Returns the list of files/directories in the format specified by the output type.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_filelist("c:\findMyPhone.txt",0,0,0,0) {Finds specific file}
• ph_filelist("c:\*.txt",0,0,0,0) {Finds all "jpg" files in powerhome directory and lists them unsorted}
• ph_filelist("c:\*.txt",0,5,1,1) {Finds all "jpg" files in powerhome directory that are everything,not Read Only/System, sorts them, and returns them as comma separated values}


ph_getphdir

ph_getphdir PowerHome formula function
Description
Returns the full path to the PowerHome directory.
Syntax
ph_getphdir ( )
Return value
String. Returns the full path to the PowerHome directory.
Usage
This function returns the full path to the installation home of PowerHome. The default is: c:\program files\powerhome


ph_getphwebdir

ph_getphwebdir PowerHome formula function
Description
Returns the full path to the PowerHome webserver directory.
Syntax
ph_getphwebdir ( )
Return value
String. Returns the full path to the PowerHome webserver directory.
Usage
This function returns the full path to the PowerHome webserver root directory. This location is contained within the pwrhome.ini file and can be configured from the PowerHome Explorer under Setup->Web. The default is: c:\program files\powerhome\web


ph_getwindowsdir

ph_getwindowsdir PowerHome formula function
Description
Returns the full path to the PowerHome machines windows or system32 directory
Syntax
ph_getwindowsdir ( type )
Argument | Description
type | An integer representing the particular Windows directory path to return. Use 0 for the Windows directory, any other value for the Windows System32 directory.
Return value
String. The path to the windows or system32 directory.
Usage
The returned values are the same as the system variables [WINDIR] and [SYS32DIR]


ph_movefile

ph_movefile PowerHome formula function
Description
Moves the specified file.
Syntax
ph_movefile ( s, s )
Argument | Description
s | String representing the full path and filename of the source file.
s | String representing the full path and filename of the target file.
Return value
Integer. Returns a 0 if the source file was successfully moved. Returns -1 if an error occurred opening the source file. Returns -2 if an error occurred opening the target file.
Usage
You cannot write to a target file if a file with the same name already exists in the target directory. If you want to copy over a target file, you can use ph_filecopy and set the replace argument to 1.


ph_readfile

ph_readfile PowerHome formula function
Description
Reads the contents of a file into memory and returns it as either a string or hex encoded string
Syntax
ph_readfile ( as_filename )
ph_readfile ( as_filename, ai_type )
Argument | Description
as_filename | String. The full path and filename of the file you wish to read
ai_type | Integer (Optional). Parameter controlling how the file data is returned. Use 0 to return as a normal string. Any other value will read the file contents and encode them as a hex encoded string. If this parameter is omitted, the default value of 0 will be assumed
Return value
String. Returns the contents of the file as a string or hex encoded string
Usage
Use this function to read the contents of a file and return the data as a string. For textual based files, you'll usually want to use an ai_type of 0. If the file contains binary data such as a graphic file, set the ai_type parameter to 1 so the data will be returned as a hex encoded string
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_readfile("C:\powerhome\web\logtemp\last.csv")
. ph_readfile("c:\powerhome\web\ph.gif",1)


ph_removedirectory

ph_removedirectory PowerHome formula function
Description
Creates the specified directory.
Syntax
ph_removedirectory ( path )
Argument | Description
path | A string representing the directory you wish to remove. This function can only remove a single directory at a time.
Return value
Integer. Returns a 0 if successful and 1 if an error occurs.


ph_saveitcurl

ph_saveitcurl PowerHome formula function
Description
Saves the data from the specified URL using a Microsoft ITC (Internet Transfer Control)
Syntax
ph_saveitcurl ( s, s, n, n )
Argument | Description
s | The URL you wish to save.
s | The directory / filename you wish to save to.
n | The write mode to use when saving. A 0 will cause the data to be appended to the file if it exists. Any other value will replace the file if it exists.
n | The timeout in seconds for the request to be executed. Use 0 for infinity.
Return value
Integer. Returns 0 if successful. 1 is returned if the file cannot be opened. 2 is returned if the timeout value is exceeded. 3 is returned if the ITC encounters an error. 4 is returned if a runtime error occurs.


ph_saveurl

ph_saveurl PowerHome formula function
Description
Retrieves the specified URL and saves the returned body to a file.
Syntax
ph_saveurl ( s, s, n )
Argument | Description
s | String representing URL you wish to retrieve.
s | String representing the full path and filename you wish to save the URL's data to.
n | Integer representing whether to overwrite the file if it exists or append to it. A 0 will cause the data to be appended to the existing file. Any other value will cause the file to be replaced.
Return value
String. Returns the http header of the requested URL if the function succeeds. Otherwise, a message indicating the error is returned.
Usage
Use this function to retrieve and save HTML, text, graphic, or binary data from a URL to a file.


ph_saveurlviaproxy

ph_saveurlviaproxy PowerHome formula function
Description
Retrieves the specified URL via a proxy and saves the returned body to a file.
Syntax
ph_saveurlviaproxy ( s, s, n, s, s, n )
Argument | Description
s | String representing URL you wish to retrieve.
s | String identifying the proxy server you wish to use.
n | Integer identifying the port of the proxy server.
s | String identifying the userid and password for the proxy server. Separate the userid from the password using a colon character. Example: userid:password.
s | String representing the full path and filename you wish to save the URL's data to.
n | Integer representing whether to overwrite the file if it exists or append to it. A 0 will cause the data to be appended to the existing file. Any other value will cause the file to be replaced.
Return value
String. Returns the http header of the requested URL if the function succeeds. Otherwise, a message indicating the error is returned.
Usage
Use this function to retrieve and save HTML, text, graphic, or binary data from a URL to a file. Same as the ph_saveurl function except you have the option to specify specific proxy server information.


ph_sendemailfile

ph_sendemailfile PowerHome formula function
Description
Sends an email message with file attachments.
Syntax
ph_sendemailfile ( s, s, s, s )
Argument | Description
s | The email addresses you wish to send a message to. Separate multiple email addresses with commas.
s | The subject of the email.
s | The text of the email message.
s | The full path and filename of the file to attach to the email. Separate multiple files with the | (vertical bar) character.
Return value
Integer. Returns 0 if successful, 1 if an error occurred while logging in to the mail system, and 2 if an error occurred while sending the email message. You can specify multiple recipients by separating the email addresses with commas. Specify multiple files by separating the path/filename with the | (vertical bar) character.


ph_sendsmtpemailfile

ph_sendsmtpemailfile PowerHome formula function
Description
Sends an email message with file attachments using SMTP.
Syntax
ph_sendsmtpemailfile ( s, n, s, s, s, s, s )
Argument | Description
Server | String. The IP or DSN of the SMTP server.
Port | Number. The port of the SMTP server. This is typically port 25.
fromAddr | String. The email address you are sending the email from. Most SMTP servers require you to enter a valid email address registered on the SMTP server. You may optionally enter a userid and password if your SMTP server requires authentication.
toAddr | String. The email addresses you wish to send a message to. Separate multiple email addresses with commas.
Subject | String. The subject of the email.
text | String. The text of the email message.
filespec | String. The full path and filename of the file to attach to the email. Separate multiple files with the | (vertical bar) character.
Return value
Integer. Returns 0 if successful. Any other value signifies an error occurred. You can specify multiple recipients by separating the email addresses with commas. Specify multiple files by separating the path/filename with the | (vertical bar) character.
Usage
Use this function to send email with file attachments using raw SMTP rather than the MAPI interface that the ph_sendemail function uses. If an error occurs while sending using SMTP, the PowerHome system will not hang like it does when sending using MAPI.

If your SMTP server requires authentication, then supply the userid and password in the third parameter after the "From" email address. Separate the "from" email address, userid, and password with commas (do not add spaces).
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_sendsmtpemailfile("smtp.mail.yahoo.com",465,"yourname@yahoo.com,login,password", "8885551212@txt.att.net","Motion Alert","Driveway Motion on CAM1 detected.","C:\powerhome\web\CAM1.jpg")


ph_setfileattrib

ph_setfileattrib PowerHome formula function
Description
Sets the attributes of the specified file.
Syntax
ph_setfileattrib ( s, n )
Argument | Description
s | A string representing the full path and filename whose attributes you wish to change.
n | An integer representing the attributes to assign to the file. Add the individual attributes listed below.
Return value
Integer. Returns a 0 if successful, 1 if the function fails.
Usage
Use this function to set the attributes of a file. You assign the attributes by adding together the attributes that you wish the file to have and using this summed value for n. The individual attribute values are: Archive = 32, Hidden = 2, Normal = 128, Readonly = 1, and System = 4. For example, if you wanted to make a file hidden and readonly, use a value of 3.


ph_writefile

ph_writefile PowerHome formula function
Description
Writes data to the specified file
Syntax
ph_writefile ( as_filename, ai_writemode, as_data )
ph_writefile ( as_filename, ai_writemode, as_data, ai_type )
Argument | Description
as_filename | String. A string representing the path and filename of the file you wish to write to
ai_writemode | Integer. An integer representing how you wish to write to the file. A value of 0 will append the data to the file, any other value will cause the file to be overwritten
as_data | String. A string representing the data you wish to write to the file
ai_type | Integer (Optional). Specified the type of data that is contained within as_data. If 0, the data is assumed to be standard string data and will be written to the file as is. Any other value means that as_data contains a hex encoded string that will first be decoded and then the results will be written to the specified file. If this parameter is omitted, a value of 0 is assumed
Return value
Integer. Returns a 0 if successful. Returns a 1 if an error occurred while opening the file
Usage
Use this function to write data to a file. If the file does not exist, it will first be created. You can write binary data to a file by representing it as a hex encoded string and using an ai_type value other than 0
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_writefile("c:\powerhome\logs\log.txt",0,string(datetime(today(),now())) + ":" + ph_getvar_s(1,1) + "~r~n") - Appends the current date and time along with the data contained in [LOCAL1] to the c:\powerhome\logs\log.txt file
. ph_writefile("c:\powerhome\test.txt",1,"54455354",1) - Overwrites or creates the file c:\powerhome\test.txt and writes the string TEST to the file


profileint

profileint PowerHome formula function
Description
Obtains the integer value of a setting in the specified profile file.
Syntax
profileint ( filename, section, key, default )
Argument | Description
filename | A string whose value is the name of the profile file. If you do not specify a full path, ProfileInt uses the operating system's standard file search order to find the file
section | A string whose value is the name of a group of related values in the profile file. In the file, section names are in square brackets. Do not include the brackets in section. Section is not case-sensitive
key | A string specifying the setting name in section whose value you want. The setting name is followed by an equal sign in the file. Do not include the equal sign in key. Key is not case-sensitive
default | An integer value that ProfileInt will return if filename is not found, if section or key does not exist in filename, or if the value of key cannot be converted to an integer
Return value
Integer. Returns default if filename is not found, section is not found in filename, key is not found in section, or the value of key is not an integer. Returns -1 if an error occurs.
Usage
Use ProfileInt and ProfileString to get configuration settings from a profile file you have designed for your application.


profilestring

profilestring PowerHome formula function
Description
Obtains the string value of a setting in the specified profile file.
Syntax
profilestring ( filename, section, key, default )
Argument | Description
filename | A string whose value is the name of the profile file. If you do not specify a full path, ProfileString uses the operating system's standard file search order to find the file
section | A string whose value is the name of a group of related values in the profile file. In the file, section names are in square brackets. Do not include the brackets in section. Section is not case-sensitive
key | A string specifying the setting name in section whose value you want. The setting name is followed by an equal sign in the file. Do not include the equal sign in key. Key is not case-sensitive
default | A string value that ProfileString will return if filename is not found, if section or key does not exist in filename, or if the value of key cannot be converted to an integer
Return value
String, with a maximum length of 4096 characters. Returns the string from key within section within filename. If filename is not found, section is not found in filename, or key is not found in section, ProfileString returns default. If an error occurs, it returns the empty string ("").
Usage
Use ProfileInt and ProfileString to get configuration settings from a profile file you have designed for your application.


setprofilestring

setprofilestring PowerHome formula function
Description
Creates or modifies a value within an INI file.
Syntax
setprofilestring ( filename, section, key, value )
Argument | Description
filename | A string containing the full path and filename of the INI file. If you don't include the full path, then PowerHome searches the path for filename.
section | A string containing the section to modify. If section does not exist, PowerHome will create it.
key | A string containing the key within a section to modify. If key does not exist, PowerHome will create it.
value | A string containing the value you wish assigned to the key.
Return value
Integer. Returns 1 if successful and - 1 if the filename cannot be found or accessed.


case

case PowerHome formula function
Description
Tests the values of a expression and returns values based on the results of the test.
Syntax
case ( expression WHEN value1 THEN result1 { WHEN value2 THEN result2 { ... } } { ELSE resultelse } )
Argument | Description
expression | Expression. An expression whose values you want to test. Expression is compared to each valuen in turn until success or ELSE. The expression can evalute to nearly any datatype including string, numeric, date, time, datetime, or boolean. The datatype of the expression MUST match the datatype of the value list.
WHEN (optional) | Introduces a value-result pair. At least one WHEN is required.
valuen | Value with same datatype as expression. One or more values that you want to compare to values of expression (value datatype must match expression datatype). A value can be: A single value A list of values separated by commas (for example: 2, 4, 6, 8 or: "Play","Pause","Mute") A TO clause (for example: 1 TO 20 or: "AAA" TO "BBB") IS followed by a relational operator and comparison value (for example: IS>5 or: IS<"DDD") Any combination of the above with an implied OR between expressions (for example, 1,3,5,7,9,27 TO 33, IS>42)
THEN | Introduces the result to be returned when expression matches the corresponding valuen
resultn | Expression. An expression whose value is returned by Case for the corresponding valuen. All resultn values must have the same datatype.
ELSE (optional) | Specifies that for any values of expression that don't match the values of valuen already specified, Case returns resultelse.
resultelse | Expression. An expression whose value is returned by Case when the value of expression doesn't match any WHEN valuen expression.
Return value
The datatype of resultn. Returns the result you specify in resultn.
Usage
If more than one WHEN clause matches the expression, Case returns the result of the first matching one.
Examples
The following examples demonstrate typical syntax/usage for this function.
• case([TEMP2] when 17 TO 20 then 4 Else 1)
• case([LOCAL1] when 1 then "DriveCam" when 2 then "HouseCam" when 3 then "PorchCam" when 4 then "TheaterCam" Else "Unknown Cam #[LOCAL1]")
• case({CURTEMP} WHEN is> 50 THEN "1" WHEN is> 30 THEN "3" ELSE "999")
• case(ph_getinsteonstat("[LOCAL2]") when 1 then "ifastoff" when 2 then "ifaston" else "?")
• case("[TEMP10]" WHEN "Play" THEN 1 WHEN "Pause" THEN 2 WHEN "Mute" THEN 3 ELSE 999)
• case(now() WHEN time("10:00:00) TO time("13:25:00") THEN 1 WHEN time("15:00:00) TO time("17:45:00") THEN 2 ELSE 0)


if

if PowerHome formula function
Description
Evaluates a condition and returns a value based on that condition.
Syntax
if ( boolean, truevalue, falsevalue )
Argument | Description
boolean | A boolean expression that evaluates to TRUE or FALSE
truevalue | A value containing the value you want returned if the boolean expression is TRUE
falsevalue | A value containing the value you want returned if the boolean expression is FALSE
Return value
The data type of truevalue or falsevalue. Returns truevalue if boolean is TRUE and falsevalue if it is FALSE. Returns NULL if an error occurs.
Usage
The IF function is one of the basic building blocks of PowerHome macros, allowing modification in program flow, parameter testing to determine if they fail, meet, or exceed expectations, and appropriate message display.

NOTE: the treuvalue/falsevalue parameters should reflect the data type expected by the function using the Return from the IF.

If a string is expected then the IF values will use quotes (eg, if({OPEN}=1,"Open","Closed"), but numbers, integers, datetime values, etc should be used as appropriate for the target function's use.

If a true or false value is not required, put a zero or a null string in that position, eg. if({DARK}=1,ph_insteon("SOFA",ion,200),"") or if({DARK}=1,ph_insteon("SOFA",ion,200),0)

Program Flow
Used in a JUMP Command line of a macro, the IF function allows branching to different program lines depending on the IF test results. The following tests the time of day in Seq line 10 and if after 7:30AM jumps to the next line to turn the studio lights. Otherwise it jumps down three lines and reschedules an event to call itself again in 15 minutes to test again. Alternatively, the 2nd image shows how a GOTO (rather than a JUMP) could be used for better program code clarity (plus avoiding errors later if the macro is changed and the jumps become inaccurate.)

Program Note: The Goto Command jumps to the named target Label, but if there is no matching Label then the jump is to the Next Line. Thus the faux Label "nextLINE" does go the next code line and provides an easy and clear indication of the program flow.
IF Jump

IF Goto

Message Construction
Used in conjunction with Message Commands/Functions, the IF produces messages that match appropriate conditions...
If Messages

Value Modification
The IF function is often used to set or modify data. For instance, if the spotlight illuminating the ceiling is On, then set the SKYLIGHT global to a "1", otherwise "0" IF Global
See also Examples below.

Examples
The following examples demonstrate typical syntax/usage for this function.
• if([LOCAL4]>100,100,[LOCAL4]) --> Trim LOCAL4 value to max of 100.
• if({CURWINDCHILL}>50,"1","5") --> Used in a macro JUMP command would cause a skip down 1 line if CURWINDCHILL was >50.
• if(Now()<08:00:00,"1","4") --> Used in a macro JUMP command would cause a skip down 1 line if the time was earlier than 8AM.
• if({SMS}=1 and {OVRTMP}=1,"ph_sendsmtpemail("smtp.mail.yahoo.com",465,"toname@yahoo.com,loginname,pwtext", "2225551212@txt.att.net","Temp Alert","Freezer Temp out of range at {TEMP-FREEZER_V} degrees.") --> If SMS and OvrTemp flags are set then send text message to phone to give alert.


ph_checktrigger

ph_checktrigger PowerHome formula function
Description
Forces the checking of a trigger. Useful for external applications interfacing with PowerHome via Windows messaging or Socket Server interface.
Syntax
ph_checktrigger ( type, id, number, value, dim, command, data, formula, auxvalue )
Argument | Description
type | The type of trigger to check.
id | The Trigger ID
number | The Trigger Number
value | The Trigger Value.
dim | A double representing the dim value.
command | An unsigned long representing the command.
data | A long representing the data.
formula | A string representing the formula.
auxvalue | A string representing the auxillary value.
Return value
Integer. Returns a 1 if no matching triggers are found. Returns a 0 otherwise.
Usage
This function can be used to force a an internal PowerHome trigger check.


ph_clearexequeue

ph_clearexequeue PowerHome formula function
Description
Clears PowerHome COMM and Execution queues.
Syntax
ph_clearexequeue ( )
Return value
Integer. Returns a 0.
Usage
When executed, this function will clear the PowerHome execution queue and the COMM queue. It does not affect Waiting macros however.

In order for this function to clear waiting execution queue items BEFORE this function is executed, you must execute this function in the boolean field of a trigger.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_clearexequeue() {No arguments needed}


ph_delay

ph_delay PowerHome formula function
Description
Delays execution for the specified number of milliseconds
Syntax
ph_delay ( timedelay )
Argument | Description
timedelay | Integer. The delay time in milliseconds. There are 1000 milliseconds in 1 second. NOTE: Use with caution. This function delays ALL PowerHome processing for the specified time amount, preventing any other macro, trigger, or timed events from happening. Use only with short delays and sparingly as this function delays macro execution for the specified time amount, preventing any other macro, trigger, or timed events from happening.
Return value
Integer. Returns a 0.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_delay(500) {Creates a 0.5 second delay.}


ph_doloop

ph_doloop PowerHome formula function
Description
Evaluates a PowerHome formula repetitively.
Syntax
ph_doloop ( formula, check )
Argument | Description
formula | A string containing the formula that you wish to have evaluated repetitively.
check | A string containing a formula that determines when the loop should exit. If this formula evaluates to a number other than 0 then the loop will exit. The loop will also exit if it evaluates to a boolean false.
Return value
Integer. Returns a 0.
Usage
Use this function to perform formula evaluations repetitively. Note that the formula will always be executed at least 1 time. See also the ph_forloop and ph_whileloop functions.


ph_extendmacrowait

ph_extendmacrowait PowerHome formula function
Description
Extends the amount of wait time for a macro which is currently in a wait state.
Syntax
ph_extendmacrowait ( ad_seconds, ai_type )
ph_extendmacrowait ( as_macro, ad_seconds, ai_type )
Argument | Description
as_macro | String (Optional). The ID of the waiting macro. If this parameter is omitted, the system variable MACRO will be used for the ID
ad_seconds | Double . The number of seconds to extend the wait. Fractions of a second can be represented in decimal format.
ai_type | Integer . The method of extending the wait. A 0 will extend the macro wait time from the time this function is executed. Any other value will extend the wait from the time the macro is currently set to expire.
Return value
Integer. Returns a 0 if the macro wait time was successfully extended. Returns a 1 if the specified macro ID is not waiting or an error occurs.
Usage
Use this function to extend the wait time of a macro that is currently waiting (Initiated by the Macro command "Wait"). If multiple macros with the same ID are waiting, this command will only extend the wait time of the oldest waiting macro. Extending the wait time of a macro does not effect its status as the oldest waiting macro. Typically this function would be used in conjunction with the ph_ismacrowaiting function to first check if a macro is waiting and then either waiting or extending the wait of a currently waiting macro so as not to have more than 1 macro of the same ID waiting.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_extendmacrowait("DELAY",5.5,1) - Extends the wait time of the DELAY macro by an additional 5.5 seconds from when it is currently set to expire


ph_forloop

ph_forloop PowerHome formula function
Description
Evaluates a formula expression a specified number of times.
Syntax
ph_forloop ( formula, n, n, n )
Argument | Description
formula | A string which contains the formula expression you would like to have evaluated.
n | A double representing the starting value of the for loop.
n | A double representing the ending value of the for loop.
n | A double representing the increment value of the for loop.
Return value
Integer. Returns a 0 when the loop is completed. If the increment value is 0, then a value of 1 is returned.
Usage
Use the ph_forloop when you want to evaluate a formula a known number of times. The formula will be evaluated as long as the starting value is less than or equal to the ending value if the increment is a positive number. The formula will be evaluated as long as the starting value is greater than or equal to the ending value if the increment is a negative number. With each iteration, the starting value will be adjusted by the increment value.


ph_forloopwinc

ph_forloopwinc PowerHome formula function
Description
Evaluates a formula expression a specified number of times while incrementing a local variable.
Syntax
ph_forloopwinc ( formula, n, n, n, local )
Argument | Description
formula | A string which contains the formula expression you would like to have evaluated.
n | A double representing the starting value of the for loop.
n | A double representing the ending value of the for loop.
n | A double representing the increment value of the for loop.
local | An integer representing the number of local variable to be incremented.
Return value
Integer. Returns a 0 when the loop is completed. If the increment value is 0, then a value of 1 is returned. If the local variable specified is out of range, then 2 is returned.
Usage
Use the ph_forloopwinc when you want to evaluate a formula a known number of times. The formula will be evaluated as long as the starting value is less than or equal to the ending value if the increment is a positive number. The formula will be evaluated as long as the starting value is greater than or equal to the ending value if the increment is a negative number.

When the function is first executed (prior to the formula being evaluated), the start value will be copied into the local variable. The formula will then be evaluated. The local will then be incremented by the increment value. If the local is still between the start and end values, then the formula will be evaluated again with the whole process repeating itself until the local is no longer between the start and end values.


ph_getforegroundwindow

ph_getforegroundwindow PowerHome formula function
Description
Returns the handle of the currently active window (the foreground window).
Syntax
ph_getforegroundwindow ( )
Return value
Long. Returns the handle of the foreground window.


ph_ismacrowaiting

ph_ismacrowaiting PowerHome formula function
Description
Checks whether the specified macro is currently in a wait state
Syntax
ph_ismacrowaiting ( )
ph_ismacrowaiting ( as_macro )
Argument | Description
as_macro | String (Optional). The ID of the macro to check for a waiting status. If this parameter is omitted, the system variable MACRO will be used
Return value
Long. Returns the number of macros waiting that match the specified ID. If no macros match the ID, then 0 is returned
Usage
Use this function to check if a macro is currently waiting or not. A typical usage would be to execute this function from within a macro to check if that macro is currently waiting or not. If it isnt waiting, continue with processing. If it is waiting, either kill the waiting macro or extend the wait time of the waiting macro. In this use case scenario, you can use the syntax that does not include the as_macro parameter as the currently executing macro ID will be in the MACRO system variable
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_ismacrowaiting("SPRINKLERCYCLE") - Returns 1 (or possibly more) if the SPRINKLERCYCLE is currently in the macro wait queue
. ph_ismacrowaiting() - Returns the number of entries in the macro wait queue for the macro ID that this function was executed from. This ID would be the value in the system variable MACRO


ph_killallmacrowait

ph_killallmacrowait PowerHome formula function
Description
Removes all waiting macros from the Macro Wait Queue.
Syntax
ph_killallmacrowait ( )
Return value
Integer. Returns a 0.


ph_killmacrowait

ph_killmacrowait PowerHome formula function
Description
Deletes the oldest waiting macro matching the specified ID from the Macro Wait Queue
Syntax
ph_killmacrowait ( )
ph_killmacrowait ( as_macro )
Argument | Description
as_macro | String (Optional). The ID of the waiting macro that you would like to have killed. If this parameter is omitted, the system variable MACRO will be used
Return value
Integer. Returns a 1 if no macros matching the ID are waiting. Returns 0 otherwise. If more than one macro matching the ID is waiting, this function only kills the oldest waiting macro
Usage
Use this function to kill a macro that is currently in a wait state. If more than one macro with the same ID is waiting, this will function will ONLY kill the oldest waiting matching macro ID. If this function is called from within a macro and the as_macro parameter is omitted, it will use the value in the system variable MACRO which will be the same ID as the macro from which this function was executed
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_killmacrowait("SPRINKLERCYCLE") - Kills the oldest waiting instance of the macro SPRINKLERCYCLE and returns a 0. If SPRINKLERCYCLE has no waiting instances, nothing happens and a value of 1 is returned.
. ph_killmacrowait() - Kills the oldest waiting instance of a macro with the same ID from which this function was executed


ph_postexequeue

ph_postexequeue PowerHome formula function
Description
Use this function to place either a macro, send keys, raw formula, or device control string into the execution queue
Syntax
ph_postexequeue ( as_formula )
ph_postexequeue ( ai_priority, ai_type, as_formula )
Argument | Description
ai_priority | Integer (Optional). Determines where in the queue the formula is to be placed. See usage below. If this parameter is omitted, a value of 0 will be used
ai_type | Integer (Optional). The type of formula to place in the execution queue. Use 0 for macros, 1 for sendkeys, 2 for raw formulas, and 3 for Device control strings. Any other value will cause the function to return a value of 2. If this parameter is omitted, a value of 2 (raw formula) will be used
as_formula | String. Contains either a macro ID, sendkeys string, raw formula, or a device control string (determined by the ai_type parameter).
Return value
Integer. Returns 1 if the ai_priority parameter is out of range, 2 if the ai_type parameter is out of range. Returns 0 otherwise.
Usage
Use this function to enqueue processes into the PowerHome execution queue. For most purposes, the execution queue is a first in, first out structure. However, by changing the priority parameter, you can either insert items to the very top of the queue or to a priority section of the queue.

The allowed values for ai_type are in the table below:
0 | A type parameter of 0 will insert the process into the queue using standard priority. This is a first in, first out queue and is the normal mechanism for putting items in the queue.
1 | A type parameter of 1 will insert the process into the priority queue.
2 | A type parameter of 2 will insert the process at the very top of the queue.

The execution queue is a single queue with 3 logical sections. Enqueued processes are executed starting at the top of the queue. The priority parameter determines where in the queue the process is inserted. A Top priority will always go to the top of the queue. This ensures that the process will execute before any priority or normal queue items. However, if a top queue item has not yet executed and another Top priority process is enqueued, the previous Top queue process will now be second after the most recent Top queue process. Inserting as a Top priority ALWAYS inserts the process at the top of the queue. A priority queue item (type parameter = 1) will be inserted after anyTop processes and after any existing priority processes. It will be inserted before any normal priority processes. A normal process will always go to the end of the queue.

This function is useful to insert priority execution items ahead of any normally queued items.

In order to get items in the queue ahead of other items, this function typically needs to be executed in the Boolean field of either a trigger or timed event (but it doesnt have to be. It can be executed anywhere any other function can be executed). The ph_postexequeue function is just a function and doesnt "change" any PowerHome processing rules.

In normal operation, all processes (formulas, macros, etc) are added to the end of the execution queue unless the new formula, macro, etc. is executed from within a currently running formula or macro. The execution queue is serviced in the background and is FIFO (First In, First Out) and the queued processes are executed. When a web request is processed, or a timed event is fired, or a trigger is triggered, etc. the action is always placed into the execution queue. The caveat however is that timed events and triggers also have the boolean field.

The boolean formula field never goes to the execution queue and is executed immediately. It was originally intended to never perform any actual "actions" because these could corrupt the processing of events in an orderly fashion and was merely a mechanism for the user to define additional criteria for whether the action of the trigger/timed event should actually be added to the queue.

In order to get certain actions ahead of other queued actions, the ph_postexequeue() function was created.

Instead of putting items in the queue at the end, it can put it to the top or ahead of others. This works without corrupting the execution queue processing because the formula that is passed along with the ph_postexequeue function is executed from the queue (and not from the boolean)...just ahead of other queued items but still via the queue. The thing to remember is that the ph_postexequeue function is just a function like any other. It performs its intended purpose and returns a value (integer in this case). It doesnt interrupt or change any other processing.

The other thing to keep in mind is that the boolean formula is just a formula but PowerHome is expecting it to return an integer or a true/false. Any other value would confuse PowerHome. The boolean formula is never queued and always executed immediately when the timed event or trigger is fired. No direct actions should be performed in the boolean field (such as a ph_insteon function or similar...simple math or comparisons are acceptable as well as this function).

If you want to get an item ahead of other items in the queue, your only option is to do it in a formula (using the ph_postexequeue function) that is executed immediately (that is not itself queued...the boolean field). If you intend to have your Timed Event or Trigger perform its desired action via a ph_postexequeue function in the boolean field, there is really no need for the action field to be enqueued (unless you also want an additional action that would go to the end of the queue). If the action is not needed, you can set the action type to Raw Formula and set the Formula field to 0 (the formula field MUST still be a valid formula and a 0 is about as simple as it gets).

If you're performing your actual action via ph_postexequeue in the boolean field, you can ensure that your action field NEVER executes by making sure that the boolean field ultimately evaluates to a 0 (zero) or false value. This can be easily accomplished by multiplying your ph_postexequeue function by 0.

Examples
The following examples demonstrate typical syntax/usage for this function.

** SIMPLE USE
ph_postexequeue(2,0,"KITCHEN MACRO")
The above example will enqueue the KITCHEN MACRO macro to the very top of the execution queue.

** COMPLEX USE WITH TRIGGERS
postexequeue-trig


ph_postformula

ph_postformula PowerHome formula function
Description
Posts a formula to the Execution Queue.
Syntax
ph_postformula ( formula )
Argument | Description
formula | A string representing the formula to be posted.
Return value
Integer. Returns a 0. The string representing the formula will be posted to the execution queue. When the execution queue processes the postformula command, the formula contained within the string will then be evaluated.


ph_setforegroundwindow

ph_setforegroundwindow PowerHome formula function
Description
Brings the window of the specified handle to the foreground.
Syntax
ph_setforegroundwindow ( n )
Argument | Description
n | The handle of the window you wish to bring to the foreground.
Return value
Integer. Returns 0 if successful. Returns 1 if the setforegroundwindow API call fails. Returns 2 if the handle is 0. Returns 3 if the handle is currently in the foreground.


ph_switchto

ph_switchto PowerHome formula function
Description
Switches focus to the specified window.
Syntax
ph_switchto ( s, n )
Argument | Description
s | The title or classname of the window you wish to switch to.
n | An integer representing type type of argument s. Use a 0 if you wish to switch using the classname of the window. Use a 1 if you wish to switch using the title of the window.
Return value
Integer. Returns a 0 if successful. A 1 indicates an error occurred while trying to set the specified window as the foreground window. A 2 indicates that the specified window was not found. A 3 indicates that an error occurred while retrieving the handle of the current window.


ph_whileloop

ph_whileloop PowerHome formula function
Description
Evaluates a PowerHome formula repetitively.
Syntax
ph_whileloop ( formula, check )
Argument | Description
formula | A string containing the formula that you wish to have evaluated repetitively.
check | A string containing a formula that determines when the loop should exit. If this formula evaluates to a number other than 0 then the loop will exit. The loop will also exit if it evaluates to a boolean false.
Return value
Integer. Returns a 0.
Usage
Use this function to perform formula evaluations repetitively. Note that the check to exit the function is performed before the first evaluation of the formula. This means that if the check is non-zero or false, the formula will not be evaluated even 1 time. See also the ph_doloop and ph_forloop functions.


ph_addtoglobal

ph_addtoglobal PowerHome formula function
Description
Adds a numeric value to an existing global variable that currently contains a numeric value
Syntax
ph_addtoglobal ( id, value )
Argument | Description
id | String. representing the ID of the global variable.
value | Long. The double value to add to the global variable.
Return value
Double. Returns the new value of the global variable. Returns 0 if an error occurs.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_addglobal("MOTIONCOUNT",1)
• ph_addglobal("LOOPCNT", [LOCAL1]) {NOTE: the LOCAL variable MUST contain a numeric value or a syntax error will occur. See next line for better syntax.}
• ph_addglobal("LOOPCNT", ph_getvar_n(1,1)) {ph_getvar converts the contents of LOCAL1 value into a numeric value}


ph_addtovar

ph_addtovar PowerHome formula function
Description
Adds a value to a system variable
Syntax
ph_addtovar ( type, id, value )
Argument | Description
type | Integer. The type of the system variable. 1 denotes a local variable, 2 denotes a temp variable, and 3 denotes a system global variable.
id | Integer. The number of the system variable. 1 thru 10 is valid for local and temp variables. 1 thru 100 is valid for system global variables.
value | Long. A positive or negative double value that you want the system variable adjusted by.
Return value
Double. Returns the value of the system variable after it has been adjusted by value.
NOTE: This function should ONLY be used when it is known that the system variable contains numeric data.
Examples
The following examples demonstrate typical syntax/usage for this function.
• To Add "15" to LOCAL3 >>> ph_addtovar(1,3,15)
• To Add "65" to TEMP5 >>> ph_addtovar(2,5,65)
• To Add "210" to GLOBAL2 >>> ph_addtovar(3,2,210)


ph_clearvars

ph_clearvars PowerHome formula function
Description
Clears a range of local, temp, and global system variables.
Syntax
ph_clearvars ( local, temp, global )
Argument | Description
local | Number representing the starting point of [LOCAL?] variables to be cleared. Use 0 to not clear any [LOCAL?] variables.
temp | Number representing the starting point of [TEMP?] variables to be cleared. Use 0 to not clear any [TEMP?] variables.
global | Number representing the starting point of [GLOBAL?] variables to be cleared. Use 0 to not clear any [GLOBAL?] variables.
Return value
Integer. Returns a 0.
Usage
For each of the three parameters, use a positive number to clear from this variable up to the max. For example: placing a 3 in the local parameter will clear [LOCAL3] thru [LOCAL10]. Use a negative number to clear from the minimum variable to the specified number. For example: placing a - 3 in the local parameter will clear[LOCAL1] thru [LOCAL3]. The example ph_clearvars(7, - 4, 0) would clear [LOCAL7] thru [LOCAL10], clear [TEMP1] thru [TEMP4], and would not change [GLOBAL1] thru [GLOBAL20].
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_clearvars(0,3,-5)
Causes the LOCAL vars to be untouched, TEMP 3-10 to be cleared, GLOBAL 1-5 cleared
• ph_clearvars(-1, [LOCAL1],0)
Causes LOCALS to be unchanged, TEMPS cleared according to contents of LOCAL1, Globals unchanged.


ph_concatglobal

ph_concatglobal PowerHome formula function
Description
Concatenates a string value to an existing global variable.
Syntax
ph_concatglobal ( id, string )
Argument | Description
id | A string representing the ID of the global variable.
string | The string to concatenate to the global variable.
Return value
String. Returns the new value of the global variable. Returns the empty string if an error occurs. If the global variable currently contains a numeric value, it will be treated as a string and have the new string concatenated to it.


ph_concatvar

ph_concatvar PowerHome formula function
Description
Concatenates a string to a system variable.
Syntax
ph_concatvar ( type, id, string )
Argument | Description
type | The type of the system variable. 1 denotes a local variable, 2 denotes a temp variable, and 3 denotes a global variable.
id | The number of the system variable. 1 thru 10 are valid for local and temp variables. 1 thru 20 are valid for global variables.
string | The string that you would like to concatenate to the system variable.
Return value
String. Returns the value of the system variable after the string has been concatenated to it.


ph_getglobal_n

ph_getglobal_n PowerHome formula function
Description
Retrieves a global variable and returns the data as a number.
Syntax
ph_getglobal_n ( id )
Argument | Description
id | String identifying the global variable you wish to retrieve. NOTE: Should be all uppercase.
Return value
Double. The data stored within the global variable will be returned as a double. You should only use this function if you know that the data stored within the global variable can be properly converted to a double.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_getglobal_n ("MOTION_COUNT")


ph_getglobal_s

ph_getglobal_s PowerHome formula function
Description
Retrieves a global variable and returns the data as a string.
Syntax
ph_getglobal_s ( globalname )
Argument | Description
globalname | String identifying the global variable you wish to retrieve.
Return value
String. The data stored within the global variable will be returned as a string. Data within global variables is always stored in a string format so this function is safe to use with all data within a global variable.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_getglobal_s("CAMERA_NAME") --> sample use: if(ph_getglobal_s("ALERT_MAIL1")="1",1,0)


ph_getinputret

ph_getinputret PowerHome formula function
Description
Retrieves the data stored within the INPUTRET system variable.
Syntax
ph_getinputret ( )
Argument Description
Return value
String. Returns the data currently stored within the system variable INPUTRET.


ph_getmbret

ph_getmbret PowerHome formula function
Description
Retrieves the data stored within the MBRET system variable.
Syntax
ph_getmbret ( )
Argument | Description
Return value
Integer. Returns the data currently stored within the system variable MBRET.


ph_getsystemvar

ph_getsystemvar PowerHome formula function
Description
Retrieves a system variable and returns the value as a string.
Syntax
ph_getsystemvar ( s )
Argument | Description
s | A string identifying the system variable you wish to retrieve.
Return value
String. The data stored within the system variable will be returned as a string. All system variables are available except for the expanded multi-x variables. The standard X10P0 thru X10P19 and X10P0TIME thru X10P9TIME are available and return the multi-x values stored within the Global multi-x buffer. If you need to retrieve a housecode specific multi-x value, use the ph_multix function.


ph_gettimeout

ph_gettimeout PowerHome formula function
Description
Retrieves the value stored within the system variable TIMEOUT
Syntax
ph_gettimeout ( )
Argument Description
Return value
Integer. The data stored within the system variable TIMEOUT will be returned as an integer. This variable represents the amount of seconds that a Message Box or Input Box macro command will wait before timing out. A value of 0 means no timeout.


ph_getvar_n

ph_getvar_n PowerHome formula function
Description
Retrieves the specified system variable as a number.
Syntax
ph_getvar_n ( type, num )
Argument | Description
type | Integer. The type of system variable you wish to retrieve. Valid values are 1, 2, 3, and 4. A 1 specifies that you wish to retrieve LOCAL variables (the same as system variables LOCAL1 thru LOCAL10), a 2 specifies that you wish to retrieve TEMP variables (the same as system variables TEMP1 thru TEMP10), and a 3 specifies that you wish to retrieve GLOBAL variables (the same as system variables GLOBAL1 thru GLOBAL20). A value of 4 is a special case and represents data that is only available during the execution of Analog I/O formulas (the Calculated to Raw and Raw to Calculated formulas). Use a num value of 1 to return raw value as a number. Use a num value of 2 to return the calc value of the Analog device as a number. This would look like ph_getvar_n(4,1) and ph_getvar_n(4,2).
num | Integer. The number of the specified system variable type you wish to retrieve. To retrieve system variable TEMP7 use ph_getvar_n(2,7).
Return value
Double. The data stored within the specified system variable returned as a double. You should be certain that the system variable contains data that can be properly converted to a numeric value.
Examples
The following examples demonstrate typical syntax/ usage for this function.
. ph_getvar_n (1,2) --> get the value in LOCAL2. The result is returned as a number, eg --> If LOCAL2 contained the string "42.65" the value returned would be the number 42.65.
. ph_getvar_n (2,4) --> get the value in TEMP4.


ph_getvar_s

ph_getvar_s PowerHome formula function
Description
Retrieves the specified system variable as a string.
Syntax
ph_getvar_s ( type, num )
Argument | Description
type | Integer. The type of system variable you wish to retrieve. Valid values are 1, 2, 3, and 4. A 1 specifies that you wish to retrieve LOCAL variables (the same as system variables LOCAL1 thru LOCAL10), a 2 specifies that you wish to retrieve TEMP variables (the same as system variables TEMP1 thru TEMP10), and a 3 specifies that you wish to retrieve GLOBAL variables (the same as system variables GLOBAL1 thru GLOBAL20). A value of 4 is a special case and represents data that is only available during the execution of Analog I/O formulas (the Calculated to Raw and Raw to Calculated formulas). Use a num value of 1 to return the raw value as a string. Use a num value of 2 to return the calc value of the Analog device as a string. This would look like ph_getvar_s(4,1) and ph_getvar_s(4,2).
num | Integer. The number of the specified system variable type you wish to retrieve. To retrieve system variable TEMP7 use ph_getvar_s(2,7).
Return value
String. The data stored within the specified system variable returned as a string. The default storage format for the LOCAL, TEMP, and GLOBAL system variables is as a string so this function is safe to use with any type of data.
Examples
The following examples demonstrate typical syntax/ usage for this function.
. ph_getvar_s (1,2) --> get the contents of LOCAL2. The result is returned as a string.
. ph_getvar_s (2,4) --> get the contents of TEMP4. The result is returned as a string.


ph_getx10level

ph_getx10level PowerHome formula function
Description
Retrieves the current level (dim / bright) value of the specifed X10 ID.
Syntax
ph_getx10level ( s )
Argument | Description
s | A string representing the ID of the X10 Device from which you wish to retrieve the level.
Return value
Double. Returns the level associated with the specified X10 Device ID that PowerHome currently has stored. This is the equivalent of the system variable X10LEVEL## where ## is the house/unit code of the X10 device.


ph_getx10stat

ph_getx10stat PowerHome formula function
Description
Retrieves the current status of the specifed X10 Device ID.
Syntax
ph_getx10stat ( s )
Argument | Description
s | A string representing the X10 Device ID from which you wish to retrieve the level.
Return value
Integer. Returns the status associated with the specified X10 Device ID that PowerHome currently has stored. Valid values are 0 for Unknown, 1 for Off, and 2 for On. This is the equivalent of the system variable X10STAT## where ## is the house/unit code of the X10 device.


ph_multix

ph_multix PowerHome formula function
Description
Gets values from a previous incoming X10 buffer.
Syntax
ph_multix ( s, start, length )
Argument | Description
s | A string identifying the buffer you wish to access. Use "" for the global buffer. Use "EXT" for the extended buffer. Use "A" for housecode A, etc.
start | An integer identifying the start of the command you wish returned. A value of 1 will return commands starting with the most recent command. A value of 20 will return starting with the oldest command.
length | An integer identifying the number of commands to return.
Return value
String. The returned commands in the format of housecode, unitcode, and command. If the last command was housecode K, unitcode 5, command on, the returned value would be "K0502". If the length is greater than 1, then the commands are returned one after the other as a single string. For the extended buffer, the returned data is in the form of unit and data. For example, if the unit is 145 and the data is 32, the returned value would be "145032".


ph_retrievevars

ph_retrievevars PowerHome formula function
Description
Retrieves and/or deletes a copy of variables that were previously stored in the database using the ph_storevars function.
Syntax
ph_retrievevars ( id, type )
Argument | Description
id | Long. The ID number you originally used in the ph_storevars function to store a copy of the variables.
type | Integer. The type of retrieval. Use 0 to retrieve the stored variables into the current variable set and delete the stored variables from the database. Use 1 to retrieve the stored variables into the current variable set but do not delete them from the database (they can be retrieved again). Use 2 to delete the stored variable set without copying to the current variable set.
Return value
Integer. The result of the retrieve variables operation. 0 is returned for success or a type value out of range. 1 is returned if there is an error retrieving the variables with the specified ID. 2 is returned if there is an error deleting the stored variables in the database.
Usage
Use this function combined with the ph_storevars function to store and later retrieve a snapshot of the current variable set.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_retrievevars(322,0)
The above example will retrieve a copy of variables previously stored under the ID 322 and overwrite the current variable set. It will then delete the stored variable set under ID 322.


ph_returnallvars

ph_returnallvars PowerHome formula function
Description
Returns a string containing the values of the requested LOCAL, TEMP, and SYSTEM variables within the current execution space
Syntax
ph_returnallvars ( )
ph_returnallvars ( ai_flags )
Argument | Description
ai_flags | Integer (Optional). A flags parameter representing which group of variables you would like to return. Add the values together to get the desired result. A value of 2 will return the LOCAL variables. A value of 4 will return the TEMP variables. A value of 8 will return the SYSTEM variables. Add a value of 1 to the total to have each of the LOCAL and TEMP variables trimmed to a max of 40 characters. If this parameter is omitted, a value of 15 will be used to return all 3 sets of variables with the LOCAL and TEMP variables each trimmed to a max of 40 characters
Return value
String. Returns a string containing all of the values of the requested LOCAL, TEMP, and SYSTEM variables
Usage
Use this function to quickly snapshot the internal variables within the current execution space. Very useful for debugging and for verifying output for macros and triggers.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_returnallvars() - A sample return from this function could look like this:

| LOCAL1 = 0
| LOCAL2 = 0
| LOCAL3 = 0
| LOCAL4 =
| LOCAL5 =
| LOCAL6 =
| LOCAL7 =
| LOCAL8 =
| LOCAL9 =
| LOCAL10 =
| TEMP1 =
| TEMP2 =
| TEMP3 =
| TEMP4 =
| TEMP5 =
| TEMP6 =
| TEMP7 =
| TEMP8 =
| TEMP9 =
| TEMP10 =
| MACROID =
| MACROROW = 0
| MACRORET =
| MACROJUMPS = 0
| SUBMACROPATH =
| SUBMACROCNT = 0
| TRIGGERID =
| FORMULAID =
| TIMEDEVENTID =
| CCTABID =
| CCOBJID =
| ANALOGID =
| ZWAVEID =
| ANALOGRAW = 0
| OANALOGRAW = 0
| ANALOGCALC =
| FORECOLOR = 0
| BACKCOLOR = 0
| MBTYPE = 0
| MBRET = 0
| MBMSG =
| INPUTRET =
| INPUTMSG =
| CCOBJX = 0
| CCOBJY = 0
| MTRET = 0
| ERRNUM = 0
| ERRTEXT =


ph_setglobal_a

ph_setglobal_a PowerHome formula function
Description
Sets the value of a global variable with any type of data.
Syntax
ph_setglobal_a ( id, value )
Argument | Description
id | A string identifying the ID of the global variable to set.
value | Data of type any which you would like assigned to the specified global variable.
Return value
Integer. Returns a 0 if successful and a 1 if an error occurred while updating the global variable. You can pass any data type as the a argument.

All global variables are stored internally as strings and will be converted. Numeric values will be converted as is. Date values will have a mask of 'yyyy-mm-dd' applied. Datetime values will have a mask of 'yyyy-mm-dd hh:mm:ss.fff' applied. String values must be contained in quotes and go over without conversion.

Any other data type will just be converted as is to a string and then stored.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_setglobal_a("ALERT_SMS2",0)
• ph_setglobal_a("MODE","Heat")


ph_setglobal_s

ph_setglobal_s PowerHome formula function
Description
Assigns a string to the specified global variable.
Syntax
ph_setglobal_s ( id, value )
Argument | Description
id | A string identifying the ID of the global variable to set.
value | A string which you would like assigned to the global variable.
Return value
Integer. Returns a 0 if successful and a 1 if an error occurred while updating the global variable.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_setglobal_s("ALERT_SMS2","0")
• ph_setglobal_s("MODE","Heat")


ph_setinputret

ph_setinputret PowerHome formula function
Description
Sets the value of the INPUTRET system variable.
Syntax
ph_setinputret ( s )
Argument | Description
s | The string data you would like stored within the INPUTRET system variable.
Return value
Integer. Returns a 0.


ph_setlocals

ph_setlocals PowerHome formula function
Description
Allows for the quick initialization of local variables [LOCAL1] thru [LOCAL5]
Syntax
ph_setlocals ( local1, local2, local3, local4, local5 )
Argument | Description
local1 | Any. The value to assign to [LOCAL1]. Data can be of any standard type.
local2 | Any. The value to assign to [LOCAL2]. Data can be of any standard type.
local3 | Any. The value to assign to [LOCAL3]. Data can be of any standard type.
local4 | Any. The value to assign to [LOCAL4]. Data can be of any standard type.
local5 | Any. The value to assign to [LOCAL5]. Data can be of any standard type.
Return value
Integer. Returns 0.
Usage
Use this function to rapidly set the first 5 LOCAL variables. If you only want to set some of the LOCAL variables, supply a string containing a single space for the variables you wish to leave unchanged.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_setlocals(35,"Test"," ",2014-06-19,321.25)
The above example will set LOCAL1, LOCAL2, LOCAL4, and LOCAL5 to the specified number, string, date, and decimal respectively. LOCAL3 will not be changed since it is set to a single space.


ph_setsystemvar

ph_setsystemvar PowerHome formula function
Description
Sets the value of a system variable.
Syntax
ph_setsystemvar ( varid, value )
Argument | Description
varid | String identifying the system variable you would like to modify.
value | String which you would like assigned to the system variable.
Return value
Integer. Returns a 0 if successful and a 1 if the system variable is undefined. Not all system variables can be modified by the user. Examples of non-modifiable system variables are the multi-x X10P0 thru X10P19 system variables as well as MBRET, DIALUPIP, etc.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_setsystemvar("TEMP1","DWN ROOM")
• ph_setsystemvar("TEMP2","19")
• ph_setsystemvar("LOCAL1", ph_readfile("C:\powerhome\findMyPhone.txt"))
NOTE: Because the contents of the file is 'text' no parentheses' are required. Had they been used, then the value put into LOCAL1 would have been the file path/name itself.


ph_settemps

ph_settemps PowerHome formula function
Description
Allows for the quick initialization of temp variables [TEMP1] thru [TEMP5]
Syntax
ph_settemps ( temp1, temp2, temp3, temp4, temp5 )
Argument | Description
temp1 | Any. The value to assign to [TEMP1]. Data can be of any standard type.
temp2 | Any. The value to assign to [TEMP2]. Data can be of any standard type.
temp3 | Any. The value to assign to [TEMP3]. Data can be of any standard type.
temp4 | Any. The value to assign to [TEMP4]. Data can be of any standard type.
temp5 | Any. The value to assign to [TEMP5]. Data can be of any standard type.
Return value
Integer. Returns 0.
Usage
Use this function to rapidly set the first 5 TEMP variables. If you only want to set some of the TEMP variables, supply a string containing a single space for the variables you wish to leave unchanged.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_settemps(35,"Test"," ",2014-06-19,321.25)
The above example will set TEMP1, TEMP2, TEMP4, and TEMP5 to the specified number, string, date, and decimal respectively. TEMP3 will not be changed since it is set to a single space.


ph_settimeout

ph_settimeout PowerHome formula function
Description
Sets the value of the TIMEOUT system variable.
Syntax
ph_settimeout ( n )
Argument | Description
n | An integer representing the number of seconds the Message box and Input box macro commands will wait before automatically timing out.
Return value
Integer. Returns a 0. This function sets the TIMEOUT system variable.


ph_setvar_a

ph_setvar_a PowerHome formula function
Description
Sets the value of a LOCAL, TEMP, or GLOBAL system variable with any type of data.
Syntax
ph_setvar_a ( n, n, a )
Argument | Description
n | The type of system variable you would like to set. Valid values are 1 for LOCAL variables, 2 for TEMP variables, and 3 for GLOBAL variables.
n | The number of the appropriate system variable. Valid values are 1 - 10 for LOCAL and TEMP variables and 1 - 20 for GLOBAL variables.
a | Any type of data you would like to have stored.
Return value
Integer. Returns a 0 if successful and a 1 the system variable is undefined. You can pass any data type as the a argument. All LOCAL, TEMP, and GLOBAL variables are stored internally as strings and will be converted. Numeric values will be converted as is. Date values will have a mask of 'yyyy-mm-dd' applied. Datetime values will have a mask of 'yyyy-mm-dd hh:mm:ss.fff' applied. Strings go over without conversion. Any other data type will just be converted as is to a string and then stored.


ph_setvar_s

ph_setvar_s PowerHome formula function
Description
Sets the value of a LOCAL, TEMP, or GLOBAL system variable with a string value.
Syntax
ph_setvar_s ( n, n, s )
Argument | Description
n | The type of system variable you would like to set. Valid values are 1 for LOCAL variables, 2 for TEMP variables, and 3 for GLOBAL variables.
n | The number of the appropriate system variable. Valid values are 1 - 10 for LOCAL and TEMP variables and 1 - 20 for GLOBAL variables.
s | A string you would like stored within the specified variable.
Return value
Integer. Returns a 0 if successful and a 1 the system variable is undefined.


ph_storevars

ph_storevars PowerHome formula function
Description
Store a copy of the current variable set in the PowerHome database.
Syntax
ph_storevars ( id )
Argument | Description
id | Long. A number representing the stored variable set that will be later retrieved with ph_retrievevars.
Return value
Long. Returns the ID that the variable set was stored under. Returns - 1 if the first step of the store operation fails. Returns - 2 if the second step of the store operation fails.
Usage
Use this function to take a snapshot of the current variable set and save them in the PowerHome database. Use the ph_retrievevars function to retrieve and/or delete a stored variable set. Care should be taken to not store too many copies or copies that contain large amounts of data as this can make your database grow to unwieldly proportions.

Use 0 for the id parameter to have the function automatically assign the ID for the stored variable set. The dynamically assigned ID will be returned from the function and should be stored for later retrieval.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_storevars(322)
The above example takes a snapshot of the current variable set and stores it as ID 322. Use ph_retrievevars(322, 0) to retrieve the stored variables into the current variable set and delete the stored copy from the database.


ph_devicerefreshstat

ph_devicerefreshstat PowerHome formula function
Description
Queries the PowerHome database and refreshes the Device status screen.
Syntax
ph_devicerefreshstat ( )
Return value
Integer. Returns a 0.
Usage
Identical to the ph_x10refreshstat function.


ph_insteonrawext

ph_insteonrawext PowerHome formula function
Description
This function allows the sending of raw Insteon extended commands.
Syntax
ph_insteonrawext ( ctlr, address, flags, cmd1, cmd2, data )
Argument | Description
ctlr | String. The controller ID for the Insteon controller.
address | String. The address of the device to send commands to.
flags | Integer. The Insteon flags to send.
cmd1 | Integer. The Insteon CMD1 value.
cmd2 | Integer. The Insteon CMD2 value.
data | String. The extended Insteon data to send. This should be in hexadecimal format with a single space between each byte (two hex characters). Insteon extended data is 14 bytes of data. If you leave this field blank or have less than 14 bytes of data then this function will pad the extended data with 00 byte characters. If the 14th byte contains 00, then PowerHome will automatically calculate the I2CS checksum and apply it to the extended data.
Return value
Integer. A value indicating the success of failure of the operation.
Usage
Use this function to send extended commands to an Insteon address (the device/address does not need to exist as an Insteon device in the PowerHome database).
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_insteonrawext("PLM","34.AB.7C",h2d("1F"),h2d("2E"),0,"03 00")
The above example sends an extended request to an Insteon keypadlic to retrieve its extended settings.


ph_insteonwithret1

ph_insteonwithret1 PowerHome formula function
Description
Send a standard length Insteon command and waits for the return value. The value returned will be the CMD2 value followed by the extended return data if it exists.
Syntax
ph_insteonwithret1 ( id, cmd1, cmd2 )
Argument | Description
id | String. The ID of the Insteon device to send commands to.
cmd1 | Integer. The command 1 value. Use standard 0 to 255 for Insteon Direct commands. Add 1000 to the cmd1 value to send Group Cleanup commands.
cmd2 | Integer. The command 2 value.
Return value
String. Returns the CMD2 value and extended return data (if it exists).
Usage
This function is nearly identical to the ph_insteonwithret function except it is also capable of returning extended data. Some Insteon standard commands return an extended data message so this function will be able to return this data whereas the ph_insteonwithret command ONLY returns the CMD2 value.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_insteonwithret ("MID CHANDELIER",3,2)
The above example sends a standard Device Text String Request. This particular Insteon command will respond with an extended data message which will be returned along with CMD2 as a string.


ph_insteonwithretext

ph_insteonwithretext PowerHome formula function
Description
This function sends an extended Insteon command to an Insteon device and waits for a return. The returned CMD2 value is returned from this function.
Syntax
ph_insteonwithretext ( id, cmd1, cmd2, extdata )
Argument | Description
id | String. The ID of the Insteon device to send extended commands to.
cmd1 | Integer. The Insteon CMD1 value to send.
cmd2 | Integer. The Insteon CMD2 value to send.
extdata | String. The extended data to send. This data must be in hexadecimal format (up to 14 bytes) with a single space between each byte (2 hex digits). If less than 14 bytes are included, PowerHome will pad the remaining bytes with 00 characters. If the 14th byte is 00, then PowerHome will automatically calculate and include the I2CS checksum.
Return value
Integer. Waits for the Insteon command to return and then returns the CMD2 value.
Usage
Use this function to send extended Insteon commands and retrieve the result (CMD2) of the command.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_insteonwithretext("KITCHENLIGHT",h2d("2E"),0,"03 00")


ph_insteonwithretext1

ph_insteonwithretext1 PowerHome formula function
Description
This function sends an extended Insteon command to an Insteon device and waits for a return. The returned CMD2 value as well as any returned extended data will be returned from this function.
Syntax
ph_insteonwithretext1 ( id, cmd1, cmd2, extdata )
Argument | Description
id | String. The ID of the Insteon device to send extended commands to.
cmd1 | Integer. The Insteon CMD1 value to send.
cmd2 | Integer. The Insteon CMD2 value to send.
extdata | String. The extended data to send. This data must be in hexadecimal format (up to 14 bytes) with a single space between each byte (2 hex digits). If less than 14 bytes are included, PowerHome will pad the remaining bytes with 00 characters. If the 14th byte is 00, then PowerHome will automatically calculate and include the I2CS checksum.
Return value
String. Waits for the Insteon command to process/return and then returns the CMD2 value followed by any extended data. The data is returned as a string in hexadecimal format.
Usage
Use this function to send extended Insteon commands and retrieve the result (CMD2 and extended data) of the command.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_insteonwithretext1("KITCHENLIGHT",h2d("2E"),0,"03 00")


Blank

ph_convertir PowerHome formula function
Description
Converts raw IR code strings to other IR formats.
Syntax
ph_convertir ( convertto, code )
Argument | Description
convertto | String. The type of IR code to convert to.
code | String. The IR code to convert.
Return value
String. Returns the converted IR code in the specified format or an error message.
Usage
Valid convertto formats are:

  • "pronto"
  • "cir"
  • "howtek"
  • "rr2"
  • "slinke"
  • "uirtraw"
  • "uirtstruct"
  • "rr3"
  • "gc"

    You do not need to specify the input code format as the system will autodetermine it based upon the code itself. If the function fails, it will return a string detailing the error. All error strings start with "***ERROR:"
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    ph_convertir("pronto","<rr2>F61L847042AC08191923X43FBF7EF7BDFBF7FEF7BFF7BFF7BDEC43FBF7EF7BDFBF7FEF7BFF7BFF7BDEC00P45BBR02")
    The above call will convert the RedRat2 IR string into the Pronto format. The result of this conversion is: <pronto>0000 0065 0022 0022 015E 00B0 0015 0015 0015 0015 0015 0015 0015 0042 0015 0015 0015 0042 0015 0015 0015 0042 0015 0042 0015 0042 0015 0042 0015 0015 0015 0042 0015 0015 0015 0042 0015 0015 0015 0015 0015 0015 0015 0042 0015 0042 0015 0042 0015 0015 0015 0015 0015 0015 0015 0042 0015 0042 0015 0015 0015 0015 0015 0015 0015 0042 0015 0042 0015 0042 0015 05C0 015E 00B0 0015 0015 0015 0015 0015 0015 0015 0042 0015 0015 0015 0042 0015 0015 0015 0042 0015 0042 0015 0042 0015 0042 0015 0015 0015 0042 0015 0015 0015 0042 0015 0015 0015 0015 0015 0015 0015 0042 0015 0042 0015 0042 0015 0015 0015 0015 0015 0015 0015 0042 0015 0042 0015 0015 0015 0015 0015 0015 0015 0042 0015 0042 0015 0042 0015 05C0<repeat>1<zone>1


ph_playlist

ph_playlist PowerHome formula function
Description
Programs a playlist into a CD changer.
Syntax
ph_playlist ( id, mode )
Argument | Description
id | The ID of the playlist you would like to have programmed.
mode | The mode to use when programming the playlist. A 0 will send the playlist unaltered. A 1 will cause the playlist to first be randomized.
Return value
Integer. Returns a 0 if successful. Other return values are: 1 - an error occurred while generating the SQL to retrieve the commands for the PLAYPLAYLIST macro. 2 - an error occurred while creating the datastore to retrieve the commands for the PLAYPLAYLIST macro. 3 - No rows are defined for the PLAYPLAYLIST macro. 4 - an error occurred while generating the SQL to retrieve the tracks to be programmed for the playlist. 5 - an error occurred while creating the datastore to retrieve the tracks to be programmed. 6 - No tracks exist in the playlist.


ph_colorcalc

ph_colorcalc PowerHome formula function
Description
Calculates an RGB color value for a supplied value based upon min and max color value ranges and min and max value ranges for the supplied value
Syntax
ph_colorcalc ( al_colormin, al_colormax, al_minval, al_maxval, al_value )
Argument | Description
al_colormin | Long. An RGB color value representing the color to be used for the supplied al_value = al_minval
al_colormax | Long. An RGB color value representing the color to be used for the supplied al_value = al_maxval
al_minval | Long. The minimum value for the supplied al_value parameter
al_maxval | Long. The maximum value for the supplied al_value parameter
al_value | Long. The value upon which the returned calculated color will be based
Return value
Long. Returns a calculated RGB color value. If the al_value parameter is equal to the al_minval parameter then al_colormin will be returned. If al_value is equal to al_maxval then the al_colormax value will be returned. Any other al_value in between al_minval and al_maxval will return a calculated color that lies on the spectrum of colors in between al_colormin and al_colormax.
Usage
Use this function to dynamically create RGB color values based upon a supplied value (al_value) within a min/max range (al_minval and al_maxval). This function is useful to set the Device Status screen background color for Analog I/O and Zwave device types. If you use this in the context of a light device that has a min value of 0 representing "off" and a max value of 100 representing full "on" and the al_colormin value is dark grey and the al_colormax value is bright yellow, al_value values between 0 and 100 will range between dark grey and bright yellow with an al_value = 50 being in between the dark grey and yellow values.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_colorcalc(rgb(50,50,50),rgb(255,255,0),0,100,75) - Returns a value of 838860 which is equivalent to rgb(204,204,12)


ph_convertimage

ph_convertimage PowerHome formula function
Description
Converts a graphic file from one format to another and/or resizes the graphic.
Syntax
ph_convertimage ( source, dest, width, height )
Argument | Description
source | String. The path and filename of the graphic file to convert.
dest | String. The path and filename to save the converted graphic to.
width | Long. The new width for the saved graphic file.
height | Long. The new height for the saved graphic file.
Return value
Integer. Returns -1 if the source graphic type cannot be determined. Returns -2 if the dest graphic type is not supported. Returns 0 otherwise.
Usage
The graphic type of the source file is determined first by the data in the file and then by the filename. The graphic type to save as is determined solely by the dest filename. If you don't wish to resize the graphic, then use a value of 0 for both the width and height. Using width and height values greater than 0 will cause the saved graphic to be resized. Supported save filetypes are BMP, JPEG, PNG, TIFF, WBMP, and GIF.


ph_createtimedevent

ph_createtimedevent PowerHome formula function
Description
Create a timed event.
Syntax
ph_createtimedevent ( type, action, datetime )
Argument | Description
type | Integer representing the action type of the timed event. A 0 will create a macro timed event. A 1 will create a Send Keys timed event. A 2 will create a Formula timed event.
action | String denoting the action associated with the timed event. If a macro type of timed event, use the macro id. If a Send Keys type of timed event, then a formula evaluating to a valid Send Keys string. If a Formula type of timed event, then any valid formula.
datetime | Datetime value for when the timed event will execute.
Return value
Integer. Returns a 0 if the timed event was successfully created. Otherwise a value equivalent to the SQL error when attempting to insert into the timed event table.
Examples
The following examples demonstrate typical syntax/usage for this function. NOTE: the TimedEvent created will have a generic system id. If a labeled ID is desired see the "ph_createtimedevent1()" function.
CREATE AN EVENT 30 MINUTES FROM NOW
• ph_createtimedevent(2,"ph_insteon('DWN ROOM',ifastoff,0)",ph_relativedatetime(today(),30))

CREATE AN EVENT 45 SECONDS FROM NOW
• ph_createtimedevent(0,"LIGHT_OFF",datetime(today(),ph_relativetime(now(),45)))

TURN ON CHRISTMAS LIGHTS AT 7:30 AM CHRISTMAS MORNING
• ph_createtimedevent(0,"XMAS_LITES",2013-12-25 07:30:00)


ph_createtimedevent1

ph_createtimedevent1 PowerHome formula function
Description
Create a timed event.
Syntax
ph_createtimedevent1 ( id, active, timing, freq, offset, offsetamt, reftime, type, action, boolean )
Argument | Description
id | String. The ID you want to use for the Timed Event. Use a blank value to have PowerHome automatically create an ID.
active | Integer. Use 0 for the Timed Event to be set inactive. Use 1 for the Timed Event to be active.
timing | Integer. The Timing value for the Timed Event. Use 0 for Exact, 1 for Sunrise, 2 for Sunset, 3 for Dawn, 4 for Dusk.
freq | Long. The frequency the Timed Event will occur in minutes. Use 0 for a One Shot. 1440 is the equivalent to Daily.
offset | Integer. The type off offset to apply to the reftime. Use 0 for None, 1 for Absolute +, 2 for Absolute -, 3 for Random +, 4 for Random -, 5 for Random +/-
offsetamt | Integer. The offset amount in minutes to apply to the reftime depending upon the offset type.
reftime | DateTime. A datetime value for when the timed event will execute.
type | Integer representing the action type of the timed event. A 0 will create a macro timed event. A 1 will create a Send Keys timed event. A 2 will create a Formula timed event.
action | String denoting the action associated with the timed event. If a macro type of timed event, use the macro id. If a Send Keys type of timed event, then a formula evaluating to a valid Send Keys string. If a Formula type of timed event, then any valid formula.
boolean | String representing the Boolean formula for the Timed Event.
Return value
String. Returns the ID of the Timed Event that was created. Otherwise a string representing the error is returned.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_createtimedevent1 ("ROOM OFF",1,1,0,2,20,TODAY(),2, "ph_insteon('CEILING_LIGHT',ifastoff,0)
• ph_createtimedevent1 ("MID CHAN OFF",1,1,0,1,15,TODAY(),2, "ph_insteon('MID CHANDELIER',ifastoff,0)+ph_insteon('MID CHANDELIER-R',ifastoff,0)","1")
/*Send turnoff 15 min after Sunrise*/
• ph_createtimedevent1 ("SOFA OFF",1,0,0,1,15,ph_relativedatetime(today(),30),2, "ph_insteon('SOFA',ifastoff,0)","1")
/*Send turnoff in 15 min */


Blank

ph_decrypt PowerHome formula function
Description
This function will decrypt strings that were previously encrypted using the ph_encrypt function
Syntax
ph_decrypt ( data, key )
Argument | Description
data | String. The encrypted string you wish to decrypt.
key | String. The key to use for decryption. This key must match the key that was used to encrypt the data originally.
Return value
String. Returns the decrypted string in standard ASCII format.
Usage
The ph_encrypt and ph_decrypt functions use the Microsoft Cryptograghy library.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_decrypt("C2DB941D6A1754A02778D80C9C91","abc123") The output of this function will be the originally encrypted string: "This is a test". The "abc123" is the key/password that used to orignally encrypt the string.


ph_deletetimedevent

ph_deletetimedevent PowerHome formula function
Description
Delete a timed event.
Syntax
ph_deletetimedevent ( )
ph_deletetimedevent ( as_id )
Argument | Description
as_id | String (Optional). A valid Timed event ID. If this parameter is omitted, then the system variable TIMEDEVENT will be used for ID
Return value
Integer. Returns 0 if successful. Returns 1 if an error occurs
Usage
Use this function to programmatically delete timed events from the PowerHome system.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_deletetimedevent("SUNRISE")


ph_encrypt

ph_encrypt PowerHome formula function
Description
This function will encrypt strings using a user specified key.
Syntax
ph_encrypt ( data, key )
Argument | Description
data | String. The data you would like to encrypt.
key | String. The key to use for encrypting the data. This can be a pass phrase or similar. In order to decrypt, you must use the same key that was used for encryption.
Return value
String. Returns the encrypted string in hex format.
Usage
The ph_encrypt and ph_decrypt functions use the Microsoft Cryptograghy library.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_encrypt("This is a test","abc123") The output of this function will be the encrypted string: "C2DB941D6A1754A02778D80C9C91". The "abc123" is the key/password that used to encrypt the string.


ph_evalscript

ph_evalscript PowerHome formula function
Description
Evaluates a single WSH (Windows Script Host) function.
Syntax
ph_evalscript ( n, s, s )
Argument | Description
n | Timeout. Specifies the time in milliseconds after which the user will be presented with an option to continue or discontinue execution of the script. A value of -1 means the script will never timeout. A value of 0 will fire the timeout event when it is detected that the script is hung.
s | Additional code to be added to the Windows Script Host control. To not add code, pass in a blank string.
s | The function to execute.
Return value
String. Returns the output of the called function or the text of an error.


ph_executescript

ph_executescript PowerHome formula function
Description
Executes a single WSH (Windows Script Host) statement.
Syntax
ph_executescript ( n, s, s )
Argument | Description
n | Timeout. Specifies the time in milliseconds after which the user will be presented with an option to continue or discontinue execution of the script. A value of -1 means the script will never timeout. A value of 0 will fire the timeout event when it is detected that the script is hung.
s | Additional code to be added to the Windows Script Host control. To not add code, pass in a blank string.
s | The statement to execute. The statement can be a function, but the result will not be returned
Return value
Integer. 0 is returned upon success, 2 with an Initialize error, 3 with an AddCode error, and 4 with execute error.


ph_formula

ph_formula PowerHome formula function
Description
Evaluates a formula and returns the result.
Syntax
ph_formula ( formula )
Argument | Description
formula | A string representing the formula to be evaluated.
Return value
String. Returns the evaluation of the formula as a string.


ph_formulabtn

ph_formulabtn PowerHome formula function
Description
Executes a formula from the "Formulas" table.
Syntax
ph_formulabtn ( id )
Argument | Description
id | The ID of the formula you wish to execute.
Return value
Integer. Returns a 2 if the ID is not found. Returns a 0 if the result of the formula is not output as a sendkeys. If the formula result is output as sendkeys, the result from the sendkeys function is returned.
Usage
This function is identical to the ph_sendkeysbtn function and reflects the new naming and methodology. The ph_sendkeysbtn function is deprecated and will be removed in a future release.


Blank

ph_formulabtnparm PowerHome formula function
Description
Executes a PowerHome saved formula (PowerHome Explorer->PowerHome->Formulas) with optional parameters.
Syntax
ph_formulabtnparm ( vartype, id, local1, local2, local3, local 4, local5 )
Argument | Description
vartype | Integer. Determines whether the current set of variables will be updated during the formula evaluation or current variable values will be preserved. Use 0 to update the current set of variables. Use any other number to preserve the current values.
id | String. The ID of the Formula that you'd like to have evaluated.
local1 | Any. This value will become the new LOCAL1 value.
local2 | Any. This value will become the new LOCAL2 value.
local3 | Any. This value will become the new LOCAL3 value.
local4 | Any. This value will become the new LOCAL4 value.
local5 | Any. This value will become the new LOCAL5 value.
Return value
String. Returns the result of the formula evaluation.
Usage
You can use this function similar to calling a macro with parameters.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_formulabtnparm(1,"SENDEMAIL","youraddress@email.com","Subject","Message body",0,0)
The above example will execute the SENDEMAIL formula that was previously created in the PowerHome Explorer. It will set the LOCAL1 thru LOCAL5 variables with LOCAL1 being the address to send email to, LOCAL2 being the subject of the email, and LOCAL3 being the body of the email. LOCAL4 and LOCAL5 are not needed by the formula so their values are default set to 0. The first parameter (vartype) of 1 will cause the current variable set to be preserved with no changes occuring to any variables as a result of running the function.


ph_formulabtn_d

ph_formulabtn_d PowerHome formula function
Description
Evaluates a formula in the PowerHome Formulas section with the value returned as a Date.
Syntax
ph_formulabtn_d ( id )
Argument | Description
id | String. The ID of the formula to evaluate.
Return value
Date. Evaluates the formula specified by ID and returns that value as a Date type.


ph_formulabtn_dt

ph_formulabtn_dt PowerHome formula function
Description
Evaluates a formula in the PowerHome Formulas section with the value returned as a DateTime.
Syntax
ph_formulabtn_dt ( id )
Argument | Description
id | String. The ID of the formula to evaluate.
Return value
Date. Evaluates the formula specified by ID and returns that value as a DateTime type.


ph_formulabtn_n

ph_formulabtn_n PowerHome formula function
Description
Evaluates a formula in the PowerHome Formulas section with the value returned as a numeric.
Syntax
ph_formulabtn_n ( id )
Argument | Description
id | String. The ID of the formula to evaluate.
Return value
Date. Evaluates the formula specified by ID and returns that value as a numeric type.


ph_formulabtn_s

ph_formulabtn_s PowerHome formula function
Description
Evaluates a formula in the PowerHome Formulas section with the value returned as a string.
Syntax
ph_formulabtn_s ( id )
Argument | Description
id | String. The ID of the formula to evaluate.
Return value
Date. Evaluates the formula specified by ID and returns that value as a string type.


ph_formulabtn_t

ph_formulabtn_t PowerHome formula function
Description
Evaluates a formula in the PowerHome Formulas section with the value returned as a time.
Syntax
ph_formulabtn_t ( id )
Argument | Description
id | String. The ID of the formula to evaluate.
Return value
Date. Evaluates the formula specified by ID and returns that value as a time type.


ph_getdevicefilter

ph_getdevicefilter PowerHome formula function
Description
Retrieves the current filter applied to the Device Status Screen.
Syntax
ph_getdevicefilter ( )
Return value
String. Returns the filter currently applied to the Device Status Screen.


ph_getdevicesort

ph_getdevicesort PowerHome formula function
Description
Retrieves the sort criteria for the Device Status Screen.
Syntax
ph_getdevicesort ( )
Return value
String. Returns the current sort expression for the Device Status Screen


ph_getline

ph_getline PowerHome formula function
Description
Parses a string containing lines of data separated by cr/lf characters.
Syntax
ph_getline ( data, local )
Argument | Description
data | String. The string containing the data to parse.
local | Integer. A value from 1 to 10 representing a LOCAL variable. This value contains the start position to start searching for the line. This local will also be updated with the new start position.
Return value
String. Returns a single line of data parsed from a string containing multiple lines of data delimited by cr/lf pairs. The local variable specified in the second parameter (a value of 3 specifies [LOCAL3]) should contain the starting position of the line to parse. This initial value contained within the local variable should be initially set to 1. Subsequent calls will update the local variable with the new start positions.


ph_getmd5hash

ph_getmd5hash PowerHome formula function
Description
Calculates the MD5 hash value for the data specified by the as_input parameter
Syntax
ph_getmd5hash ( as_input )
ph_getmd5hash ( as_input, ai_type )
Argument | Description
as_input | String. The data to have the MD5 hash calcuated for. Depending upon the ai_type parameter, this value can be either a direct string, a hex encoded string, or a full path and filename of a file to hash
ai_type | Integer (Optional). Determines how to interpret the data supplied in the as_input parameter. Valid values are 0, 1, 2, and 3. See Usage below for details. If this parameter is not supplied, a value of 0 will be assumed
Return value
String. Returns the calculated MD5 hash value for the specified data
Usage
Use this function to calculate an MD5 hash for strings or files. The hash is done using the standard routines available in C#. The ai_type parameter specifies how to interpret the data in the as_input parameter. An ai_type value of 0 will interpret the data in as_input as a string of ASCII bytes. An ai_type value of 1 will interpret the data as a string of UTF8 bytes. An ai_type value of 2 expects the data in as_input to be a hex encoded string (such as the output of the s2h( ) function). The function will first decode the hex string to their actual byte values and then perform the hash on the byte array. An ai_type value of 3 expects as_input to contain a full path and filename that you wish to hash.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_getmd5hash("Test") - This example will return the following string: 0CBC6611F5540BD0809A388DC95A615B


ph_getmtret

ph_getmtret PowerHome formula function
Description
This function retrieves the result of the last asynchronous operation
Syntax
ph_getmtret ( )
Argument | Description
Return value
Integer. The result of the last asynchronous operation.
Usage
This function currently only has meaning in conjunction with the ph_sendsmtpemailasync and ph_sendsmtpemailfileasync function. When using these functions, you have the option to specify the ID of a macro or formula that you would like to have executed once the asynchronous operation is complete. In this macro or formula, you would call the ph_getmtret function to retrieve the result of the asynchronous operation.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_getmtret()


ph_getsha1hash

ph_getsha1hash PowerHome formula function
Description
Calculates the SHA1 hash value for the data specified by the as_input parameter
Syntax
ph_getsha1hash ( as_input )
ph_getsha1hash ( as_input, ai_type )
Argument | Description
as_input | String. The data to have the SHA1 hash calcuated for. Depending upon the ai_type parameter, this value can be either a direct string, a hex encoded string, or a full path and filename of a file to hash
ai_type | Integer (Optional). Determines how to interpret the data supplied in the as_input parameter. Valid values are 0, 1, 2, and 3. See Usage below for details. If this parameter is not supplied, a value of 0 will be assumed
Return value
String. Returns the calculated SHA1 hash value for the specified data
Usage
Use this function to calculate a SHA1 hash for strings or files. The hash is done using the standard routines available in C#. The ai_type parameter specifies how to interpret the data in the as_input parameter. An ai_type value of 0 will interpret the data in as_input as a string of ASCII bytes. An ai_type value of 1 will interpret the data as a string of UTF8 bytes. An ai_type value of 2 expects the data in as_input to be a hex encoded string (such as the output of the s2h( ) function). The function will first decode the hex string to their actual byte values and then perform the hash on the byte array. An ai_type value of 3 expects as_input to contain a full path and filename that you wish to hash.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getsha1hash("This is a test",0) - Returns a SHA1 hash value of A54D88E06612D820BC3BE72877C74F257B561B19


ph_getsha256hash

ph_getsha256hash PowerHome formula function
Description
Calculates the SHA256 hash value for the data specified by the as_input parameter
Syntax
ph_getsha256hash ( as_input )
ph_getsha256hash ( as_input, ai_type )
Argument | Description
as_input | String. The data to have the SHA256 hash calcuated for. Depending upon the ai_type parameter, this value can be either a direct string, a hex encoded string, or a full path and filename of a file to hash
ai_type | Integer (Optional). Determines how to interpret the data supplied in the as_input parameter. Valid values are 0, 1, 2, and 3. See Usage below for details. If this parameter is not supplied, a value of 0 will be assumed
Return value
String. Returns the calculated SHA256 hash value for the specified data
Usage
Use this function to calculate a SHA256 hash for strings or files. The hash is done using the standard routines available in C#. The ai_type parameter specifies how to interpret the data in the as_input parameter. An ai_type value of 0 will interpret the data in as_input as a string of ASCII bytes. An ai_type value of 1 will interpret the data as a string of UTF8 bytes. An ai_type value of 2 expects the data in as_input to be a hex encoded string (such as the output of the s2h( ) function). The function will first decode the hex string to their actual byte values and then perform the hash on the byte array. An ai_type value of 3 expects as_input to contain a full path and filename that you wish to hash.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getsha256hash("This is a test",0) - Returns a SHA256 hash value of C7BE1ED902FB8DD4D48997C6452F5D7E509FBCDBE2808B16BCF4EDCE4C07D14E


ph_getteactive

ph_getteactive PowerHome formula function
Description
Returns whether a Timed Event is active or not
Syntax
ph_getteactive ( )
ph_getteactive ( as_id )
Argument | Description
as_id | String (Optional). The Timed Event ID that you would like to check is active or not. If this parameter is omitted, the system variable TIMEDEVENT will be used
Return value
Integer. Returns 1 if the specified Timed Event is active. Returns 0 if the Timed Event is not active. Returns -1 if the specified timed event does not exist
Usage
Use this function to determine if a Timed Event is currently set to active within PowerHome
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getteactive("SPRINKLERMON") - Returns 1 if timed event SPRINKLERMON is flagged as active in the Timed Events screen


ph_gettetime

ph_gettetime PowerHome formula function
Description
Returns either the start DateTime or reference DateTime for a Timed Event
Syntax
ph_gettetime ( ai_type )
ph_gettetime ( as_id, ai_type )
Argument | Description
as_id | String (Optional). The ID of the Timed Event to return the DateTime for. If this parameter is omitted, the system variable TIMEDEVENT will be used
ai_type | Integer. The type of DateTime to be returned. Use 0 for the Start Time. Any other value returns the Reference Time
Return value
Datetime. A DateTime value for the specified Timed Event ID and type. If the specified Timed Event doesnt exist, a DateTime value equivalent to 01-01-0000 00:00:00 will be returned
Usage
Use this function to return either the current Start DateTime or Reference DateTime for a Timed Event
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_gettetime("SPRINKLERMON",0) - Returns the next scheduled Start time for the SPRINKLERMON timed event


ph_gettickcount

ph_gettickcount PowerHome formula function
Description
Returns the number of ticks from the system clock chip since last restart or rollover.
Syntax
ph_gettickcount ( )
Return value
Unsignedlong. Returns the number of ticks from the system clock chip. This value starts at 0 when the system is rebooted or if the value rolls over. Handy for timing how long sections of code may take to execute.


ph_highestcontrast

ph_highestcontrast PowerHome formula function
Description
Given a base RGB color to compare to and two RGB colors to choose between, returns the RGB color value that has the highest contrast
Syntax
ph_highestcontrast ( ai_type, al_color1, al_color2, al_backcolor )
Argument | Description
ai_type | Integer. A flags parameter to determine how to perform the calculation. See Usage below for more info
al_color1 | Long. The 1st of 2 RGB color values to check for highest contrast
al_color2 | Long. The 2nd of 2 RGB color values to check for highest contrast
al_backcolor | Long. The base RGB color to compare the above two RGB color values against
Return value
Long. Returns either the value in al_color1 or the value in al_color2. If the RGB color in al_color1 compared to the al_backcolor is a higher contrast than the RGB color in al_color2 compared to the al_backcolor, then al_color1 will be returned. Otherwise, al_color2 will be returned
Usage
Use this function to quickly determine which of two supplied RGB color values will produce a higher contrast against a base RGB color. This function would typically be used to decide whether a foreground color of black or a foreground color of white would provide the best contrast against the supplied background color. In Analog I/O and Zwave raw to calc formulas, a typical scenario is to adjust the background color of the calc value based upon it's value. Having done so, this function will then determine if the foreground color for the calc value would be best as either black or white. You can use ANY valid RGB colors for the al_color1 and al_color2 parameters but either Black or White will always provide the highest possible contrast and best legibility.

The ai_type parameter is a flags (values added together) parameter than determines how the calculation of luminance is performed. The proper value for ai_type is obtained by adding each desired value below together to achieve the desired calcuation result which would should end up as either 4, 8, 12, or 16:

  • 4 - Convert gamma corrected RGB values to linear
  • 8 - Add gamma correction to calculated result. (Don't need this for a pure luminance value)
  • 16 - Square RGB values before applying weights and take SQRT of value after applying weights. Approximates 4 and 8 (12) correction for gamma

    To the above calculated value (either 4, 8, 12, or 16), add ONLY 1 of the below values to determine which set of weights to use

  • 0 - Use 1st set of weighted values
  • 1 - Use 2nd set of weighted values
  • 2 - Use 3rd set of weighted values

    The weight values are below:
    Red | Green | Blue
    Weight 1 | 0.2126 | 0.7152 | 0.0722
    Weight 2 | 0.299 | 0.587 | 0.114
    Weight 3 | 0.241 | 0.691 | 0.068

    Best default to determine displayed color contrast would be a type with a value of 12. This converts gamma corrected RGB values to linear values, applies the first set of weights (most commonly accepted values) and then gamma corrects the result. This gives us a perceived luminance to compare color contrast. This is also the best default to convert color values to grayscale.

    Adding a value of 16 to the type approximates the conversion from gamma corrected RGB values to linear RGB values (raised to power of 2.0 vs power of 2.2). When using a type that includes 16, you would most likely NOT want to include a 4 or 8 in the type value. A type value of 12 or 16 should produce very similar results.

    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_highestcontrast(12,rgb(0,0,0),rgb(255,255,255),rgb(240,170,44)) - Returns 0 which is the rgb value for black or rgb(0,0,0)
    . ph_highestcontrast(12,rgb(0,0,0),rgb(255,255,255),rgb(30,100,44)) - Returns 16777215 which is the rgb value for white or rgb(255,255,255)


ph_keybd_event

ph_keybd_event PowerHome formula function
Description
This function duplicates the Windows API subroutine keybd_event in USER32.DLL.
Syntax
ph_keybd_event ( bvk, bscan, dwflags, dwextrainfo )
Argument | Description
bvk | Specifies a virtual key code. The code must be a value from 1 to 254
bscan | Not used. Set to 0.
dwflags | Specifies various aspects of function operation.
dwextrainfo | Specifies an additional value associated with a keystroke.
Return value
Integer. Returns a 0.
Usage
Refer to Microsofts documentation concerning the use of this function.


ph_latlongcalclat

ph_latlongcalclat PowerHome formula function
Description
Given a starting latitude and longitude, a bearing and a distance to travel, calculates the new latitude
Syntax
ph_latlongcalclat ( d_lat1, d_long1, d_bearing, d_distance )
Argument | Description
d_lat1 | Double. Starting latitude in decimal degrees
d_long1 | Double. Starting longitude in decimal degrees
d_bearing | Double. Bearing (heading) in decimal degrees (0 >= d_bearing < 360)
d_distance | Double. Distance in Kilometers
Return value
Double. Returns the calcuated latitude in decimal format
Usage
Use this function along with the ph_latlongcalclong( ) function to calculate a new latitude and longitude from a starting point (lat/long) and traveling for d_distance on a bearing of d_bearing
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_latlongcalclat(28.78, -81.25,25.2,38.4) - Returns a latitude of 29.09236822460959


ph_latlongcalclong

ph_latlongcalclong PowerHome formula function
Description
Given a starting latitude and longitude, a bearing and a distance to travel, calculates the new longitude
Syntax
ph_latlongcalclong ( d_lat1, d_long1, d_bearing, d_distance )
Argument | Description
d_lat1 | Double. Starting latitude in decimal degrees
d_long1 | Double. Starting longitude in decimal degrees
d_bearing | Double. Bearing (heading) in decimal degrees (0 >= d_bearing < 360)
d_distance | Double. Distance in Kilometers
Return value
Double. Returns the calcuated longitude in decimal format
Usage
Use this function along with the ph_latlongcalclat( ) function to calculate a new latitude and longitude from a starting point (lat/long) and traveling for d_distance on a bearing of d_bearing
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_latlongcalclat(28.78, -81.25,25.2,38.4) - Returns a latitude of -81.0817332315134


ph_latlongdist

ph_latlongdist PowerHome formula function
Description
Determines the straight line distance between two latitude/longitude points.
Syntax
ph_latlongdist ( lat1, long1, lat2, long2 )
Argument | Description
lat1 | Double. The latitude for point 1.
long1 | Double. The longitude for point 1.
lat2 | Double. The latitude for point 2.
long2 | Double. The longitude for point2.
Return value
Double. The distance between the two points is returned in kilometers.
Usage
The lat/long values must be entered in pure decimal format. Northern latitudes are entered as a positive number, southern latitudes as a negative number. Eastern longitudes are a positive number, western longitudes are a negative number.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_latlongdist(28.6761,-81.5106,27.9710,-82.4650)
The above example calculates the distance between Apopka, Florida and Tampa, Florida. The returned value will be: 121.9592661764512 kilometers.


ph_latlongendbearing

ph_latlongendbearing PowerHome formula function
Description
Given a starting latitude/longitude and an ending latitude/longitude, calculates the final (end) bearing in degrees
Syntax
ph_latlongendbearing ( d_lat1, d_long1, d_lat2, d_long2 )
Argument | Description
d_lat1 | Double. Starting latitude in decimal degrees
d_long1 | Double. Starting longitude in decimal degrees
d_lat2 | Double. Ending latitude in decimal degrees
d_long2 | Double. Ending longitude in decimal degrees
Return value
Double. Returns the final (end) bearing in decimal degrees going from the starting point to the ending point
Usage
Use this function to calculate the final (end) bearing after traveling from a starting lat/long to an ending lat/log
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_latlongendbearing(28.78, -81.25,29.092410, -81.081711) - Returns an end bearing of 25.28137896027616


ph_latlongmidlat

ph_latlongmidlat PowerHome formula function
Description
Calculates the midpoint latitude between a starting lat/long and an ending lat/long
Syntax
ph_latlongmidlat ( d_lat1, d_long1, d_lat2, d_long2 )
Argument | Description
d_lat1 | Double. Starting latitude in decimal degrees
d_long1 | Double. Starting longitude in decimal degrees
d_lat2 | Double. Ending latitude in decimal degrees
d_long2 | Double. Ending longitude in decimal degrees
Return value
Double. Returns the latitude in decimal degrees that is midway between a starting lat/long and ending lat/long
Usage
Use this function along with the ph_latlongmidlong( ) function to find the midpoint lat/long between two supplied lat/long points
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_latlongmidlat(28.78, -81.25,29.092410, -81.081711) - Returns a midpoint latitude in decimal degrees of 28.93623116271454


ph_latlongmidlong

ph_latlongmidlong PowerHome formula function
Description
Calculates the midpoint longitude between a starting lat/long and an ending lat/long
Syntax
ph_latlongmidlong ( d_lat1, d_long1, d_lat2, d_long2 )
Argument | Description
d_lat1 | Double. Starting latitude in decimal degrees
d_long1 | Double. Starting longitude in decimal degrees
d_lat2 | Double. Ending latitude in decimal degrees
d_long2 | Double. Ending longitude in decimal degrees
Return value
Double. Returns the longitude in decimal degrees that is midway between a starting lat/long and ending lat/long
Usage
Use this function along with the ph_latlongmidlat( ) function to find the midpoint lat/long between two supplied lat/long points
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_latlongmidlong(28.78, -81.25,29.092410, -81.081711) - Returns a midpoint longitude in decimal degrees of -81.16598232655467


ph_latlongstartbearing

ph_latlongstartbearing PowerHome formula function
Description
Given a starting latitude/longitude and an ending latitude/longitude, calculates the initial (start) bearing in degrees
Syntax
ph_latlongstartbearing ( d_lat1, d_long1, d_lat2, d_long2 )
Argument | Description
d_lat1 | Double. Starting latitude in decimal degrees
d_long1 | Double. Starting longitude in decimal degrees
d_lat2 | Double. Ending latitude in decimal degrees
d_long2 | Double. Ending longitude in decimal degrees
Return value
Double. Returns the initial (start) bearing in decimal degrees going from the starting point to the ending point
Usage
Use this function to calculate the initial (start) bearing in order to travel from a starting lat/long and arrive at an ending lat/log
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_latlongstartbearing(28.78, -81.25,29.092410, -81.081711) - Returns a start bearing of 25.1999544221211


ph_ldapquery

ph_ldapquery PowerHome formula function
Description
Allows a limited query against LDAP for a persons name and a specific attribute
Syntax
ph_ldapquery ( as_name, as_attribute )
Argument | Description
as_name | String. The persons name in LDAP
as_attribute | String. The attribute you'd like to retrieve from LDAP
Return value
String. Returns the LDAP result for the requested person/attribute
Usage
Use this function to quickly query LDAP for attributes for a person. NOTE: this function does not work in a typical home environment and will usually ONLY work in a corporate environment where Active Directory is in use

This function performs limited LDAP queries in the format of: "(&(objectcategory=person)(objectclass=user)(name= " + as_name + "));" + as_attribute +";subtree"

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_ldapquery("dwh","mail") - Returns the email address for user AD user DWH


ph_luminance

ph_luminance PowerHome formula function
Description
Returns the perceived luminance (brightness) of an RGB color value
Syntax
ph_luminance ( ai_type, al_color )
Argument | Description
ai_type | Integer. A flags parameter that control how the luminance calculations are performed. See Usage below
al_color | Long. A standard RGB color value to determine the luminance of
Return value
Integer. Returns the perceived luminance of the RGB color value in the range of 0 to 255 with 255 being the brightest or highest luminance
Usage
Use this function to determine the luminance of an RGB color value. Useful for determining the perceived brightness of a color

The ai_type parameter is a flags (values added together) parameter than determines how the calculation of luminance is performed. The proper value for ai_type is obtained by adding each desired value below together to achieve the desired calcuation result which would should end up as either 4, 8, 12, or 16:

  • 4 - Convert gamma corrected RGB values to linear
  • 8 - Add gamma correction to calculated result. (Don't need this for a pure luminance value)
  • 16 - Square RGB values before applying weights and take SQRT of value after applying weights. Approximates 4 and 8 (12) correction for gamma

    To the above calculated value (either 4, 8, 12, or 16), add ONLY 1 of the below values to determine which set of weights to use

  • 0 - Use 1st set of weighted values
  • 1 - Use 2nd set of weighted values
  • 2 - Use 3rd set of weighted values

    The weight values are below:
    Red | Green | Blue
    Weight 1 | 0.2126 | 0.7152 | 0.0722
    Weight 2 | 0.299 | 0.587 | 0.114
    Weight 3 | 0.241 | 0.691 | 0.068

    Best default to determine perceived luminance/brightness would be a type with a value of 12. This converts gamma corrected RGB values to linear values, applies the first set of weights (most commonly accepted values) and then gamma corrects the result. This is also the best default to convert color values to grayscale.

    Adding a value of 16 to the type approximates the conversion from gamma corrected RGB values to linear RGB values (raised to power of 2.0 vs power of 2.2). When using a type that includes 16, you would most likely NOT want to include a 4 or 8 in the type value. A type value of 12 or 16 should produce very similar results.

    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_luminance(12,rgb(255,255,255)) - Returns a luminance value of 255. The function rgb(255,255,255) is pure white and would have the highest luminance
    . ph_luminance(12,rgb(255,0,0)) - Returns a luminance value of 127. The function rgb(255,0,0) is pure red
    . ph_luminance(12,rgb(0,0,255)) - Returns a luminance value of 76. The function rgb(0,0,255) is pure blue and indicates that pure red (127) will be perceived as brighter than pure blue (76)


ph_macro

ph_macro PowerHome formula function
Description
Plays a PowerHome macro.
Syntax
ph_macro ( id )
Argument | Description
id | String identifying the ID of the macro you wish to play.
Return value
Integer. Returns a 0 if the macro is successfully played. A 1 signifies that no rows exist in the macrodetail table. A 2 is returned if you try to play the special macros 'PLAYSLOTTRACK' or 'PLAYPLAYLIST'. A 3 is returned if an infinite loop condition is detected.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_macro("GDR-S SENSE")
• ph_macro("CAMTRIG")


ph_macroparm

ph_macroparm PowerHome formula function
Description
Plays a PowerHome macro and passes 5 optional parameters.
Syntax
ph_macroparm ( s, a, a, a, a, a )
Argument | Description
s | A string identifying the ID of the macro you wish to play.
a | Any data type that will be passed to LOCAL1.
a | Any data type that will be passed to LOCAL2.
a | Any data type that will be passed to LOCAL3.
a | Any data type that will be passed to LOCAL4.
a | Any data type that will be passed to LOCAL5.
Return value
Integer. Returns a 0 if the macro is successfully played. A 1 signifies that no rows exist in the macrodetail table. A 2 is returned if you try to play the special macros 'PLAYSLOTTRACK' or 'PLAYPLAYLIST'. A 3 is returned if an infinite loop condition is detected.
Usage
The passed parameters are copied into the system variables LOCAL1 thru LOCAL5. Any valid data type can be passed in these values. All data types are first converted to type string before being stored in the system variables. You must specifiy a valid data type for each parameter. If you do not wish to pass data for a particular parameter then just pass either "" or 0.


ph_macroparmret

ph_macroparmret PowerHome formula function
Description
Plays a PowerHome macro and passes 5 optional parameters. Also returns the value stored in LOCAL1 when the macro terminates.
Syntax
ph_macroparmret ( s, a, a, a, a, a )
Argument | Description
s | A string identifying the ID of the macro you wish to play.
a | Any data type that will be passed to LOCAL1.
a | Any data type that will be passed to LOCAL2.
a | Any data type that will be passed to LOCAL3.
a | Any data type that will be passed to LOCAL4.
a | Any data type that will be passed to LOCAL5.
Return value
String. Returns the value that was last stored in system variable LOCAL1 when the macro terminated.
Usage
The passed parameters are copied into the system variables LOCAL1 thru LOCAL5. Any valid data type can be passed in these values. All data types are first converted to type string before being stored in the system variables. You must specifiy a valid data type for each parameter. If you do not wish to pass data for a particular parameter then just pass either "" or 0.


ph_modifytimedevent

ph_modifytimedevent PowerHome formula function
Description
Modifies an existing Timed Event.
Syntax
ph_modifytimedevent ( ai_active, adt_reftime, ai_flags )
ph_modifytimedevent ( as_id, ai_active, adt_reftime, ai_flags )
Argument | Description
as_id | String (Optional). The ID of the Timed Event you wish to modify. If this parameter is omitted, then the system variable TIMEDEVENT will be used for ID
ai_active | Integer. Use 0 to set the Timed Event inactive. Use 1 to set the Timed Event active. Controlled by the flags parameter.
adt_reftime | DateTime. The new reference time for the specified Timed Event. Using the reference time, a new start time will be calculated. Controlled by the flags parameter.
ai_flags | Integer. Determines which parameters are used to update the Timed Event. Add values together. 1 - Recalculate a new StartTime, 2 - Update the Active parameter, 4 - Set a new RefTime and recalculate StartTime, 8 - Delete the Timed event (other flag options will be ignored).
Return value
Integer. Returns 0 if successful. 1 if the Timed Event specified does not exist.
Usage
Use this function to update an existing timed event to set a new start/reference time, set a timed event inactive, or delete the specified timedevent.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_modifytimedevent("SPRINKLERMON",0,datetime(date("2020-05-25","yyyy-mm-dd"),time("04:00:00","hh:mm:ss")),4) - Updates the SPRINKLERMON timed event and sets the reference time to 05/25/2020 04:00:00


ph_msgbox

ph_msgbox PowerHome formula function
Description
Displays a message box window.
Syntax
ph_msgbox ( title, message, timeout )
Argument | Description
title | String. The title to display within the title bar of the window.
message | String. The text to display within the body of the window.
timeout | Integer. The number of seconds for the window to display before automatically closing itself. Use 0 for the window to not close itself automatically.
Return value
Integer. Returns a 0.
Usage
Use this function to quickly display a message to the user. It is important to note that this function DOES not wait for the user to press a button or the window to timeout. PowerHome execution WILL NOT be halted and will continue as normal. There is NO way to detect if the user has closed the window or if the window has timed out short of programatically looping and checking for the existance of the window. This function is intended ONLY for the display of informational text. If you wish to display messages and continue processing after the user has closed the message box, use the macro command "Message Box".
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_msgbox("SYNC-GRAPHIC1","DVC ID=[LOCAL1]; CC BUT ID=[LOCAL2]~r~n Intensity=[LOCAL3]",10)
• ph_msgbox("","LOCAL5=[LOCAL5]",10)
• ph_msgbox("INITIALIZE","Initialization Finished",3)
• ph_msgbox("SYNC-GRAPHIC4","[LOCAL1] ON and CC item made yellow",5)


ph_natlang

ph_natlang PowerHome formula function
Description
This function allows you to pass an English command string (such as "Turn on the Dining Room light") to be processed as natural language and have the interpreted results of that command optionally executed
Syntax
ph_natlang ( as_cmd, ai_type, ai_tables, ai_execute, ai_certainty, ai_fullresult, ai_rettype, ai_vars )
Argument | Description
as_cmd | String. The English command to be analyzed and interpreted
ai_type | Integer. This parameter controls how the command is analyzed against the PowerHome database. A number of options represented by numbers can be added together to achieve the desired combination of options to be analyzed. This value will end up being a number between 1 and 1023. The individual options (represented by binary values) and their associated functions are detailed in the Usage section below
ai_tables | Integer. This parameter controls which tables and views are used in the analysis of the command. This will be a number from 0 to 15 and is derived by adding binary identfiers representing the tables and views that will be used to create the dynamic SQL
ai_execute | Integer. This parameter specifies whether or not to execute the command in as_cmd for the top ranking match. A value of -1 means to never execute. A value of 0 means to always execute. Any other positive number represents the minimum "rank" value the top ranked match must meet in order to execute the command. Whether a command is executed or not depends upon both this parameter and the ai_certainty parameter
ai_certainty | Integer. This parameter specifies whether or not to execute the command based upon the difference in rank between the top and second ranked matches. A value of 0 means to always execute if the ai_execute parameter conditions are met. Any other positive values indicates the minimum difference in rank between the top and second matches before executing. It is a combination of this parameter and the ai_execute parameter that determines if a command is actually executed
ai_fullresult | Integer. Specifies how to display the internal results of the match analysis. A value of 0 means to discard the results. A value of 1 means to place the results in the clipboard. A value of 2 will open a results window similar to a SQL Query and display the results. A value of 3 will place the results in the clipboard AND open a results window
ai_rettype | Integer. Specifies the string data to be returned by the function. A value of 0 returns the top ranked match details. A value of 1 returns the full results (the same contents that would be sent to the clipboard if ai_fullresult = 1). A value of 2 returns the answer/results of the execution of the top ranked match if it is executed (this is the value most likely to be used in normal usage)
ai_vars | Integer. Specifies a starting system variable to return the function "return value" and details of the top ranked match. Use 0 to not update a system variable. Use 1 to 10 for [LOCAL1] thru [LOCAL10]. Use 101 thru 110 for [TEMP1] thru [TEMP10]. Use 1001 thru 1100 for [GLOBAL1] thru [GLOBAL100]. A total of up to 6 data items will be returned. If ai_vars = 2 then the first data item will be in [LOCAL2], the second data item in [LOCAL3], etc. The data items returned (in order) are the numeric function return value (see Return value below for the possible return values), the top rank match "Rank", "Type", "ID", "Keynum", and "Description"
Return value
String. Returns a number of different results/data dependent upon the value in the ai_rettype parameter. In normal usage, the ai_rettype parameter will by 2 and the function will return the results or answer of the execution of the top ranked match if the execution actually occurs (determined by the ai_execute and ai_certainty parameters). An ai_rettype of 0 will return the function "return value" followed by the following top ranked match details all separated by a tab (~t) character: rank, type, id, keynum, description. An ai_rettype of 1 will return tab separated lines of the results of the match analysis. The "return value" for the function which will be returned as the first piece of data if the ai_rettype = 0 will be a number representing the results of the analysis. The possible return values are:
  • 0 - Success
  • 1 - Error: as_cmd is blank
  • 2 - Error: ai_type out of range
  • 3 - Error: ai_tables out of range
  • 4 - Error: dynamic SQL generation failed
  • 5 - Error: dynamic SQL create failed
  • 6 - Error: no data found for dynamic SQL
  • 7 - Error: below minimum rank level in ai_execute
  • 8 - Error: below minimum certainty level (difference in rank between the top and second matches) in ai_certainty
Usage
Use this function to pass natural language commands to PowerHome for execution and the return of the results. This natural language can be generated from an email, webpage, text, smart assistant, etc. The function works by searching for keywords in the command such as play, run, execute, do, what, give, set, etc. to determine the desired control action and then searches the PowerHome database for the closest matching entity to execute the desired action upon. The function is capable of returning various sets of data through the return value of the function, data placed in the clipboard, and data returned into system variables.

The function will return a string of data based upon the value in the ai_rettype parameter. See the Return Value section above for details on the data that can appear in this string. The function also provides two other mechanisms for returning data that can be processed by the user. If the ai_fullresults parameter is 1, 2, or 3, you'll get access to the full analysis results of the database matching in either the clipboard, a separate window, or both. If the ai_vars parameter specifies an appropriate starting system variable number, then you will get the numeric function return result as well as details on the top ranked match assuming the function return result is not an error. In normal usage, the ai_fullresult parameter will be set to 0 and the ai_rettype parameter will be set to 2. In this case, you'll want to set the ai_vars value to a valid system variable number in order to get the results of the analysis (with ai_rettype = 2, the function return value will be the result of the execution of the command and not the results of the analysis). When debugging to determine the best settings for the parameters based upon how you've configured PowerHome and your usage patterns, you'll probably set the ai_execute parameter to -1 (you don't want to execute during testing) and the ai_fullresults to 2 so you can easily see the analysis results and how your tweaking of parameters such as ai_type and ai_tables have affected the outcome.

The function builds dynamic SQL to execute upon the database based upon the individual words in the command, the SQL options specified in ai_type, and the tables / views specified in the ai_tables parameters. Depending upon the options chosen in ai_types and how many of those options result in a match, the sum of the matches will become the "rank" for the match. The higher the "rank" value, the more options were matched and a higher certainty that the command was properly interpreted. Each match is returned in a table sorted by rank from highest to lowest. If you configure the function such to return the "full results", you will be able to see and analyze this data. The match with the highest rank can be executed if the criteria for the ai_execute and ai_certainty parameters are met. The ai_execute parameter can define a minimum "rank" level that the top match must meet before an execution can occur. The ai_certainty parameter can control by how much the top match rank and the second match rank must differ before an execution can occur. If the top matched rank is 400 and the second rank is 290 (a difference of 110) then you can be fairly certain that the top match is definitely what you want to execute. If the top rank is 400 and the second rank is 398 (a difference of 2), then you may want not want to execute the command because it is so close in matching to the second ranked match.

The binary values to be added together for the desired options in the ai_type parameter are detailed below:
Value | Description
1 | Perform a DB similar search for each command word without spaces in the "ID" field
2 | Perform a DB similar search for each command word with spaces in the "Description" field
4 | Perform a DB similar search for each command word without spaces in the "Description" field
8 | Perform a DB similar search for each command word with spaces in the "ID" field
16 | Perform a DB similar search for full buildup of all command words without spaces in "ID" field
32 | Perform a DB similar search for full buildup of all command words with spaces in "Description" field
64 | Perform a DB similar search for full buildup of all command words without spaces in "Description" field
128 | Perform a DB similar search for full buildup of all command words with spaces in "ID" field
256 | Searches for the existance of each word in the command in the "ID" field
512 | Searches for the existance of each word in the command in the "Description" field

The binary values to be added together for the desired tables / views to perform the database search on in the ai_tables parameter are detailed below:
Value | Description
0 | If the ai_tables parameter is 0, then PowerHome will automatically determine the tables/views to search based upon the command action words
1 | Include the Device Status view in the search. This would include any type of device that appears on the Device Status screen
2 | Include the Macro Header table in the search
4 | Include the IR table in the search
8 | Include the Global Variables table in the search
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_natlang("turn on dining room light",742,15,0,0,0,2,0) - Depending upon PowerHome configuration, a possible return value could be: "Insteon device DINING ROOM set to ON"


ph_openiewindow

ph_openiewindow PowerHome formula function
Description
Allows the user to open a specialized window object consisting of an Internet Explorer control. Full control of this window is available by sending Windows messages.
Syntax
ph_openiewindow ( title, url, flags, x, y, width, height, timeout )
Argument | Description
title | String. The Title you wish to appear on the IE window.
url | String. The URL you wish to be opened in the Internet Explorer window control. You can use the system variable [HANDLE] to have the handle of the IE Wndow substituted within the URL.
flags | Integer. Individual flag values summed together to control how the window appears. The individual flag values are: 1 to suppress the Title bar. 2 to make the Window not resizeable. 4 to remove the Control menu. 8 to remove the minimize box. 16 to remove the maximize box. 32 to suppress the display of the countdown timer if a timeout value is passed. 64 to suppress scrollbars. 128 to have the IE Window NOT be a child window of the PowerHome environment. 256 to have the window open maximized.
x | Integer. The X location you wish the IE Window to appear. Use - 1 to have the window centered horizontally.
y | Integer. The Y location you wish the IE Window to appear. Use - 1 to have the window centered vertically.
width | Integer. The width of the IE Window. Use - 1 to set the width of the window to the screen width.
height | Integer. The height of the IE Window. Use - 1 to set the height of the window to the screen height.
timeout | Integer. The time in seconds for the IE Window to remain open. Use 0 if you don't wish the window to timeout and close automatically.
Return value
Unsigned Long. Returns the handle of the new IE Window. Using this handle, Windows Messages can be sent to remotely control aspects of the window.
Usage
You can use this function to create highly configurable user display windows to also control aspects of PowerHome if the URL contains control code to manipulate the PH environment.


ph_parseline

ph_parseline PowerHome formula function
Description
Parses values from a line of string data.
Syntax
ph_parseline ( line, sep, instance )
Argument | Description
line | String. The string of line data to parse.
sep | String. A string representing the separater character(s). For tab separated values use "~t"
instance | Integer. The instance of the data you wish to retrieve. The first value is 1.
Return value
String. The parsed piece of data.


ph_pid

ph_pid PowerHome formula function
Description
Allows for calculating a PID (Proportional Integral Derivative) control value
Syntax
ph_pid ( as_id, ad_setpoint, ad_input, ad_outmin, ad_outmax, ad_p, ad_i, ad_d )
Argument | Description
as_id | String. The ID you would like to use for this particular PID control loop. If the ID has not been used before, a new entry is created in the PID table. The ID can only contain the following characters A-Z, 0-9, _, -, or space characters and must be 25 characters or less in length
ad_setpoint | Double. The SetPoint wish to control to. This is the desired value you hope to achieve by sequentially applying the output of repeated calls to this function
ad_input | Double. The current value of what you're trying to control. Ideally, the ad_input value will reach and stabilize at the ad_setpoint value
ad_outmin | Double. The minimum control output adjustment that the function should return
ad_outmax | Double. The maximum control output adjustment that the function should return
ad_p | Double. The Proportional constant you wish to use
ad_i | Double. The Integral constant you wish to use
ad_d | Double. The Derivative constant you wish to use
Return value
Double. Returns the calculated control output to be applied in an effort for the ad_input value to equal the ad_setpoint value. Returns -99999999 if the ID contains invalid characters or is too long
Usage
Use this function to enable PID control loops. A good explantion of PID control can be found at this Wikipedia entry: https://en.wikipedia.org/wiki/PID_controller. This type of control algorithm and feedback loop is typically used in industrial automation.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_pid("TESTPID",75,70.3, -4,4,0.3,0.02,0) - Returns a value between -4 and 4 depending upon currently stored internal values from previous executions of the function. In this hypothetical example, our setpoint is 75 and the current value is 70.3 which will likely return a value of 4. Based upon how that effects the current value, the output will be adjusted accordingly until equilibrium with each successive call to the function. This example illustrates the most commonly used control loop of PI (Proportional Integral) control since the Derivative value is set to 0.


ph_pidclear

ph_pidclear PowerHome formula function
Description
Allows the user to delete previously saved PID data (created with the ph_pid( ) function) from the PID database table
Syntax
ph_pidclear ( as_id )
Argument | Description
as_id | String. The ID of the PID data you would like to delete. Use an empty string "" to clear ALL the saved PID data
Return value
Integer. Returns 0 if successful. If an error occurs while deleting the data, a 1 will be returned. Specifying an invalid PID ID will not return an error and will return 0. An error occurs only if the table delete fails
Usage
Use this function to delete no longer needed PID data from the PID database table
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_pidclear("TESTPID") - Returns 0 and deletes just the data associated with the PID ID "TESTPID"
. ph_pidclear("") - Returns 0 and deletes ALL currently stored PID data


ph_ping

ph_ping PowerHome formula function
Description
Pings a machine on the network.
Syntax
ph_ping ( host, ttl )
Argument | Description
host | String. The IP of hostname of the machine to ping.
ttl | Integer. The Time to Live value for the Ping command in milliseconds. Use values from 1 to 255.
Return value
Integer. Returns the Round Trip Time in milliseconds or a negative number if an error occurs. Returns -1 if the host is an invalid IP or hostname. Returns -2 if a system error occurs. Returns -3 if the ping fails. Values less than or equal to -11000 are errors returned from the Ping command itself.
Usage
Use the ph_ping command to check for the availability of a machine on the network.


ph_ping1

ph_ping1 PowerHome formula function
Description
Pings a machine on the network using either a Catalyst ICMP control or function within Microsofts ICMP.DLL.
Syntax
ph_ping1 ( type, ip, ttl, timeout )
Argument | Description
type | Integer. Determines the method that will be used to ping the machine. Use 0 to ping using Microsofts ICMP.DLL (same as the ph_ping function). Use any other value to ping using the Catalyst ICMP control.
ip | String. The IP or URL you wish to ping.
ttl | Integer. The Time To Live value to pass to the ping function for the ICMP echo datagram.
timeout | Long. The time in milliseconds before the function times out.
Return value
Long. Returns a positive value representing the time in milliseconds to complete the ping operation. A negative return indicates an error occured.
Usage
Use this function to verify a machine is available on the network.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_ping1(1,"www.google.com",100,50)
The above example will ping Google with a TTL value of 100 ms using the Catalyst ICMP control. The function will timeout after 50 ms if the ping has not yet returned.


ph_regex

ph_regex PowerHome formula function
Description
Performs a regular expression search on a string of data.
Syntax
ph_regex ( pattern, data, start, flags, localstart, locallength )
Argument | Description
pattern | String. A regular expression search pattern.
data | String. The string in which to perform the search.
start | Long. The position within the data in which to start the search. Use 1 to start at the beginning.
flags | Integer. Flags that control how the search is performed. Add individual flag values together. Add 1 to cause the search to match case. Add 2 to cause the search to ignore cr/lf's within the data.
localstart | Integer. The index of a local variable in which to have the start of the found data returned. Use 0 to not have the start returned.
locallength | Ingeger. The index of a local variable in which to have the length of the found data returned. Use 0 to not have the length returned.
Return value
String. Returns the data that matches the regular expression search criteria.
Usage
Use this function for powerful text searching capabilities. The regular expression special characters supported are:
. | Matches any character.
\< | This matches the start of a word, where a word is defined in the traditional sense, that is, letters, or number. Spaces, punctuation, CR/LF, etc. would not be included as part of a word, and thus create a break.
\> | This matches the end of a word. See also word definition above.
\x | This allows you to use a character x that would otherwise have a special meaning. For example, \[ would be interpreted as [ and not as the start of a character set.
[...] | This indicates a set of characters, for example, [abc] means any of the characters a, b or c. You can also use ranges, for example [a-z] for any lower case character.
[^...] | The complement of the characters in the set. For example, [^A-Za-z] means any character except an alphabetic character.
^ | This matches the start of a line (unless used inside a set, see above).
$ | This matches the end of a line.
* | This matches 0 or more times. For example, Sa*m matches Sm, Sam, Saam, Saaam and so on.
+ | This matches 1 or more times. For example, Sa+m matches Sam, Saam, Saaam and so on.

An important note on the special characters is that they can conduct a "greedy" regular expression search. When using the * and + special characters this function will not stop at the first match but will instead go to the last match.

NOTE: If a string contains any quote characters (") then the string must be delimited with the single quote charcter ('). For example... 'he said, "no"'

Also this function will not perform a regular expression search that spans multiple lines. If the data to search contains carraige returns or line feeds, the entire matching search data for the regular expression must exist within a single line. If your regular expression must span across a line, then add 2 to the flags to have CR's and LF's temporarily converted. CR will be converted to ASCII 128 and LF will be converted to ASCII 129. If you convert CF/LF then you can include them in your search with PowerHome escape characters ~128 and ~129 respectively.

NOTE: Where search pattern srings might contain a quote (') character then you must use the single quote (') character to delineate your string variables. For example:
ph_regex ('he said, "no" ', "[LOCAL1"', 1, 0,1,2 )

You may also perform multiple searches by separating your search pattern using the PowerHome escape character ~255. This is most useful when CF/LF IS NOT replaced and trying to match a particular piece of data. When using multiple searches, only the last matching search data is returned. An example multiple search would be: "degrees$~255[0-9]+ humidity". What this search does is first search for the first occurence where the word "degrees" appears at the end of a line. The function will then do a regex search using "[0-9]+ humidity" starting from the end of the last regex search (the start of the line following the one on which "degrees" was found).

This function is often used with other PH string functions to trim a larger string, or to locate a string position within another string. See also pos(), posw(), ph_pos(), left(), mid(), right().

See also the .FAQs-String Tips-Hints Help file.

Examples
The following examples demonstrate typical syntax/usage for this function.

*** Simple Example ***
Assume you have multiple water leak sensors installed and trigger from each individually, but want to process them all with a single common Macro routine that puts the battery status (GOOD/BAD) in a series of Globals named "BATCHK_SINK", "BATCHK_WASHING", "BATCHK_TOILET"

The Leak Sensor battery periodic heartbeat Trigger will pass the triggering device's ID (eg, "WATER LEAK-SINK") to the Macro. If you name all the device ID's in a similar fashion, such as . . .

WATER LEAK-SINK
WATER LEAK-WASHING
WATER LEAK-TOILET

Then you can strip off the unique device name (following the dash) and write the status to the appropriate Global var, as follows.

The following string operations would find the unique device name then append it to the base Global string to form the unique Global variable name.

Macro line 100 searches the device ID string date passed in TEMP10 by the Trigger and looks for the dash character ("-") starting at position 1 in the string. Since this is a simple search no special Flag settings are needed, so "0" is used. The last two parameters will store in LOCAL 4 the position of the "-" in the string, and in LOCAL5 the length of the found data ("-SINK"). These are useful for further string operations, but actually not needed here, but shown for generality.

Macro line 110 trims the dash off the found string, leaving only "SINK"

Macro line 120 appends "SINK" to the common Global name of "BATCHK_" forming "BATCHK_SINK"

Finally in line 130, the value "OK" is written to this Global variable.

Line 140 prints out the various parameter values FYI.

*** Complex Example ***
The following examples assume that the following string (with CR/LF line enders) is stored in [LOCAL1]...

ROMId,Name, Value,Avg,
"3F000001CD92C728","Refrig",39.20,37.46,
"3F6000017C8BD128","Outside",23.90,19.81,
"3F000001CDB2BA27","House",70.65,70.13,
"3F000001CD9E6D28","Freezer",1.96,1.11,

The following command extractsthe 9 ending digits of the first ROM ID. Note there is no need to set the CR/LF flag since the Start Pointer (35) positioned the search to start and end in a single line.
ph_regex ('.........',"[LOCAL1]", 36, 0,2,3 ) --> returns "1CD92C728"

This captures the initial portion of the first ROM ID
ph_regex ("3F[0-9]+","[LOCAL1]", 1, 0,2,3 ) --> returns "3F000001"

Because of "greediness" the following will search from "3F" to the beginning of the last word it can find on the line (not the first word).
ph_regex ("3F.+\<","[LOCAL1]", 1, 0,2,3 ) --> returns "3F000001CD92C728","Refrig",39.20,37."

Note that if the CR/LF flag had been set to 2 (ignore line endings) the search would have captured everything from the first "3F" all the way to the "...6D28","Freezer",1.96,1." characters at the end.


ph_regex2

ph_regex2 PowerHome formula function
Description
Performs a regular expression search against a string of data.
Syntax
ph_regex2 ( pattern, data, start, occur, flags, localstart, locallength )
Argument | Description
pattern | String. A regular expression search pattern.
data | String. The string in which to perform the search.
start | Long. The position within the data in which to start the search. Use 1 to start at the beginning.
occur | Integer. The occurence of the match you'd like returned. If a file contains multiple matches and this value is 3, then the 3rd matching occurence will be returned.
flags | Integer . Flags that control how the search is performed. Set this value to 1 in order to match case. Use 0 for case insensitive searches.
localstart | Integer. The index of a local variable in which to have the start of the found data returned. Use 0 to not have the start returned.
locallength | Ingeger. The index of a local variable in which to have the length of the found data returned. Use 0 to not have the length returned.
Return value
String. Returns the regular expression match.
Usage
This function is very similar to the ph_regex function except that it uses the regular expression engine contained within the Microsoft VBScript library. The ph_regex function uses the open source Scintilla editor to perform regular expression searches which is more limited in options and capabilities.

The full documentation for this regular expression library is way too much information for this help file. Please reference this site for a very good reference and tutorial for utilizing the Microsoft VBScript regular expression library: http://www.regular-expressions.info/vb.html
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_regexsnap2("def[\S\s]*mn","abcdefghijklmnopqrstuvwxyz",1,1,0,0,0)
The above example will return "defghijklmn".


ph_regexdiff

ph_regexdiff PowerHome formula function
Description
searches a string of data and returns the data between two regular expression searches.
Syntax
ph_regexdiff ( pat1, pat2, data, start, flags )
Argument | Description
pat1 | String. The starting regular expression search pattern.
pat2 | String. The ending regular expression search pattern.
data | String. The string in which to perform the search.
start | Long. The position within the data in which to start the search. Use 1 to start at the beginning.
flags | Integer. Flags that control how the search is performed. Add individual flag values together. Add 1 to cause the search to match case. Add 2 to cause the search to ignore cr/lf's within the data.
Return value
String. Returns the data string between the pat1 regular expression and pat2 regular expression.
Usage
Use this function for powerful text search capabilities. The regular expression special characters supported are:
. | Matches any character.
\< | This matches the start of a word, where a word is defined in the traditional sense, that is, letters, or number. Spaces, punctuation, CR/LF, etc. would not be included as part of a word, and thus create a break.
\> | This matches the end of a word. See also word definition above.
\x | This allows you to use a character x that would otherwise have a special meaning. For example, \[ would be interpreted as [ and not as the start of a character set.
[...] | This indicates a set of characters, for example, [abc] means any of the characters a, b or c. You can also use ranges, for example [a-z] for any lower case character.
[^...] | The complement of the characters in the set. For example, [^A-Za-z] means any character except an alphabetic character.
^ | This matches the start of a line (unless used inside a set, see above).
$ | This matches the end of a line.
* | This matches 0 or more times. For example, Sa*m matches Sm, Sam, Saam, Saaam and so on.
+ | This matches 1 or more times. For example, Sa+m matches Sam, Saam, Saaam and so on.

An important note on the special characters is that they can conduct a "greedy" regular expression search. When using the * and + special characters this function will not stop at the first match but will instead go to the last match.

NOTE: If a string contains any quote characters (") then the string must be delimited with the single quote charcter ('). For example... 'he said, "no"'

This function will also not perform a regular expression search that spans multiple lines. If the data to search contains carraige returns or line feeds, the entire matching search data for the regular expression must exist within a single line. If your regular expression must span across a line, then add 2 to the flags to have CR's and LF's temporarily converted. CR will be converted to ASCII 128 and LF will be converted to ASCII 129. If you convert CF/LF then you can include them in your search with PowerHome escape characters ~128 and ~129 respectively.

Within each search pattern you may perform multiple searches by separating your search pattern using the PowerHome escape character ~255. This is most useful when CF/LF IS NOT replaced and trying to match a particular piece of data that spans multiple lines. If you do multiple searches, the last search is used as the starting position and ending position of the returned text.

This function is often used with other PH string functions to trim a larger string, or to locate a string position within another string. See also pos(), posw(), ph_pos(), left(), mid(), right().

See also the .FAQs-String Tips-Hints Help file.

Examples
The following examples demonstrate typical syntax/usage for this function.
The following examples assume that the following string (with CR/LF line enders) is stored in [LOCAL1]...
ROMId,Name, Value,Avg,
"3F000001CD92C728","Refrig",39.20,37.46,
"3F6000017C8BD128","Outside",23.90,19.81,
"3F000001CDB2BA27","House",70.65,70.13,
"3F000001CD9E6D28","Freezer",1.96,1.11,

The following command uses a CR/LF Flag of "0" to search only lines ...
ph_regexdiff ("ROMId,", ", Val", "[LOCAL1]", 1, 0 ) --> Finds Name

While this expression with the CR/LF Flag set to search thru everything (2) ...
ph_regexdiff ("ROMId,", ", Val", "[LOCAL1]", 1, 2 ) --> Finds all characters from "Name" to the ending comma after 1.11 (ie, Name ... 1.11,)

This ...
ph_regexdiff ('3F.+",', ',', '[LOCAL1]', 1,0 ) --> Finds 39.20

While ...
ph_regexdiff ('3F.+",', ',', '[LOCAL1]', 1,2 ) --> finds 1.96

====

More Examples: {Searching in LOCAL1}
ph_regexdiff ('2C728', '\<', '[LOCAL1]', 1,0 ) --> finds "," (Between ..C728 and Refrig..)
ph_regexdiff ('2C728', '\>', '[LOCAL1]', 1,0 ) --> finds ","Refrig
ph_regexdiff ('BA27...', "7", '[LOCAL1]', 1,0 ) --> finds House",
ph_regexdiff ('Refrig', "$", '[LOCAL1]', 1,0 ) --> finds ",39.20,37.46,
ph_regexdiff ("3F[0-9]+","R", "[LOCAL1]", 1,0 ) --> finds CD92C728","


ph_regexdiff1

ph_regexdiff1 PowerHome formula function
Description
Searches a string of data and returns the data between two regular expression searches.
Syntax
ph_regexdiff1 ( pat1, pat2, data, start, occ, flags, localstart, locallength )
Argument | Description
pat1 | String. The starting regular expression search pattern.
pat2 | String. The ending regular expression search pattern.
data | String. The string in which to perform the search.
start | Long. The position within the data in which to start the search. Use 1 to start at the beginning.
occ | Integer. The matching occurrence number to be returned. Use 1 to return the first matching occurrence. A 3 will return the third matching occurrence, etc.
flags | Integer. Flags that control how the search is performed. Add individual flag values together. Add 1 to cause the search to match case. Add 2 to cause the search to ignore cr/lf's within the data.
localstart | Integer. The index of a local variable in which to have the start (1st character) of the found data returned. Use 0 to not have the start returned.
locallength | Integer. The index of a local variable in which to have the length of thefound data returned. Use 0 to not have the length returned.
Return value
String. Returns the data string between the pat1 regular expression and pat2 regular expression.
Usage
Use this function for powerful text search capabilities. The regular expression special characters supported are:
. | Matches any character.
\< | This matches the start of a word, where a word is defined in the traditional sense, that is, letters, or number. Spaces, punctuation, CR/LF, etc. would not be included as part of a word, and thus create a break.
\> | This matches the end of a word. See also word definition above.
\x | This allows you to use a character x that would otherwise have a special meaning. For example, \[ would be interpreted as [ and not as the start of a character set.
[...] | This indicates a set of characters, for example, [abc] means any of the characters a, b or c. You can also use ranges, for example [a-z] for any lower case character.
[^...] | The complement of the characters in the set. For example, [^A-Za-z] means any character except an alphabetic character.
^ | This matches the start of a line (unless used inside a set, see above).
$ | This matches the end of a line.
* | This matches 0 or more times. For example, Sa*m matches Sm, Sam, Saam, Saaam and so on.
+ | This matches 1 or more times. For example, Sa+m matches Sam, Saam, Saaam and so on.

An important note on the special characters is that they can conduct a "greedy" regular expression search. When using the * and + special characters this function will not stop at the first match but will instead go to the last match.

NOTE: If a string contains any quote characters (") then the string must be delimited with the single quote charcter ('). For example... 'he said, "no"'

This function will also not perform a regular expression search that spans multiple lines. If the data to search contains carraige returns or line feeds, the entire matching search data for the regular expression must exist within a single line. If your regular expression must span across a line, then add 2 to the flags to have CR's and LF's temporarily converted. CR will be converted to ASCII 128 and LF will be converted to ASCII 129. If you convert CF/LF then you can include them in your search with PowerHome escape characters ~128 and ~129 respectively.

Within each search pattern you may perform multiple searches by separating your search pattern using the PowerHome escape character ~255. This is most useful when CF/LF IS NOT replaced and trying to match a particular piece of data that spans multiple lines. If you do multiple searches, the last search is used as the starting position and ending position of the returned text.

This function is often used with other PH string functions to trim a larger string, or to locate a string position within another string. See also pos(), posw(), ph_pos(), left(), mid(), right().

See also the .FAQs-String Tips-Hints Help file.

Examples
The following examples demonstrate typical syntax/usage for this function.
The following examples assume that the following string (with CR/LF line enders) is stored in [LOCAL1]...
ROMId,Name, Value,Avg,
"3F000001CD92C728","Refrig",39.20,37.46,
"3F6000017C8BD128","Outside",23.90,19.81,
"3F000001CDB2BA27","House",70.65,70.13,
"3F000001CD9E6D28","Freezer",1.96,1.11,

The following command extracts "92C"
ph_regexdiff1 ("3F~255D", "7", "[LOCAL1]", 1, 1,0,3,0 )

As does
ph_regexdiff1 ("3F.+D", "7", "[LOCAL1]", 1, 1,0,3,0 ) --> "92C"

But the following fails ...
ph_regexdiff1 ("3F.+D", "7", "[LOCAL1]", 1, 1,2,3,0 ) --> no match found
because the ignore Return character Flag is turned on (2) and the ".+" skips over all characters and will keep skipping thru lines until it finds the last "D" in the text. This occurs in the ROM ID in the last (Freezer) line of the string, but there is then no "7" following after the "D" so the search fails.

This extracts "39.20" ...
ph_regexdiff1 ('3F.+",', ',', '[LOCAL1]', 1, 1,0,3,0 )

But when the CR/LF Flag is set (2) then "1.96" is extracted in a "greedy" search ...
ph_regexdiff1 ('3F.+",', ',', '[LOCAL1]', 1, 1,2,3,0 )

====

Continuing with the same source data, the following syntax could be used to get the Outside data value (23.90) ...
ph_regexdiff1('Outside",',",","[LOCAL1]",[LOCAL3],1,0,0,0)

Which says to extract the string that is in-between Outside", and the next comma "," ...
Starting at the position in the LOCAL1 data indicated by the starting location in LOCAL3 (60)
Return the 1st matching occurance
No special flags required
LOCAL3 will now contain the Index# of the 1st match character, equal to 103
Do not return Length

This will return a value of of "23.90"

====

A more general way to extract the data that also allows a simple macro loop to get successive values is ...
ph_regexdiff1 ('3F~255","~255",', ",", "[LOCAL1]", 1, [LOCAL2], 2, 3, 0 ) --> {where LOCAL2 is incremented for loop control]

Which says to look thru all lines (CRLF Flag=2) to find the string bounded on the left by 3F...","...", and on the right by , (where ... stands for the Escape character ) ..
( These bounding strings are highlighted in this sample line ... "3F000001CD92C728","Refrig",39.20,37.46, ) {red=match; grn=escape over}
Using the "occurrence" parameter (LOCAL2 above) in a loop to set which match occurrence we want, will can select each of the four values in turn.

====

More Examples: (LOCAL1 contains the text to be searched)
NOTE: The regular expression engine will only search for a match on its regex search string within the confines of a single line.
If the data contains multiple lines, the search is performed on EACH line until a match is found.

If the sought string is all on one line then CRLFs make no practical difference, but if the sought string covers multiple lines then either the ~255 escape character must be used to span line endings or the replace CRLF flag must set set on in order to find a match.
ph_regexdiff1 ("3F~255D", "7", "[LOCAL1]", 1, 1,0,3,0 ) --> finds 92C
ph_regexdiff1 ("3F.+D", "7", "[LOCAL1]", 1, 1,0,3,0 ) --> finds 92C
ph_regexdiff1 ("3F~255D", "7", "[LOCAL1]", 1, 1,0,3,0 ) --> finds 92C
ph_regexdiff1 ('3F.+",', ',', '[LOCAL1]', 1, 1,2,3,0 ) --> finds 1.96 by greed
ph_regexdiff1 ('Outside",',",", "[LOCAL1]", 1, 1,0,3,0 ) --> finds 23.90 --> NOTE that the first parameter (Outside) contained a " thus a single quote(') had to be used to delineate the parameter.
ph_regexdiff1 ('3F.+",', ',', '[LOCAL1]', 1, 1,2,3,0 ) --> finds ",23
ph_regexdiff1 ('3F.+",', ',', '[LOCAL1]', 1, 1,0,3,0 ) --> fails because "the ignore CRLF is not set" and the .+ search will not work across multiple lines.
ph_regexdiff1 ('3F~255",', ',', '[LOCAL1]', 1, 1,0,3,0 ) -->finds ",23 as the escape (~255) ignores CRLF line breaks.
ph_regexdiff1 ("ROMId,", ", Val", "[LOCAL1]", 1, 1,0,3,0 ) --> finds Name
ph_regexdiff1 ("ROMId,", "\>", "[LOCAL1]", 1, 1,0,3,0 ) --> finds Name
ph_regexdiff1 ("R", "\>", "[LOCAL1]", 1,2,0,3,2 ) --> finds efrig


ph_regexdiff2

ph_regexdiff2 PowerHome formula function
Description
Searches a string of data and returns the data between two regular expression searches.
Syntax
ph_regexdiff2 ( pat1, pat2, data, start, occ, flags, localstart, locallength )
Argument | Description
pat1 | String. The starting regular expression search pattern.
pat2 | String. The ending regular expression search pattern.
data | String. The string in which to perform the search.
start | Long. The position within the data in which to start the search. Use 1 to start at the beginning.
occ | Integer. The matching occurrence number to be returned. Use 1 to return the first matching occurrence. A 3 will return the third matching occurrence, etc.
flags | Integer . Flags that control how the search is performed. Set this value to 1 in order to match case. Use 0 for case insensitive searches.
localstart | Integer. The index of a local variable in which to have the start (1st character) of the found data returned. Use 0 to not have the start returned.
locallength | Integer. The index of a local variable in which to have the length of thefound data returned. Use 0 to not have the length returned.
Return value
String. Returns the data string between the pat1 regular expression and pat2 regular expression.
Usage
This function is nearly identical to the ph_regexdiff1 function except it uses the regular expression engine in the Microsoft VBScript library vs the Scintilla editor regular expression engine used by the ph_regexdiff1 function.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_regexdiff2("<span>","</span>",ph_readfile("c:\powerhome\weather.txt"),4,0,0,0)
The above example will return the text that appears between the 4th occurence of span tags in the c:\powerhome\weather.txt file.


ph_regexsnap

ph_regexsnap PowerHome formula function
Description
Performs a regular expression search and snaps specific pieces of data out.
Syntax
ph_regexsnap ( pattern, data, start, flags )
Argument | Description
pattern | String. A regular expression search pattern containing tagged regions of (up to 9) that you want snapped out and returned.
data | String. The string in which to perform the search and snap.
start | Long. The starting postion of the search. Use 1 to start at the beginning.
flags | Integer. Flags that control how the search is performed. Add individual flag values together. Add 1 to cause the search to match case. Add 2 to cause the search to ignore cr/lf's within the data.
Return value
String. Returns the snapped data from the searched string.
Usage
Use this function for powerful text search capabilities. The regular expression special characters supported are:

. | Matches any character.
\( | This marks the start of a region for tagging a match.
\) | This marks the end of a tagged region.
\< | This matches the start of a word.
\> | This matches the end of a word.
\x | This allows you to use a character x that would otherwise have a special meaning. For example, \[ would be interpreted as [ and not as the start of a character set.
[...] | This indicates a set of characters, for example, [abc] means any of the characters a, b or c. You can also use ranges, for example [a-z] for any lower case character.
[^...] | The complement of the characters in the set. For example, [^A-Za-z] means any character except an alphabetic character.
^ | This matches the start of a line (unless used inside a set, see above).
$ | This matches the end of a line.
* | This matches 0 or more times. For example, Sa*m matches Sm, Sam, Saam, Saaam and so on.
+ | This matches 1 or more times. For example, Sa+m matches Sam, Saam, Saaam and so on.

An important note on the special characters is that they can conduct a "greedy" regular expression search. When using the * and + special characters this function will not stop at the first match but will instead go to the last match.

NOTE: If a string contains any quote characters (") then the string must be delimited with the single quote charcter ('). For example... 'he said, "no"'

This function will also not perform a regular expression search that spans multiple lines. If the data to search contains carraige returns or line feeds, the entire matching search data for the regular expression must exist within a single line. If your regular expression must span across a line, then add 2 to the flags to have CR's and LF's temporarily converted. CR will be converted to ASCII 128 and LF will be converted to ASCII 129. If you convert CF/LF then you can include them in your search with PowerHome escape characters ~128 and ~129 respectively. NOTE however that replacing CR/LFs will slow down searches significantly as, before the search can even be started, the entire string must be examaned character-by-character and the replacments made as needed. It is thus preferable to use the escape (~255) character, rather than (.+) and CR/LF replacement, where possible.

The ~255 approach allows you to perform multiple searchs within your search pattern (even across multiple lines). Only the last search, of multiple, can be used for Returning "snapped" data. NOTE: the ~255 character is NOT a part of the regular expression syntax and is strictly a PH special creation to separate regex searches. The \( and \) regex characters are a pair that MUST go together, so a non-regex character expression should never be inserted between them.

The regexsnap function is similar to the ph_regexdiff function in that it uses regular expressions to search and return data within the searched string. Instead of returning data between two regular expressions (like ph_regexdiff), this function uses the \( and \) to mark tagged regions. You may have up to 9 tagged regions in the last search pattern. All matched text within the tagged regions will be "snapped out" and returned by this function.

This function is often used with other PH string functions to trim a larger string, or to locate a string position within another string. See also pos(), posw(), ph_pos(), left(), mid(), right().

See also the .FAQs-String Tips-Hints Help file.

Examples
The following examples demonstrate typical syntax/usage for this function.
The following examples assume that the following string (with CR/LF line enders) is stored in [LOCAL1]...
ROMId,Name, Value,Avg,
"3F000001CD92C728","Refrig",39.20,37.46,
"3F6000017C8BD128","Outside",23.90,19.81,
"3F000001CDB2BA27","House",70.65,70.13,
"3F000001CD9E6D28","Freezer",1.96,1.11,

The following command ...
ph_regexsnap('ROM~255,\(.+,\)', '[LOCAL1]', 1, 0 ) --> finds Name, Value,Avg,
because the ".+," search is greedy and doesn't quit until it finds the last ","

While ...
ph_regexsnap('ROM~255,\(.+,\)', '[LOCAL1]', 1, 2 ) --> finds everything from Name to .... 6D28","Freezer",1.96,1.11,
because the ignore CR/LF Flag is set so the extraction keeps going across multiple lines until it finds the last comma.

Because of this "greediness," regsnap is thus not easily used in some situations and the regexdiff family is more useful. However, when you are assured of finding unique strings to bound the search, then regexsnap can be very powerful, while easy to use.

This ...
ph_regexsnap('ROM~255,\(....\)', '[LOCAL1]', 1, 0 ) --> finds Name
since the "...." accepts any 4 characters after the comma.

A good example to explain the use of ~255 is extracting weather data.

Consider the following data which may have been returned by a ph_geturl() function (the data is simplified of course):

<html>
<body>
<h4>Temperature</h4>
<b>78.5</b>
<h4>Humidity</h4>
<b>55.7</b>
<h4>Wind Speed</h4>
<b>7.5</b>
</body>
</html>

Without the ~255, this data would be difficult to parse (like retrieving the value for humidity) unless you substituted the CR/LF (which we never want to do if we can help it). Since a regex can only be performed on a single line, the best we could do is search for the second occurrence of the <b></b> tags which will work for this data but if they added a new parameter, then this would fail.

Using the ~255 we can do a regexsnap to retrieve humidity like this...

ph_regexsnap("Humidity~255<b>\(.+\)</b>",'[LOCAL1]',1,0) {where the ~255 causes the characters in green above to be skipped over, and the red characters to be extracted.}

The statement above will always return the value between the first <b></b> tags following the word Humidity. Of course, we have to remember the regex is greedy so we need to be careful with the ".+". If there are multiple <b></b> tags on the same line, we would get more than we expected. Since we know the humidity value will only be numbers and a decimal, we could error proof the above a little more with this:

ph_regexsnap("Humidity~255<b>\([0-9\.]*\)</b>",'[LOCAL1]',1,0)


ph_regexsnap1

ph_regexsnap1 PowerHome formula function
Description
Performs a regular expression search and snaps specific pieces of data out.
Syntax
ph_regexsnap1 ( pattern, snap, data, start, occurrence, flags, localstart, locallength )
Argument | Description
pattern | String. A regular expression search pattern containing tagged regions of (up to 9) that you want snapped out and returned.
snap | String. A regular expression snap pattern containing the snapped regions of text along with other desired text.
data | String. The string in which to perform the search and snap.
start | Long. The starting postion of the search. Use 1 to start at the beginning.
occurrence | Integer. The matching occurrence number to be returned. Use 1 to return the first matching occurrence. A 3 will return the third matching occurrence, etc.
flags | Integer. Flags that control how the search is performed. Add individual flag values together. Add 1 to cause the search to match case. Add 2 to cause the search to ignore cr/lf's within the data.
localstart | Integer. The index of a local variable in which to have the start of the found data returned. Use 0 to not have the start returned.
locallength | Integer. The index of a local variable in which to have the length of the found data returned. Use 0 to not have the length returned.
Return value
String. Returns the snapped data formatted per the snap parameter.
Usage
Use this function for powerful text search capabilities. The regular expression special characters supported are:

. | Matches any character.
\( | This marks the start of a region for tagging a match.
\) | This marks the end of a tagged region.
\< | This matches the start of a word.
\> | This matches the end of a word.
\x | This allows you to use a character x that would otherwise have a special meaning. For example, \[ would be interpreted as [ and not as the start of a character set.
[...] | This indicates a set of characters, for example, [abc] means any of the characters a, b or c. You can also use ranges, for example [a-z] for any lower case character.
[^...] | The complement of the characters in the set. For example, [^A-Za-z] means any character except an alphabetic character.
^ | This matches the start of a line (unless used inside a set, see above).
$ | This matches the end of a line.
* | This matches 0 or more times. For example, Sa*m matches Sm, Sam, Saam, Saaam and so on.
+ | This matches 1 or more times. For example, Sa+m matches Sam, Saam, Saaam and so on.
\1 - \9 | Use this only within the snap parameter. These tags represent the up to 9 snapped regions.

An important note on this function is that it is a "greedy" regular expression search. When using the * and + special characters this function will not stop at the first match but will instead go to the last match.

This function will also not perform a regular expression search that spans multiple lines. If the data to search contains carraige returns or line feeds, the entire matching search data for the regular expression must exist within a single line. If your regular expression must span across a line, then add 2 to the flags to have CR's and LF's temporarily converted. CR will be converted to ASCII 128 and LF will be converted to ASCII 129. If you convert CF/LF then you can include them in your search with PowerHome escape characters ~128 and ~129 respectively.

You may perform multiple searchs within your search pattern by separating your searchs with the PowerHome escape character ~255. Only the last search will be used for "snapping" data for return.

This function is similar to the ph_regexdiff function in that it uses regular expressions to search and return data within the searched string. Instead of returning data between two regular expressions (like ph_regexdiff), this function uses the \( and \) to mark tagged regions. You may have up to 9 tagged regions in the last search pattern. All matched text within the tagged regions will be "snapped out" and formatted according to the snap parameter and then returned by this function.


ph_regexsnap2

ph_regexsnap2 PowerHome formula function
Description
Performs a regular expression search against a string of data and snaps specific pieces of data out.
Syntax
ph_regexsnap2 ( pattern, data, start, occur, flags, localsnapcnt, localsnapvars )
Argument | Description
pattern | String. A regular expression search pattern. The pattern should contains snap patterns. A snap pattern is a portion of a regular expression contained within open and close parenthesis "(" and ")".
data | String. The string in which to perform the search.
start | Long. The position within the data in which to start the search. Use 1 to start at the beginning.
occur | Integer. The occurence of the match you'd like returned. If a file contains multiple matches and this value is 3, then the 3rd matching occurence will be returned.
flags | Integer . Flags that control how the search is performed. Set this value to 1 in order to match case. Use 0 for case insensitive searches.
localsnapcnt | Integer . The index of a local variable in which to have the count of snapped items returned. Use 0 to not have the count returned.
localsnapvars | Ingeger . The starting index of a local variable in which to have the individual snaps returned. If there are 3 snaps to return and this parameter is set to 5, then the snaps will be returned in [LOCAL5], [LOCAL6], and [LOCAL7]. Use 0 to not have the snaps returned in local variables.
Return value
String. Returns the snapped expressions.
Usage
This function is very similar to the ph_regexsnap1 function except that it uses the regular expression engine contained within the Microsoft VBScript library. The ph_regexsnap1 function uses the open source Scintilla editor to perform regular expression searches which is more limited in options and capabilities.

The full documentation for this regular expression library is way too much information for this help file. Please reference this site for a very good reference and tutorial for utilizing the Microsoft VBScript regular expression library: http://www.regular-expressions.info/vb.html
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_regexsnap2("def([\S\s]*)mn","abcdefghijklmnopqrstuvwxyz",1,1,0,0,0)
The above example will return "ghijkl".


ph_regexsnap3

ph_regexsnap3 PowerHome formula function
Description
Another function for using Regular Expressions to search for and "snap" (extract) data from a source. This version of the function uses C#.net regular expressions to perform the desired actions
Syntax
ph_regexsnap3 ( as_pattern, as_snap, as_data, al_start, ai_occurence, ai_flags, ai_localstart, ai_locallength )
Argument | Description
as_pattern | String. The regular expression pattern to search and snap data
as_snap | String. The snap pattern that dictates how the snapped data is returned. Use an empty string "" to just return all matches concatenated together
as_data | String. The data you wish to perform the regular expression search and snap on
al_start | Long. The starting position in the data at which the regular expression search will start. Use 1 to start searching at the beginning
ai_occurence | Integer. The occurence of the particular data you wish to match. In a given as_data string, there may be multiple matches for a particular regular expression search. This parameter allows you to define which particular matching instance you would like to work with. Use a value of 1 to use the first instance. To return ALL instances, use a value of 0
ai_flags | Integer. A flags parameter that controls how the regular expression is performed. See Usage below for details
ai_localstart | Integer. The index of a local variable in which to store the start of data that is matched by the regular expression. Use 1 thru 10 for [LOCAL1] thru [LOCAL10]. If you don't want the start position stored in a local variable, use 0
ai_locallength | Integer. The index of a local variable in which to store the length of data that is matched by the regular expression. Use 1 thru 10 for [LOCAL1] thru [LOCAL10]. If you don't want the length of matched data stored in a local variable, use 0
Return value
String. Returns the requested "snapped" data based upon the snap pattern in the as_snap parameter.
Usage
Use this function to search a string for patterns of characters and return desired extracted portions of the matched search. Very useful for parsing HTML data returned by a ph_geturl1( ) function. This function can be used to just find the starting position and length of matched data for a particular occurrence or it can be used to extract portions of data that are searched for. A very good reference for the C# regular expressions that this function uses can be found here: https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference

To extract (or "snap") portions of a regex match, a "capturing" group is specifed in the as_pattern parameter. A capturing group is defined by enclosing the portion of the regular expression search you wish to capture in open "(" and close ")" parenthesis. To specify how the extraction is built into the return string, the as_snap pattern allows you to reference the capturing groups (numbered from left to right in the order that they appear in as_pattern starting with 1) by prefixing the capture group number with a dollar sign "$" character. You can also include additional text to separate or otherwise delimit the captured entries. A simple snap pattern to return the #1 capture group with a colon surrounded by space characters as a delimiter would be: "$1 : "

The ai_flags parameter controls how the regular expression search is done. The value for each desired option below would be added together to arrive at the proper ai_flags value. If none of the additional options are required, then use an ai_flags value of 0. For a detailed explanation of eachof the options, see this link: https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regexoptions?view=netcore-3.1

  • 1 - Ignore Case
  • 2 - Multiline
  • 4 - Explicit Capture
  • 8 - Compiled
  • 16 - Single Line
  • 32 - Ignore Pattern Whitespace
  • 64 - Right to Left
  • 256 - ECMA Script
  • 512 - Culture Invariant
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_regexsnap3("([a-f]+)","","This is a bc test def",1,0,0,1,2) - Returns "abcedef". [LOCAL1] will contain the value 9 (the start position of the first match) and [LOCAL2] will contain the value 1 (the length of the first match)
    . ph_regexsnap3("([a-f]+)","","This is a bc test def",1,2,0,1,2) - Returns "bc". [LOCAL1] will contain the value 11 (the start position of the requested second match) and [LOCAL2] will contain the value 2 (the length of the requested second match)
    . ph_regexsnap3("([a-f]+)","($1)","This is a bc test def",1,0,0,1,2) - Returns "(a)(bc)(e)(def)". [LOCAL1] will contain the value 9 (the start position of the first match) and [LOCAL2] will contain the value 1 (the length of the first match)


ph_replaceallregex

ph_replaceallregex PowerHome formula function
Description
Performs a regular expression search and replace on all occurences within a string of data.
Syntax
ph_replaceallregex ( pattern, replace, data, flags )
Argument | Description
pattern | String. A regular expression search pattern.
replace | String. A regular expression replacement pattern.
data | String. The string in which to perform the search and replace.
flags | Integer. Flags that control how the search is performed. Add individual flag values together. Add 1 to cause the search to match case. Add 2 to cause the search to ignore cr/lf's within the data.
Return value
String. Returns the data string with the appropriate replacements performed.
Usage
Use this function for powerful text search and replace capabilities. The regular expression special characters supported are:

. | Matches any character.
\( | This marks the start of a region for tagging a match.
\) | This marks the end of a tagged region.
\n | Where n is 1 through 9 refers to the first through ninth tagged region when replacing. For example, if the search string was Fred\([1-9]\)XXX and the replace string was Sam\1YYY, when applied to Fred2XXX this would generate Sam2YYY.
\< | This matches the start of a word.
\> | This matches the end of a word.
\x | This allows you to use a character x that would otherwise have a special meaning. For example, \[ would be interpreted as [ and not as the start of a character set.
[...] | This indicates a set of characters, for example, [abc] means any of the characters a, b or c. You can also use ranges, for example [a-z] for any lower case character.
[^...] | The complement of the characters in the set. For example, [^A-Za-z] means any character except an alphabetic character.
^ | This matches the start of a line (unless used inside a set, see above).
$ | This matches the end of a line.
* | This matches 0 or more times. For example, Sa*m matches Sm, Sam, Saam, Saaam and so on.
+ | This matches 1 or more times. For example, Sa+m matches Sam, Saam, Saaam and so on.

An important note on this function is that it is a "greedy" regular expression search. When using the * and + special characters this function will not stop at the first match but will instead go to the last match.

This function will also not perform a regular expression search that spans multiple lines. If the data to search contains carraige returns or line feeds, the entire matching search data for the regular expression must exist within a single line. If your regular expression must span across a line, then add 2 to the flags to have CR's and LF's temporarily converted. CR will be converted to ASCII 128 and LF will be converted to ASCII 129. If you convert CF/LF then you can include them in your search with PowerHome escape characters ~128 and ~129 respectively.

You may perform multiple search and replaces by separating your search and replace patterns with the PowerHome escape character ~255. If you have more searches than replaces then the last replace pattern will be used for the remaining searches.

You may also perform multiple searches within a single search pattern section by separating your searchs using the PowerHome escape character ~254. If you do multiple searches, then replacement will only be performed on the last search within a search pattern section.


ph_replaceallregex3

ph_replaceallregex3 PowerHome formula function
Description
Uses C# regular expressions to replace ALL occurences of matches within a string of data
Syntax
ph_replaceallregex3 ( as_pattern, as_replace, as_data, ai_flags )
Argument | Description
as_pattern | String. The regular expression pattern to match which may include capturing groups
as_replace | String. The replace (substitution) pattern to apply to matches from as_pattern
as_data | String. The string of data on which to perform the regular expression operations
ai_flags | Integer. A flags parameter that controls how the regular expression is processed. See Usage below for details
Return value
String. Returns the as_data parameter with matches appropriately substituted based upon the replace pattern
Usage
Use this function to search and replace data within a supplied string using C# regular expression operations as the basis of the search and replacement. See this link for an explanation on regular expression substitutions: https://docs.microsoft.com/en-us/dotnet/standard/base-types/substitutions-in-regular-expressions

The ai_flags parameter controls how the regular expression search is done. The value for each desired option below would be added together to arrive at the proper ai_flags value. If none of the additional options are required, then use an ai_flags value of 0. For a detailed explanation of eachof the options, see this link: https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regexoptions?view=netcore-3.1

  • 1 - Ignore Case
  • 2 - Multiline
  • 4 - Explicit Capture
  • 8 - Compiled
  • 16 - Single Line
  • 32 - Ignore Pattern Whitespace
  • 64 - Right to Left
  • 256 - ECMA Script
  • 512 - Culture Invariant
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_replaceallregex3("[^a-f]*([a-f]+)[^a-f]*","$1","This is a bc test def",0) - Returns "abcedef". This example searches for any characters that are not "a" thru "f" and matches those. When any character that matches "a" thru "f" is encountered, it is then identified in the capturing group that is surrounded by "(" and ")" characters. This is capture group 1. This is followed by matching any characters that are not "a" thru "f". In regular expression processing, "This is " is matched by the section of the regular expression that is any character that is not "a" thru "f". The next character "a" is matched by the capturing group. The space character following the "a" is matched by the section following the capturing group that is match any character that is not "a" thru "f". The "bc" following this space does not match so the entire matched string is now replaced according to the as_replace pattern "$1" which says to replace the entire matched section, which in this case is "This is a ", with capture 1, which is "a". This process repeats itself until all of as_data has been matched/replaced.
    . ph_replaceallregex3("[a-f]+","*","This is a bc test def",0) - Returns "This is * * t*st *". This example does not specify a capturing group in the as_pattern regular expression and instead only matches on one or more characters that match "a" thru "f". Whenever a match is encountered, it is replaced by an asterisk "*" character. Non matching characters are ignored which means they will NOT be replaced and will instead be part of the returned string.


ph_replaceregex

ph_replaceregex PowerHome formula function
Description
Performs a regular expression search and replace on a string of data.
Syntax
ph_replaceregex ( pattern, replace, data, start, flags, localstart, locallength, localreplength )
Argument | Description
pattern | String. A regular expression search pattern.
replace | String. A regular expression replacement pattern.
data | String. The string in which to perform the search and replace.
start | Long. The position within the data in which to start the search. Use 1 to start at the beginning.
flags | Integer. Flags that control how the search is performed. Add individual flag values together. Add 1 to cause the search to match case. Add 2 to cause the search to ignore cr/lf's within the data.
localstart | Integer. The index of a local variable in which to have the start of the found data returned. Use 0 to not have the start returned.
locallength | Ingeger. The index of a local variable in which to have the length of the found data returned. Use 0 to not have the length returned.
localreplength | Ingeger. The index of a local variable in which to have the replacement length of the found data returned. Use 0 to not have the replacement length returned.
Return value
String. Returns the data string with the appropriate replacements performed.
Usage
Use this function for powerful text search and replace capabilities. The regular expression special characters supported are:

. | Matches any character.
\( | This marks the start of a region for tagging a match.
\) | This marks the end of a tagged region.
\n | Where n is 1 through 9 refers to the first through ninth tagged region when replacing. For example, if the search string was Fred\([1-9]\)XXX and the replace string was Sam\1YYY, when applied to Fred2XXX this would generate Sam2YYY.
\< | This matches the start of a word.
\> | This matches the end of a word.
\x | This allows you to use a character x that would otherwise have a special meaning. For example, \[ would be interpreted as [ and not as the start of a character set.
[...] | This indicates a set of characters, for example, [abc] means any of the characters a, b or c. You can also use ranges, for example [a-z] for any lower case character.
[^...] | The complement of the characters in the set. For example, [^A-Za-z] means any character except an alphabetic character.
^ | This matches the start of a line (unless used inside a set, see above).
$ | This matches the end of a line.
* | This matches 0 or more times. For example, Sa*m matches Sm, Sam, Saam, Saaam and so on.
+ | This matches 1 or more times. For example, Sa+m matches Sam, Saam, Saaam and so on.

An important note on this function is that it is a "greedy" regular expression search. When using the * and + special characters this function will not stop at the first match but will instead go to the last match.

This function will also not perform a regular expression search that spans multiple lines. If the data to search contains carraige returns or line feeds, the entire matching search data for the regular expression must exist within a single line. If your regular expression must span across a line, then add 2 to the flags to have CR's and LF's temporarily converted. CR will be converted to ASCII 128 and LF will be converted to ASCII 129. If you convert CF/LF then you can include them in your search with PowerHome escape characters ~128 and ~129 respectively.

You may also perform multiple searches by separating your search pattern using the PowerHome escape character ~255. This is most useful when CF/LF IS NOT replaced and trying to match a particular piece of data. If you do multiple searches, then replacement will only be performed on the last search.


ph_replaceregex3

ph_replaceregex3 PowerHome formula function
Description
Uses C# regular expressions to selectively match and replace elements within the supplied input string
Syntax
ph_replaceregex3 ( as_pattern, as_replace, as_data, al_start, al_occur, ai_flags, ai_localstart, ai_locallength, ai_localreplength )
Argument | Description
as_pattern | String. The regular expression pattern to match
as_replace | String. The replace (substitution) pattern to replace matches with
as_data | String. The input string of data you wish to perform regular expression search/replace operations on
al_start | Long. The starting position in which to apply the regular expression search pattern. Use 1 to start at the first character
al_occur | Long. The number of search and replacements you would like to perform. To perform all possible replacements, use 0. To perform only a single search and replacement, use 1, etc. Note that this parameter is different from the other RegEx3 functions in that it specifies how many times to do a search and replace operation rather than specifying to do a search and replace only on a particular occurence.
ai_flags | Integer. A flags parameter that controls how the regular expression is performed
ai_localstart | Integer . The index of a local variable in which to store the start of data that is matched and replaced by the regular expression. Use 1 thru 10 for [LOCAL1] thru [LOCAL10]. If you don't want the start position stored in a local variable, use 0. This parameter is ONLY relevant if the al_occur parameter is 1. Any other value for al_occur will return a 0 in the specified LOCAL variable
ai_locallength | Integer . The index of a local variable in which to store the length of data that is matched by the regular expression before replacement. Use 1 thru 10 for [LOCAL1] thru [LOCAL10]. If you don't want the length of matched data stored in a local variable, use 0. This parameter is ONLY relevant if the al_occur parameter is 1. Any other value for al_occur will return a 0 in the specified LOCAL variable
ai_localreplength | Integer . The index of a local variable in which to store the length of the replacement data that was performed by the regular expression. Use 1 thru 10 for [LOCAL1] thru [LOCAL10]. If you don't want the replacement length of matched data stored in a local variable, use 0. This parameter is ONLY relevant if the al_occur parameter is 1. Any other value for al_occur will return a 0 in the specified LOCAL variable
Return value
String. Returns the as_data input string after the appropriate search and replacements have been performed
Usage
Use this function to search and replace data within a supplied string using C# regular expression operations as the basis of the search and replacement. See this link for an explanation on regular expression substitutions: https://docs.microsoft.com/en-us/dotnet/standard/base-types/substitutions-in-regular-expressions

This function is useful for search and replacement using regular expressions when you want a finer level of control instead of just performing a brute force search and replace ALL using the ph_replaceallregex3( ) function. You can still achieve the same effect as ph_replaceallregex3 by setting the al_occur parameter to 0 albeit you'll have to supply all the other parameters required by this function

The ai_flags parameter controls how the regular expression search is done. The value for each desired option below would be added together to arrive at the proper ai_flags value. If none of the additional options are required, then use an ai_flags value of 0. For a detailed explanation of eachof the options, see this link: https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regexoptions?view=netcore-3.1

  • 1 - Ignore Case
  • 2 - Multiline
  • 4 - Explicit Capture
  • 8 - Compiled
  • 16 - Single Line
  • 32 - Ignore Pattern Whitespace
  • 64 - Right to Left
  • 256 - ECMA Script
  • 512 - Culture Invariant
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_replaceregex3(" [a-f]+[^a-f]*","*XX*","abc This is a bc test def",1,0,0,1,2,3) - Returns "abc This is*XX*bc test*XX*". This example searches for any occurence of one more letters of "a" thru "f" following a space and itself being followed by 0 or more characters that are not "a" thru "f". All searches that match this criteria are replaced with the string "*XX*". The first "abc" is not replaced because it was not preceeded by a space character. The " a " in "This is a " matches the search pattern (space followed by 1 or more a-f characters followed by 0 or more characters other than a-f) and so is replaced. The "bc" is NOT matched because the space character that preceeded it was no longer there as it had been replaced by the "*XX*" in the prior match so it is skipped. The "e" in "test" is also not matched due to the lack of a space character. The final " def" is matched and is thus replaced. The [LOCAL1], [LOCAL2], and [LOCAL3] variables will all contain 0 because the al_occur parameter is NOT equal to 1


ph_run

ph_run PowerHome formula function
Description
Execute a program
Syntax
ph_run ( filespec )
Argument | Description
filespec | String representing the full path and filename of the program to be executed. Command line parameters can be included within this string.
Return value
Integer. Returns a 1 if successful and -1 if an error occurs.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_run("C:\powerhome\findMyPhone.exe 192.168.1.92 C:/powerhome/findMyPhone.txt")
• ph_run("C:\powerhome\jsonBI.exe login http://192.168.1.90:1002/json login password; camconfig pause ThtrCam -1") { Includes Command LIne Parameters (from the "/" on) }


ph_run1

ph_run1 PowerHome formula function
Description
Uses a C# process control to execute/open files with a variety of options including launching as a specific user.
Syntax
ph_run1 (as_appl)
ph_run1 (as_appl, al_timeout)
ph_run1 (as_appl, al_timeout, ai_flags)
ph_run1 (as_appl, as_arg, as_currdir, al_timeout, ai_flags)
ph_run1 ( as_appl, as_arg, as_currdir, as_user, as_pass, al_timeout, ai_flags )
Argument | Description
as_appl | String. The application, file, or hyperlink you wish to launch or open
as_arg | String. Optional arguments to be passed on the command line to application in as_appl. Use an empty string "" if you have no arguments
as_currdir | String. Set the current default directory for the process that is launched. Use an empty string "" if you don't wish to change the default directory
as_user | String. An optional username to launch the process under. To use the current user that PowerHome is running under, use an empty string ""
as_pass | String. An optional password for the as_user parameter to launch the process under. If you are not launching as a specific user, set this parameter to empty string ""
al_timeout | Long. The number of milliseconds to wait for the process to finish if launching the process synchronously. Use 0 to wait indefinitely until the process finishes. If the function syntax you're using includes the ai_flags parameter it must have the value 64 added to it for this parameter to have any effect.
ai_flags | Integer. A flags parameter that controls how the process or file is to be launched. Individual options are added together. See Usage below for details
Return value
Long. If the process is launched asynchronously, the return value will be 0 if the function is successful and -1 if the function failed. If a -2 is returned, an exception occurred. You can retrieve the details of the exception by immediately calling the ph_lasterrorstring( ) function (note that the ph_lasterror( ) function is NOT updated by this function). If the function is launched synchronously, then the return value will be the exitcode generated by the process that was launched.
Usage
Use this function to launch/execute/open files, hyperlinks, and programs with a variety of options including launching as a specific user, hidden, without a visible window, etc. This single function with it's various overloads and options can effectively replace the following PowerHome functions: ph_run( ), ph_runasuser( ), ph_runasuser1( ), ph_runsync( ), and ph_runsync1( ) and will be deprecated at a later date.

Below are the values available for the ai_flags parameter. Add each value together for each desired option. See notes below as some options together will not work:

  • 0 - Window Style Normal
  • 1 - Window Style Maximized
  • 2 - Window Style Minimized
  • 4 - Window Style Hidden
  • 8 - Create No Window
  • 16 - Use Shell Execute
  • 32 - Hide Window after opening
  • 64 - Wait for process to finish

  • For the first 4 options (values 0, 1, 2, 4), you should choose only 1 value as the Window Style can only have one state. If you do add more than one Window Style value together, the higher value will win.
  • Option value 4 (Window Style Hidden) has no effect unless you also include option value 16 (Use Shell Execute). Similarly, option value 8 (Create No Window) has no effect if option value 16 (Use Shell Execute).
  • If the goal is to have the process window completely hidden, you need to have the ai_flags parameter contain both 4 + 16 or contain just 8 without 16. Using the 4 + 16 option has a higher success rate of hiding the window instead of just using 8 alone. Both methods will hide a cmd.exe window.
  • Option value 32 (Hide Window after opening) will work either with option 16 or without but the window will briefly flash open before being hidden.
  • If you wish to open a non-executable file or hyperlink using the default application assigned to the type, you must include option value 16 (Use Shell Execute)
  • if you have a process execute as a specific user and provide values for the as_user and as_pass parameters, you must NOT include option value 16 (Use Shell Execute). If you do, an exception will occur resulting in a return value of -2
  • Option value 8 (Create No Window) has no effect if option value 16 (Use Shell Execute) is included -OR- if you specify a userid and password to run the process as a specific user. If you need to run the process as a different user, the closest you can get to hiding the window is to include option value 32 (Hide Window after opening). You'll get a brief flash but the window will be immediately hidden

    The first four function overloads are detailed below:

  • ph_run1 (as_appl) - Supplies an empty string for the as_args, as_currdir, as_user, and as_pass parameters. The ai_flags parameter is 16 and al_timeout is 0
  • ph_run1 (as_appl, al_timeout) - Supplies an empty string for the as_args, as_currdir, as_user, and as_pass parameters. The ai_flags parameter is 80 (16 + 64)
  • ph_run1 (as_appl, al_timeout, ai_flags) - Supplies an empty string for the as_args, as_currdir, as_user, and as_pass parameters
  • ph_run1 (as_appl, as_arg, as_currdir, al_timeout, ai_flags) - Supplies an empty string for the as_user and as_pass parameters
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_run1("http://www.google.com") - Returns 0 if successful. This example opens the default browser and launches the www.google.com website. This works because the ai_flags parameter for this overload is 16
    . ph_run1("c:\powerhome\phtest.bat") - Returns 0 if successful. This example opens a cmd.exe window and then launches the phtest.bat batch file. The window will be visible.
    . ph_run1("c:\powerhome\phtest.bat",0,4 + 16) - Returns 0 if successful. This example is the same as the previous one except that the window will be hidden
    . ph_run1("cmd.exe","c:\powerhome\phtest.bat","",0,8) - Returns 0 if successful. This example is basically the same as the previous one except that "Use Shell Execute" is not used. Because shell execute is not used, we cant directly open the batch file and instead have to pass it as an argument to cmd.exe
    . ph_run1("c:\powerhome\phtest.bat","","","","",2000,4 + 16 + 64) - Opens cmd.exe as a hidden window and executes the phtest.bat batch file. PowerHome will wait for the batch file to terminate and will return the exitcode from the batch file if one is supplied. If the batch file does not complete within 2 seconds, control is returned to PowerHome and a -2 (exception) will be returned. If ph_lasterrorstring( ) is called, it will state that the process did not yet finish. Note that the as_args, as_currdir, as_user, and as_pass parameters are all blank so we could have used one of the function overloads


ph_runasuser

ph_runasuser PowerHome formula function
Description
Executes an application as a specific user.
Syntax
ph_runasuser ( domain, user, pass, appl, currdir, vis, async, wait )
Argument | Description
domain | String. The domain of the userid you're attempting to run as. Typically you would enter an empty string unless you're trying to authenticate over a corporate network.
user | String. The userid to run the program as.
pass | String. The password for the userid.
appl | String. The full path and filename of the application to execute.
currdir | String. The default directory you wish the application to start from.
vis | Integer. Whether the application should be visible or not. Use 0 for the app to run in the background without a visible window. Use 1 to run the application normally.
async | Integer. Whether the application runs asynchronously or not. Use 0 to run the app synchronously and have PowerHome wait until the app completes or the wait parameter is exceeded. Use 1 to have the app run asynchronously and return control immediately to PowerHome.
wait | Long. The time in milliseconds to wait for an app that is run synchronously (async parameter is 0) to complete. If the app is not done within the specified time, the function will return. Use a negative value in order to wait indefinitely.
Return value
Long. Returns the status of the operation or the exit code from the application. - 1 is returned if PowerHome cannot launch the application as the specified user. If the async parameter = 1 and the application was successfully launched, then 0 will be returned. If the async parameter = 0 and the application is still running when the wait parameter expires, then 259 will be returned signifying that the application is still running. If the application completes before the wait parameter expires, then the return value will be the exit code returned by the application.
Usage
Use this function (or the ph_runasuser1 function) to execute an application as a specific user. Both the ph_runasuser and ph_runasuser1 functions do the same thing but each uses a different mechanism. Depending upon the system, one function or the other may have better results. The ph_runasuser function uses CreateProcessWithLogon while the ph_runasuser1 function uses CreateProcessAsUser .
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_runasuser("","administrator","adminpass","regsvr32.exe phuirt.dll","c:\powerhome",1,0,5000)


ph_runasuser1

ph_runasuser1 PowerHome formula function
Description
Executes an application as a specific user.
Syntax
ph_runasuser1 ( domain, user, pass, appl, currdir, vis, async, wait )
Argument | Description
domain | String. The domain of the userid you're attempting to run as. Typically you would enter an empty string unless you're trying to authenticate over a corporate network.
user | String. The userid to run the program as.
pass | String. The password for the userid.
appl | String. The full path and filename of the application to execute.
currdir | String. The default directory you wish the application to start from.
vis | Integer. Whether the application should be visible or not. Use 0 for the app to run in the background without a visible window. Use 1 to run the application normally.
async | Integer. Whether the application runs asynchronously or not. Use 0 to run the app synchronously and have PowerHome wait until the app completes or the wait parameter is exceeded. Use 1 to have the app run asynchronously and return control immediately to PowerHome.
wait | Long. The time in milliseconds to wait for an app that is run synchronously (async parameter is 0) to complete. If the app is not done within the specified time, the function will return. Use a negative value in order to wait indefinitely.
Return value
Long. Returns the status of the operation or the exit code from the application. - 1 is returned if the PowerHome cannot login as the specified domain, user, and pass. - 2 is returned if PowerHome cannot launch the application as the specified user. If the async parameter = 1 and the application was successfully launched, then 0 will be returned. If the async parameter = 0 and the application is still running when the wait parameter expires, then 259 will be returned signifying that the application is still running. If the application completes before the wait parameter expires, then the return value will be the exit code returned by the application.
Usage
Use this function (or the ph_runasuser function) to execute an application as a specific user. Both the ph_runasuser and ph_runasuser1 functions do the same thing but each uses a different mechanism. Depending upon the system, one function or the other may have better results. The ph_runasuser function uses CreateProcessWithLogon while the ph_runasuser1 function uses CreateProcessAsUser .
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_runasuser1("","administrator","adminpass","regsvr32.exe phuirt.dll","c:\powerhome",1,0,5000)


ph_runavg

ph_runavg PowerHome formula function
Description
Performs a running average calculation on the supplied data
Syntax
ph_runavg ( ad_avg, ad_newdata, al_samplecnt )
Argument | Description
ad_avg | Double. The current running average value from previous executions of this function. If this is the first sample for the running average, set this value the same as ad_newdata so the returned result won't be skewed
ad_newdata | Double. This is the new value to be figured into the running average
al_samplecnt | Long. This is the number of samples to keep in the running average. You should use a value > 1 otherwise the function will do nothing other than to return the supplied ad_newdata value
Return value
Double. Returns the running average based upon the supplied parameters
Usage
Use this formula to perform running averages on values. Very useful for averaging data such as temperatures over multiple samples to smooth false readings. This is the same function that is used by the Analog I/O screens running average column.

This function uses the following formula to calculate a running average:
If the al_samplecnt parameter is < 1, then the return value will be ad_newdata. Any other sample count value will result in returning a value based upon the following formula: ad_avg - ad_avg / al_samplecnt + ad_newdata / al_samplecnt< /p >

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_runavg(75.0,76.3,5) - Returns a value of 75.26. The ad_avg value of 75.0 is the current running average. The ad_newdata value is the new value to be calculated into the running average. The al_samplecnt value of 5 signifies that the running average is calculated over the last 5 samples


ph_runscript_0

ph_runscript_0 PowerHome formula function
Description
Executes a WSH (Windows Script Host) file.
Syntax
ph_runscript_0 ( timeout, filespec, name )
Argument | Description
timeout | Integer. Timeout. Specifies the time in milliseconds after which the user will be presented with an option to continue or discontinue execution of the script. A value of -1 means the script will never timeout. A value of 0 will fire the timeout event when it is detected that the script is hung.
filespec | String. The full path and filename of the WSH file you wish to execute.
name | String. The function or subroutine which should be executed.
Return value
String. Returns the output of the called function or the text of an error.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_runscript_0(0,"C:\powerhome\web\WthrImgs\weather.vbs","main")


ph_runscript_1

ph_runscript_1 PowerHome formula function
Description
Executes a WSH (Windows Script Host) file and passes 1 parameter.
Syntax
ph_runscript_1 ( timeout, filespec, name, parameter )
Argument | Description
timeout | Integer. Timeout. Specifies the time in milliseconds after which the user will be presented with an option to continue or discontinue execution of the script. A value of -1 means the script will never timeout. A value of 0 will fire the timeout event when it is detected that the script is hung.
filespec | String. The full path and filename of the WSH file you wish to execute.
name | String. The function or subroutine which should be executed.
parameter | Value. The first parameter to be passed to the called function. Can be any datatype.
Return value
String. Returns the output of the called function or the text of an error.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_runscript_1(10,"C:\powerhome\web\WthrImgs\weather.vbs","main","temperature")


ph_runscript_2

ph_runscript_2 PowerHome formula function
Description
Executes a WSH (Windows Script Host) file and passes two parameters.
Syntax
ph_runscript_2 ( timeout, filespec, name, parameter1, parameter2 )
Argument | Description
timeout | Integer. Timeout. Specifies the time in milliseconds after which the user will be presented with an option to continue or discontinue execution of the script. A value of -1 means the script will never timeout. A value of 0 will fire the timeout event when it is detected that the script is hung.
filespec | String. The full path and filename of the WSH file you wish to execute.
name | String. The function or subroutine which should be executed.
parameter1 | Value. The first parameter to be passed to the called function. Can be any datatype.
parameter2 | Value. The second parameter to be passed to the called function. Can be any datatype.
Return value
String. Returns the output of the called function or the text of an error.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_runscript_1(10,"C:\powerhome\web\WthrImgs\weather.vbs","main","temperature","Fahrenheit")
• ph_runscript_1(0,"C:\powerhome\Control\ContactSense.vbs","main","Input",2)


ph_runscript_3

ph_runscript_3 PowerHome formula function
Description
Executes a WSH (Windows Script Host) file and passes three parameters.
Syntax
ph_runscript_3 ( timeout, filespec, name, parameter1, parameter2, parameter3 )
Argument | Description
timeout | Integer. Timeout. Specifies the time in milliseconds after which the user will be presented with an option to continue or discontinue execution of the script. A value of -1 means the script will never timeout. A value of 0 will fire the timeout event when it is detected that the script is hung.
filespec | String. The full path and filename of the WSH file you wish to execute.
name | String. The function or subroutine which should be executed.
parameter1 | Value. The first parameter to be passed to the called function. Can be any datatype.
parameter2 | Value. The second parameter to be passed to the called function. Can be any datatype.
parameter3 | Value. The third parameter to be passed to the called function. Can be any datatype.
Return value
String. Returns the output of the called function or the text of an error.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_runscript_1(10,"C:\powerhome\web\WthrImgs\weather.vbs","main","temperature","Fahrenheit","Ave")
• ph_runscript_1(0,"C:\powerhome\Control\ContactSense.vbs","main","Input",2,"write")


ph_runscript_4

ph_runscript_4 PowerHome formula function
Description
Executes a WSH (Windows Script Host) file and passes four parameters.
Syntax
ph_runscript_3 ( timeout, filespec, name, parameter1, parameter2, parameter3, parameter4 )
Argument | Description
timeout | Integer. Timeout. Specifies the time in milliseconds after which the user will be presented with an option to continue or discontinue execution of the script. A value of -1 means the script will never timeout. A value of 0 will fire the timeout event when it is detected that the script is hung.
filespec | String. The full path and filename of the WSH file you wish to execute.
name | String. The function or subroutine which should be executed.
parameter1 | Value. The first parameter to be passed to the called function. Can be any datatype.
parameter2 | Value. The second parameter to be passed to the called function. Can be any datatype.
parameter3 | Value. The third parameter to be passed to the called function. Can be any datatype.
parameter4 | Value. The forth parameter to be passed to the called function. Can be any datatype.
Return value
String. Returns the output of the called function or the text of an error.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_runscript_1(10,"C:\powerhome\web\WthrImgs\weather.vbs","main","temperature","Match","Current", 72 )
• ph_runscript_1(0,"C:\powerhome\Control\ContactSense.vbs","main","Input",2,"write", 1 )


ph_runscript_5

ph_runscript_5 PowerHome formula function
Description
Executes a WSH (Windows Script Host) file and passes five parameters.
Syntax
ph_runscript_3 ( timeout, filespec, name, parameter1, parameter2, parameter3, parameter4, parameter5 )
Argument | Description
timeout | Integer. Timeout. Specifies the time in milliseconds after which the user will be presented with an option to continue or discontinue execution of the script. A value of -1 means the script will never timeout. A value of 0 will fire the timeout event when it is detected that the script is hung.
filespec | String. The full path and filename of the WSH file you wish to execute.
name | String. The function or subroutine which should be executed.
parameter1 | Value. The first parameter to be passed to the called function. Can be any datatype.
parameter2 | Value. The second parameter to be passed to the called function. Can be any datatype.
parameter3 | Value. The third parameter to be passed to the called function. Can be any datatype.
parameter4 | Value. The forth parameter to be passed to the called function. Can be any datatype.
parameter5 | Value. The fifth parameter to be passed to the called function. Can be any datatype.
Return value
String. Returns the output of the called function or the text of an error.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_runscript_1(10,"C:\powerhome\web\WthrImgs\weather.vbs","main","temperature","Match","Current", 72, "STAT2")
• ph_runscript_1(0,"C:\powerhome\Control\ContactSense.vbs","main","Input",2,"write", 1, "SAVE")


ph_runsync

ph_runsync PowerHome formula function
Description
Launches an external executable and waits for it to complete.
Syntax
ph_runsync ( path, wait, waittype )
Argument | Description
path | String. The full path and filename of the executable to run.
wait | Long. The number of milliseconds to wait for the executable to complete. Use -1 to wait indefinately.
waittype | Integer. The type of waiting for PowerHome to perform. If 0, then PowerHome will not be locked and other functions may be performed (however, the execution queue will not process any more actions until this function completes). Any other value and PowerHome will be frozen and appear to be hung until the application completes or times out.
Return value
Integer. 0 is returned if the function returns because the executable was closed. 1 is returned if the function returns because the timeout (wait) parameter was exceeded.


ph_runsync1

ph_runsync1 PowerHome formula function
Description
Execute an application synchronously or asynchronously.
Syntax
ph_runsync1 ( path, currdir, async, wait )
Argument | Description
path | String. The full path and filename of the executable to run.
currdir | String. The default directory for the program to be executed in.
async | Integer. Determines whether the application will run asynchronously or synchronously. Use 0 for synchronous execution. Use 1 for asynchronous execution.
wait | Long. The number of milliseconds to wait for the executable to complete if the async parameter is 0. Use - 1 to wait indefinately.
Return value
Long. If the async parameter is 1, then 0 will be returned immediately. If the async parameter is 0 and the application is still running when the wait parameter expires, then 259 will be returned signifying that the application is still running. If the application completes before the wait parameter expires, then the return value will be the exit code returned by the application.
Usage
Use this function to execute an application under the PowerHome users context either asynchronously or synchronously. If you need to execute an application using a different user context, use the ph_runasuser or ph_runasuser1 functions.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_runsync1("notepad.exe","",1,0)
The above example will execute the Windows notepad application and return control immediately back to PowerHome (run asynchronously).


ph_sendkeys

ph_sendkeys PowerHome formula function
Description
Executes the string as a Send Keys command.
Syntax
ph_sendkeys ( s )
Argument | Description
s | A string representing a sequence of Send Keys commands. The string IS NOT a formula and is not evaluated before being parsed as a Send Keys command.
Return value
Integer. Returns a 0 if successful and 1 if an infinite loop condition is detected,


ph_sendkeysbtn

ph_sendkeysbtn PowerHome formula function
Description
Executes a formula from the "Formulas" table.
Syntax
ph_sendkeysbtn ( id )
Argument | Description
id | The ID of the formula you wish to execute.
Return value
Integer. Returns a 2 if the ID is not found. Returns a 0 if the result of the formula is not output as a sendkeys. If the formula result is output as sendkeys, the result from the sendkeys function is returned.
Usage
This function is identical to the ph_formulabtn function which reflects the new naming and methodology. This function is deprecated and will be removed in a future release. All references to this function should be changed to the new ph_formulabtn function.


ph_sendkeysmq

ph_sendkeysmq PowerHome formula function
Description
Simulates keystrokes directly to a handle by posting WM_KEYDOWN messages to the handles message queue.
Syntax
ph_sendkeysmq ( n, s )
Argument | Description
n | The handle you wish keystrokes sent to.
s | A string representing the send keys commands to generate.
Return value
Integer. Returns a 0.
Usage
This function uses the same send keys commands as the ph_sendkeys function. However, this function can simulate keystrokes to applications that are minimized or do not currently have focus. Note that using this method of generating keystrokes is not quite the same as ph_sendkeys. For example: To send keystrokes to a Notepad window, you would typically use ph_switchto to bring the Notepad window to the foreground and then use ph_sendkeys. To send these same keystrokes using ph_sendkeysmq, you must first identify the handle of the "Edit" box within the notepad window (typically using ph_findwindow to retrieve the handle of the Notepad window followed by ph_findwindowex to retrieve the handle of the "Edit" window).


ph_sendsocketdata

ph_sendsocketdata PowerHome formula function
Description
Sends and retrieves data using a socket to a remote IP/ Port.
Syntax
ph_sendsocketdata ( url, port, data )
Argument | Description
url | String. The IP or hostname of the remote device to communicate with.
port | Long. The Port of the remote device to communicate with.
data | String. The data to send via a socket to the remote device.
Return value
String. Returns data from the remote device. If an error occurs, it will be in the form: "*ERROR* - XXX"
Usage
Use this funciton to send and receive raw data using sockets.


ph_sendsocketdata1

ph_sendsocketdata1 PowerHome formula function
Description
Sends and retrieves data using a socket to a remote IP/ Port.
Syntax
ph_sendsocketdata1 ( url, port, flags, data )
Argument | Description
url | String. The IP or hostname of the remote device to communicate with.
port | Long. The Port of the remote device to communicate with.
flags | Integer. Flags controlling how the function performs. Indivdual flag values are added together to create the Flags value. Add 1 to have the function return on "SendComplete". Add 2 to have special characters translated before sending. Add 4 to have special characters returned translated. Add 8 to have the function return when data is received. You should not use 1 and 8 together as they mutually exclusive. If neither 1 or 8 are added to the flags parameter, then the function will return when the connection is closed.
data | String. The data to send via a socket to the remote device.
Return value
String. Returns data from the remote device. If an error occurs, it will be in the form: "*ERROR* - XXX". Special characters can be sent using this function by converting them to 3 digit ASCII and escaping the sequence with a '\' character. So to send a carriage return as part of the data, use \013 and be sure to include a 2 in the flags sum. If the data being returned by the function is likely to contain characters outside of the normal character range (32 to 125) then add a 4 to the flags sum so that these characters will be returned in the escaped 3 digit ASCII form. Keep in mind if you are using escaped characters that the backslash character (\) must now be escaped as \092.

You may also encode special characters in a hexadecimal format rather than a decimal format. In this case, the escape sequence consists of the "\" character followed by either an upper or lower case "x" followed by two upper or lower case hexadecimal digits. A carriage return using the hex format would be \x0D. You must also include a 2 in the flags sum as is the case with decimal escape codes.
Usage
Use this funciton to send and receive raw data using sockets.


ph_setanalogdisplay

ph_setanalogdisplay PowerHome formula function
Description
Sets the display values associated with records in the analogio table (Analog I/O screen) that will display in the Device Status screen
Syntax
ph_setanalogdisplay ( al_foreground, al_background, as_graphic, ai_refresh )
ph_setanalogdisplay ( as_id, al_foreground, al_background, as_graphic, ai_refresh )
Argument | Description
as_id | String (Optional). The ID of the record in the analogio table. If this parameter is omitted the system variable ANALOG will be used for the ID
al_foreground | Long. The foreground color to display in the Control area of the Device Status screen. Use a negative number to use the existing value
al_background | Long. The background color to display in the Control area of the Device Status screen. Use a negative number to use the existing value
as_graphic | String. The path and filename of a graphic to display in the Control area of the Device Status screen. Use a string containing a single space " " to use the existing value
ai_refresh | Integer. Use 0 to update the table but not refresh the Device Status screen if open. Any other value will update the table as well as refresh the open Device Status screen
Return value
Integer. Returns 0 if successful. Returns 1 if the ID does not exist. Returns 2 if the analogio table cannot be updated
Usage
Since the Analog I/O screen only contains a single setting for foreground, background, and graphic, this function allows the user flexibility in changing these static values based upon the current value of the particular Analog I/O point. This function may be called in the CalctoRaw and RawtoCalc formulas defined for the Analog I/O point. If called from within the CalctoRaw or RawtoCalc formulas, you can use the syntax that omits the as_id parameter
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setanalogdisplay("KITCHENLIGHT", -1,rgb(255,255,0)," ",1) - Sets the background color for the KITCHENLIGHT Analog I/O device to yellow. The foreground color and graphic is unchanged. The Device Status screen is refreshed to show the changes.


ph_setdevicefilter

ph_setdevicefilter PowerHome formula function
Description
Sets the filter for the Device Status Screen.
Syntax
ph_setdevicefilter ( filter )
Argument | Description
filter | Filter expression to apply to the Device Status Screen
Return value
Integer. Returns 1 if the filter succeeds. - 1 is returned if the filter fails.
Usage
Use the ph_setdevicefilter formula to programatically limit the amount of rows displayed on the Device Status Screen.

The filter expression consists of columns, relational operators, and values against which column values are compared. Boolean expressions can be connected with logical operators AND and OR. You can also use NOT, the negation operator. Use parentheses to control the order of evaluation.

Sample Filters:
location = 'LIVING ROOM'
type = 0 and id like 'E%'


ph_setdevicesort

ph_setdevicesort PowerHome formula function
Description
Sets the sort criteria for the Device Status Screen.
Syntax
ph_setdevicesort ( sort )
Argument | Description
sort | Sort expression to apply to the Device Status Screen
Return value
Integer. Returns 1 if the filter succeeds. - 1 is returned if the sort fails.
Usage
Use the ph_setdevicesort formula to programatically sort the rows displayed on the Device Status Screen.

The sort criteria for a column has one of the forms shown in the following table, depending on whether you specify the column by name or number. Order is a, asc, or ascending for ascending order or d, desc, or descending for descending order. Order is case insensitive. If you omit order or specify an unrecognised string, the sort is performed in ascending order.

You can specify secondary sorting by specifying criteria for additional columns in the format string. Separate each column specification with a comma.

Syntax for sort order | Examples
columnname order | "location a,key_desc a"
 | "type"
#columnnumber order | "#6 D,#7 A"


ph_ssrequest

ph_ssrequest PowerHome formula function
Description
This function makes properly formatted requests to a PowerHome Socket Server (Another instance of PowerHome or the Distributed Control Client).
Syntax
ph_ssrequest ( s, n, s, s, s, s )
Argument | Description
s | The IP or DNS equivalent of the Socket Server.
n | The port of the Socket Server
s | The userid of the Socket Server
s | The password for the Socket Server
s | The Socket Server request type. (The DCC only supports the "FORMULA" request type)
s | The actual data to pass to the Socket Server.
Return value
String. Returns the value returned from the remote Socket Server.


ph_timedeventsinfo

ph_timedeventsinfo PowerHome formula function
Description
Returns the requested info for the specified Timedevent ID.
Syntax
ph_timedeventsinfo ( id, command )
Argument | Description
id | String. The ID of the Timedevent whose info you're trying to receive.
command | String. Specifies the type of data you'd like to retrieve for the timedevent. See usage below.
Return value
String. Returns either the ID of the next timedevent or a string containing the date and time for when the specified timedevent ID is going to fire. Returns empty string if the command parameter is invalid or the timedevent ID is not found.

The valid values for the command parameter are detailed in the table below:
nextevent | This value will cause the function to return the timedevent ID of the next timedevent to fire. Set the ID parameter to empty string "" when using this option.
nexttime | This value will cause the function to return a formatted string (yyyy-mm-dd hh:mm:ss) for the next date/time when the specified timedevent ID will be fired.
Usage
Use this function to retrieve information concerning Timedevents.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_timedeventsinfo("SUNRISE","nexttime")
The above example will return the date/time for when the SUNRISE timed event will next be fired.

ph_timedeventsinfo("","nextevent")
The above example will return the ID of the next timedevent that will be fired.


ph_winampctrl

ph_winampctrl PowerHome formula function
Description
Controls a Winamp instance running on the PowerHome machine.
Syntax
ph_winampctrl ( command, ldata, sdata )
Argument | Description
command | String. A string representation of the control command.
ldata | Long. Numeric data for the command. Use 0 when the command does not require numeric data.
sdata | String. String data for the command. Use "" (empty string) when the command does not require string data.
Return value
Integer. Returns 0 if the command is successful. Returns 1 if an error occurs. Returns 2 if Winamp is not running. Returns 3 if the command is not recognized.
Usage
Use this function for complete control of Winamp on the PowerHome computer. This function relies upon the data in the [Winamp] section of the pwrhome.ini file. The path parameter should be set to the location path and filename of the Winamp executable. Set the class parameter if you wish to launch Winamp using a unique class name differing from the default. Leave blank to use the default Winamp class name.

Command | Description
launch | Used to launch Winamp if it is not running.
addlist | Adds individual songs to the current playlist or entire playlists to the current playlist. Place the path the song or playlist in the sdata parameter.
playfile | Plays an individual song or a playlist. Place the path and filename of the song or playlist in the sdata parameter. This command will replace the current playlist with the new song or playlist.
prev | Moves to the previous song in the list.
play | Plays the currently selected song.
pause | Pauses the currently selected song.
stop | Stops the currently selected song.
next | Moves to the next song in the list.
fadeout | Stops the currently playing song by slowly fading away.
stoptrack | Stops play after the currently playing track completes.
fwd5sec | Skips the currently playing song forward 5 seconds.
rew5sec | Rewinds the currently playing song by 5 seconds.
startlist | Moves the current position within the playlist to the first song.
endlist | Moves the current position within the playlist to the last song.
volumeup | Raises the Winamp volume slightly.
volumedown | Lowers the Winamp volume slightly.
togglerepeat | Toggles the repeat button on and off.
toggleshuffle | Toggles the shuffle button on and off.
close | Closes Winamp
clearlist | Clears the current playlist.
seek | Seeks to a specific section in milliseconds of currently playing song. Place the seek milliseconds in the ldata parameter.
writelist | Writes the current playlist to <>\winamp.m3u
seeklist | Seek to a specific position within the current playlist. Place the seek position in the ldata parameter.
setvolume | Sets the Winamp volume. Place the volume setting (0 - 255) in the ldata parameter.
setpanning | Sets the Winamp panning. Place the panning value (0 left to 255 right) in the ldata parameter
restart | Restarts Winamp
seekpercent | Seeks to a specific position within the currently playing song using a percent value rather than milliseconds. Place the seek percent (0 - 100) in the ldata parameter.
shuffleset | Turns the Winamp shuffle on.
shuffleclear | Turns the Winamp shuffle off.
repeatset | Turns the Winamp repeat on.
repeatclear | Turns the Winamp repeat off.
setclass | Sets the class value in the WinAmp section of the pwrhome.ini file.
setpath | Sets the path value in the WinAmp section of the pwrhome.ini file.


ph_winampinfo

ph_winampinfo PowerHome formula function
Description
Retrieves information from a Winamp instance running on the PowerHome machine.
Syntax
ph_winampinfo ( command, data, local )
Argument | Description
command | String. A string representation of the info command.
data | Long. Data to passed for certain commands. Use 0 for commands that do not require data.
local | Integer. The index of a local variable in which to return error information. Use 0 to not return error information.
Return value
String. Returns data for the requested command. If the command is successful, then the local variable will contain "0". If an error occurs, then the local variable will contain "1". If Winamp is not running, then the local variable will contain "2". If the command is not recognized, then the local variable will contain "3".
Usage
Use this function to retrieve information from an instance of Winamp running on the PowerHome computer. This function relies upon the data in the [Winamp] section of the pwrhome.ini file.

Command | Description
status | Returns the current status of Winamp. Possible return values are "playing", "paused", "stopped", and "not running".
title | Returns the title of the current song.
titlenum | Returns the number of the current title within the current playlist.
version | Returns the version of Winamp that is running.
trackpos | Returns the current position in milliseconds of the current song.
tracklen | Returns the length of the current song in seconds.
listlen | Returns the length of the current playlist in tracks.
listpos | Returns the current position within the playlist.
tracksamplerate | Returns the sample rate of the current playing song.
trackbitrate | Returns the bitrate of the current playing song.
tracknumchannels | Returns the number of channels of the current playing song.
trackpercent | Returns the percent complete of the current playing song.
shuffle | Returns the status of the shuffle.
repeat | Returns the status of the repeat.
listfilename | Returns the filename of a song within the playlist. The data parameter is the number of the song whose data you wish returned. Use - 1 for the current playing song.
listtitlename | Returns the title name of a song within the playlist. The data parameter is the number of the song whose data you wish returned. Use - 1 for the current playing song.
listpath | Returns the path of a song within the playlist. The data parameter is the number of the song whose data you wish returned. Use - 1 for the current playing song.
listartist | Returns the artist of a song within the playlist. The data parameter is the number of the song whose data you wish returned. Use - 1 for the current playing song.
listtitle | Returns the title of a song within the playlist. The data parameter is the number of the song whose data you wish returned. Use - 1 for the current playing song.
listalbum | Returns the album of a song within the playlist. The data parameter is the number of the song whose data you wish returned. Use - 1 for the current playing song.
listyear | Returns the year of a song within the playlist. The data parameter is the number of the song whose data you wish returned. Use - 1 for the current playing song.
listbitrate | Returns the bitrate of a song within the playlist. The data parameter is the number of the song whose data you wish returned. Use - 1 for the current playing song.
listlength | Returns the length of a song within the playlist. The data parameter is the number of the song whose data you wish returned. Use - 1 for the current playing song.


abs

abs PowerHome formula function
Description
Calculates the absolute value of a number.
Syntax
abs (number)
Argument | Description
number | The number for which you want the absolute value
Return value
The data type of number. Returns the absolute value of number.
Examples
The following examples demonstrate typical syntax/usage for this function.
• abs([LOCAL1])
• abs([TEMP2]-[TEMP3])


acos

acos PowerHome formula function
Description
Calculates the arccosine of an angle.
Syntax
acos (n)
Argument | Description
n | The ratio of the lengths of two sides of a triangle for which you want a corresponding angle (in radians). The ratio must be a value between -1 and 1
Return value
Double. Returns the arccosine of n if it succeeds.


asin

asin PowerHome formula function
Description
Calculates the arcsine of an angle.
Syntax
asin (n)
Argument | Description
n | The ratio of the lengths of two sides of a triangle for which you want a corresponding angle (in radians). The ratio must be a value between -1 and 1
Return value
Double. Returns the arcsine of n if it succeeds.


atan

atan PowerHome formula function
Description
Calculates the arctangent of an angle.
Syntax
atan (n)
Argument | Description
n | The ratio of the lengths of two sides of a triangle for which you want a corresponding angle (in radians).
Return value
Double. Returns the arctangent of n if it succeeds.


ceiling

ceiling PowerHome formula function
Description
Retrieves the smallest whole number that is greater than or equal to a specified limit.
Syntax
ceiling ( n )
Argument | Description
n | The number for which you want the smallest whole number that is greater than or equal to it
Return value
The data type of n. Returns the smallest whole number that is greater than or equal to n.


cos

cos PowerHome formula function
Description
Calculates the cosine of an angle.
Syntax
cos ( n )
Argument | Description
n | The angle (in radians) for which you want the cosine
Return value
Double. Returns the cosine of n.


exp

exp PowerHome formula function
Description
Raises e to the specified power.
Syntax
exp ( n )
Argument | Description
n | The power to which you want to raise e (2.71828)
Return value
Double. Returns e raised to the power n.


fact

fact PowerHome formula function
Description
Gets the factorial of a number.
Syntax
fact ( n )
Argument | Description
n | The number for which you want the factorial
Return value
Double. Returns the factorial of n.


int

int PowerHome formula function
Description
Gets the largest whole number less than or equal to a number.
Syntax
int ( n )
Argument | Description
n | The number for which you want the largest whole number that is less than or equal to it
Return value
The data type of n. Returns the largest whole number less than or equal to n.


isnumber

isnumber PowerHome formula function
Description
Reports whether the value of a string is a number.
Syntax
isnumber ( string )
Argument | Description
string | String whose value you want to test to determine whether it is a valid number
Return value
Boolean. Returns TRUE if string is a valid number and FALSE if it is not.
Examples
The following examples demonstrate typical syntax/usage for this function.
• if(isnumber("{SKYLIGHT}"),2,1)


log

log PowerHome formula function
Description
Gets the natural logarithm of a number.
Syntax
log ( n )
Argument | Description
n | The number for which you want the natural logarithm (base e). The value of n must be greater than 0
Return value
Double. Returns the natural logarithm of n. An execution error occurs if n is negative or zero. The inverse of the Log function is the Exp function.


logten

logten PowerHome formula function
Description
Gets the base 10 logarithm of a number.
Syntax
logten ( n )
Argument | Description
n | The number for which you want the base 10 logarithm. The value of n must not be negative
Return value
Double. Returns the base 10 logarithm.

The expression 10^n is the inverse for LogTen(n). To obtain n given number (nbr = LogTen(n)), use n = 10^nbr.


mod

mod PowerHome formula function
Description
Obtains the remainder (modulus) of a division operation.
Syntax
mod ( x, y )
Argument | Description
x | The number you want to divide by y
y | The number you want to divide into x
Return value
The data type of x or y, whichever data type is more precise.


ph_and

ph_and PowerHome formula function
Description
Bitwise (binary) AND's two numbers.
Syntax
ph_and ( val1, val2 )
Argument | Description
val1 | Long. Unsigned long value of the first operand.
val2 | Long. Unsigned long value of the second operand.
Return value
Unsigned long. Returns the value of the two operands AND'ed together.
Usage
Used to compare boolean values to determine if both are true, or not. Can also be used to mask bits from a binary value. See examples below.

In addition to the ph_and() function, the stand-alone AND operator is also available for use in boolean testing, typically in IF functions. Using the AND operator this way often makes code more 'readable' and has the added advantage that more than only two variables can be compared.

A typical use of the AND operator in an IF function is...
• if(Now()>09:00:00 and {DARK}=0 and {HOME}=1,1,0)
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_and({DARK},{HOME}) | Yields a "1" if both the DARK and HOME Globals are true (ie, equal to 1)
ph_and(17,1) | Yields "1" {0b10001 AND 0b00001 >> 1}
ph_and(21, [LOCAL1]) | Yields "1" if LOCAL1=3 {0b10101 AND 0b00011 >> 1}


ph_iseven

ph_iseven PowerHome formula function
Description
Determines whether a whole number is even or not
Syntax
ph_iseven ( num )
Argument | Description
num | Integer. A whole (positive or negative) number to check
Return value
Integer. Returns 1 if the number is even. Returns 0 if the number is odd.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_iseven(2) --> Return=1
• ph_iseven([TEMP2]-[TEMP3]) --> Return=0 if the result is an odd number


ph_isodd

ph_isodd PowerHome formula function
Description
Determines whether a whole number is odd or not
Syntax
ph_isodd ( num )
Argument | Description
num | Integer. A whole (positive or negative) number to check
Return value
Integer. Returns 1 if the number is odd. Returns 0 if the number is even.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_isodd(2) --> Return=0
• ph_isodd([TEMP2]-[TEMP3]) --> Return=1 if the result is an odd number


ph_not

ph_not PowerHome formula function
Description
This function is a numeric equivalent of a boolean NOT function.
Syntax
ph_not ( value )
Argument | Description
value | Unsigned Long. A numeric value to test.
Return value
Unsigned Long. If the value parameter is 0, then this function will return 1. Any other non-zero value will cause the function to return 0.
Usage
Use this function to equate a numeric integer value as either a 0 or 1.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_not(234)
The above example will return 0.


ph_or

ph_or PowerHome formula function
Description
Bitwise OR's two numbers.
Syntax
ph_or ( val1, val2 )
Argument | Description
val1 | Long. Unsigned long value of the first operand.
val2 | Long. Unsigned long value of the second operand.
Return value
Unsigned long. Returns the value of the two operands OR'ed together.
Usage
Used to compare boolean values to determine if either is true, or not. Can also be used to combine bits from a binary value. See examples below.

In addition to the ph_or() function, the stand-alone OR operator is also available for use in boolean testing, typically in IF functions. Using the OR operator this way often makes code more 'readable' and has the added advantage that more than two variables can be compared.

A typical use of the OR operator in an IF function is...
. if(now() > 09:00:00 or {DARK} = 0 or {ON}= 1,1,0)
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_or({DARK},{HOME}) | Yields a "1" if either the DARK or HOME Globals are true (ie, equal to 1)
ph_or(8,2) | Yields "10" {0b1000 AND 0b0010 >> 0b1010}
ph_or(10,2) | Yields "10" {0b1010 AND 0b0010 >> 0b1010}
ph_or(21,[LOCAL1]) | Yields "23" if LOCAL1=3 {0b10101 AND 0b00011 >> 1}


ph_random

ph_random PowerHome formula function
Description
Generates random numbers.
Syntax
ph_random ( max )
Argument | Description
max | Long. The maximum random value to return.
Return value
Long. Returns a random number which will be between 1 and max inclusive.
Usage
This function uses the random number generator provided with the Microsoft cryptographic routines (vs the internal random number generator used by the rand function). This function creates much more random numbers than the rand function and should be used instead for truly random number generation. This function also does NOT require the randomize() function to be executed and will generate completely random numbers immediately.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_random(10)
The above example will return a randomly generated number between 1 and 10 inclusive.


ph_sumnum

ph_sumnum PowerHome formula function
Description
This function will take a string of numerics and perform one of several summations on them.
Syntax
ph_sumnum ( data, numtype, sumtype )
Argument | Description
data | String. The string containing the numbers to sum. Numbers should be separated using commas, spaces, or some other non-numeric character (the "-" sign is reserved to indicate a negative number).
numtype | Integer. The type of numbers contained in the data parameter. Use 0 for standard whole numbers. Use 1 for numbers that contain a decimal point. Use 2 for hexadecimal numbers.
sumtype | Integer. The type of summation to perform. Use 0 to have the individual numbers added together. Use 1 to return the average of the numbers. Use 2 to return a checksum of the numbers.
Return value
Double. Returns the result of the specified summation. Returns 0 if the numtype or sumtype are invalid values.
Usage
Use this function to quickly add a string of delimited numbers or return their average. The checksum option uses the same technique specified for Insteon I2CS operations. The checksum operation is defined as: ph_and(ph_xor(ph_and(d_sum,255),255) + 1,255) where d_sum is the total of individual numbers added together.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_sumnum("A5 19 2E 45 AA BB 34 1A 2D",2,2)
The above example will add the hexadecimal numbers in the data parameter and then perform the I2CS checksum operation. The result returned will be 239.


ph_xor

ph_xor PowerHome formula function
Description
Bitwise XOR's two numbers.
Syntax
ph_xor ( val1, val2 )
Argument | Description
val1 | Unsigned long value of the first operand.
val2 | Unsigned long value of the second operand.
Return value
Unsigned long. Returns the value of the two operands XOR'ed together.


pi

pi PowerHome formula function
Description
Multiplies pi by a specified number.
Syntax
pi ( n )
Argument | Description
n | The number you want to multiply by pi (3.14159265358979323...)
Return value
Double. Returns the result of multiplying n by pi if it succeeds and -1 if an error occurs.


rand

rand PowerHome formula function
Description
Obtains a random whole number between 1 and a specified upper limit.
Syntax
rand ( n )
Argument | Description
n | The upper limit of the range of random numbers you want returned. The lower limit is always 1. The upper limit cannot exceed 32,767
Return value
A numeric data type, the data type of n. Returns a random whole number between 1 and n.


round

round PowerHome formula function
Description
Rounds a number to the specified number of decimal places.
Syntax
round ( x , n )
Argument | Description
x | The number you want to round
n | The number of decimal places to which you want to round x
Return value
Decimal. If n is positive, Round returns x rounded to the specified number of decimal places. If n is negative, it returns x rounded to (- n +1) places before the decimal point. Returns -1 if it fails.


sign

sign PowerHome formula function
Description
Reports whether the number is negative, zero, or positive by checking its sign.
Syntax
sign ( n )
Argument | Description
n | The number for which you want to determine the sign
Return value
Integer. Returns a number (-1, 0, or 1) indicating the sign of n.


sin

sin PowerHome formula function
Description
Calculates the sine of an angle.
Syntax
sin ( n )
Argument | Description
n | The angle (in radians) for which you want the sine
Return value
Double. Returns 1 if it succeeds and -1 if an error occurs.


sqrt

sqrt PowerHome formula function
Description
Calculates the square root of a number.
Syntax
sqrt ( n )
Argument | Description
n | The number for which you want the square root
Return value
Double. Returns the square root of n.
Usage
Sqrt(n) is the same as n ^.5.

Taking the square root of a negative number causes an execution error.


tan

tan PowerHome formula function
Description
Calculates the tangent of an angle.
Syntax
tan ( n )
Argument | Description
n | The angle (in radians) for which you want the tangent
Return value
Double. Returns the tangent of n if it succeeds and -1 if an error occurs.


truncate

truncate PowerHome formula function
Description
Truncates a number to the specified number of decimal places.
Syntax
truncate ( x, n )
Argument | Description
x | The number you want to truncate
n | The number of decimal places to which you want to truncate x
Return value
The data type of x. If n is positive, returns x truncated to the specified number of decimal places. If n is negative, returns x truncated to (- n +1) places before the decimal point. Returns -1 if it fails.


ph_createpluginpt

ph_createpluginpt PowerHome formula function
Description
Creates a "passthru" window object for use by plugins that may not have a Windows handle associated with them.
Syntax
ph_createpluginpt ( index )
Argument | Description
index | Long. The index number of the Generic Plugin the passthru is being attached to.
Return value
Long. Returns the handle of the Passthru window.
Usage
The Passthru window is an invisible window with a Windows handle with predefined events enabled. Certain PowerHome Generic Plugins may not have a handle associated with them but may need to be accessed by external programs using Windows messaging. The Passthru window provides this necessary handle. This handle may have Windows messages sent to it which will then be passed to the Generic Plugin defined by the index parameter using the phpi_syscommand function.

The captured events are 1024 thru 1033. Both the wparm and lparam values will be passed using the phpi_syscommand function. Event 1034 is used to close the passthru window if the wparam contains the handle of the passthru and the lparam contains the index of the plugin. Event 1050 is used to setup a "Wait" timer. The max wait value is contained in seconds in the lparam value. When this event is called the passthru will wait until the busy flag is cleared or the max wait value is exceeded. Event 1051 will clear the busy flag set by event 1050. The last captured event is event 74 which is used by a COPYDATASTRUCT type of Windows message. The wparam and lparam values will be passed using the phpi_syscommand function so that the COPYDATASTRUCT structure can be directly accessed by the generic plugin.


ph_picmd

ph_picmd PowerHome formula function
Description
Sends a command to a Generic PowerHome Plugin Control using the standard plugin interface function of phpi_command.
Syntax
ph_picmd ( timeout, id, cmd, data1, data2, data3, data4 )
Argument | Description
timeout | The length of time in seconds to wait for the plugin to return a value. Use a value of 0 to wait indefinately. Use a negative number to not wait for a return value (post the function call).
id | The ID of the PowerHome Plugin.
cmd | A long representing the command number.
data1 | A long representing the Data 1 value.
data2 | A long representing the Data 2 value.
data3 | A string representing the Data 3 value.
data4 | A string representing the Data 4 value.
Return value
String. Returns the value returned from the Plugin's phpi_command function. Returns empty string if the plugin is not valid or you passed a negative number for the timeout. Returns "*ERROR - PLUGIN TIMEOUT" if the plugin did not return a value before your timeout expired.
Usage
Use this function for general communication with a Generic PowerHome Plugin. This function is a direct passthru to the phpi_command function required by the PowerHome Generic Plugin Interface. Implementation of the cmd and data1 thru data4 parameters is dependent upon the indivdual plugin.


ph_pictrl

ph_pictrl PowerHome formula function
Description
Enables the user to control low level functions of a generic plugin
Syntax
ph_pictrl ( id, cmd, type )
Argument | Description
id | A string representing the ID of the plugin to control.
cmd | A string representing the command. Available commands are detailed below.
type | An integer value containing additional data used by some commands.
Return value
Long. Returns data dependant upon the requested command type.
Usage
"reinit" will reinitialize a plugin. If the type parameter is 0, PowerHome will first execute the plugins PHPI_Close function (and wait up to 10 seconds for the function to return) followed by unloading and reloading the plugin. Any other value for the type parameter causes PowerHome to bypass the PHPI_Close function and immediately unload and reload the plugin.

"enable" will call the plugin function PHPI_Enable.

"disable" will the the plugin function PHPI_Disable.

"status" will call the plugin function PHPI_Status.

"getbusycnt" will return the number of queued commands for a plugin. Since plugins run in their own thread, multiple command may queue up for a plugin. If the "getbusycnt" never comes down to 0, then the plugin itself may be hung and you may want to "reinit" it.


ph_pitrigger

ph_pitrigger PowerHome formula function
Description
Calls the Generic Plugin Trigger (Trigger type 27).
Syntax
ph_pitrigger ( id, number, value, dim, command, data, formula, auxvalue )
Argument | Description
id | The trigger ID to call. Within the Generic Plugin Trigger, this is the ID of the plugin.
number | The trigger number to call. This will be a value from 1 to 256.
value | The trigger value to call. This will be a value from 1 to 256.
dim | A double representing the dim value. This value will simply be passed to the trigger in the [TEMP2] variable.
command | An unsigned long representing the command. This value will be passed to the [TEMP3] variable.
data | A long representing the data. This value will be passed to the [TEMP4] variable.
formula | A string representing the formula. This value will be passed to the [TEMP5] variable.
auxvalue | A string representing the auxillary value. This value will be passed to the [TEMP10] variable.
Return value
Integer. The return value is the binary addition of the four individual trigger calls. This sum consists of 1 if the first check returns no rows, 2 if the second check returns no rows, 4 if the third check returns no rows, and 8 if the fourth check returns no rows.
Usage
This function is very similar to the ph_checktrigger function except that it only calls trigger types of 27 (Generic Plugin Trigger). It is provided as a simple interface for generic plugins to fire the generic plugin trigger. Using a single function call, 4 individual trigger checks will be made. The first will be made for [Any], [Any], the second for [Any], Specific Value, the third for Specific Number, [Any], and the fourth for Specific Number, Specific Value.

While a plugin can fire ANY trigger using the ph_checktrigger function, for plugin specific triggers not handled by the other existing trigger types, the Generic Plugin Trigger should be used along with this function call.


fill

fill PowerHome formula function
Description
Builds a string of the specified length by repeating the specified Unicode characters until the result string is long enough.
Syntax
fill ( chars, n )
Argument | Description
chars | A string whose value will be repeated to fill the return string
n | A long whose value is the length of the string you want returned
Return value
String. Returns a string n characters long filled with repetitions of the characters in the argument chars. If the argument chars has more than n characters, the first n characters of chars are used to fill the return string. If the argument chars has fewer than n characters, the characters in chars are repeated until the return string has n characters.


filla

filla PowerHome formula function
Description
Builds a string of the specified length by repeating the specified ASCII characters until the result string is long enough.
Syntax
filla ( chars, n )
Argument | Description
chars | A string whose value will be repeated to fill the return string
n | A long whose value is the length of the string you want returned
Return value
String. Returns a string n characters long filled with repetitions of the characters in the argument chars. If the argument chars has more than n characters, the first n characters of chars are used to fill the return string. If the argument chars has fewer than n characters, the characters in chars are repeated until the return string has n characters.


lastpos

lastpos PowerHome formula function
Description
Finds the last position of a target string in a source string.
Syntax
lastpos ( string1, string2 {, searchlength } )
Argument | Description
string1 | The string in which you want to find string2
string2 | The string you want to find in string1
searchlength | (optional) A long that limits the search to the leftmost searchlength characters of the source string string1. The default is the entire string
Return value
Long. Returns a long whose value is the starting position of the last occurrence of string2 in string1 within the characters specified in searchlength. If string2 is not found in string1 or if searchlength is 0, LastPos returns 0. If any argument's value is NULL, LastPos returns NULL.
Usage
The LastPos function is case sensitive. The entire target string must be found in the source string.


left

left PowerHome formula function
Description
Obtains a specified number of characters from the beginning (left side) of a string.
Syntax
left ( string, n )
Argument | Description
string | String containing the characters you want to search.
n | Integer. A number specifying the number of characters you want to return.
Return value
String. Returns the leftmost n characters in string if it succeeds and the empty string ("") if an error occurs.

If n is greater than or equal to the length of the string, Left returns the entire string. It does not add spaces to make the return value's length equal to n.
Examples
The following examples demonstrate typical syntax/ usage for this function.
. left("[LOCAL1]",10) --> get the first 10 characters from the string.
. if( left( "[LOCAL1]", 12 ) = "HTTP/1.1 404", "ERROR", "Nextline")


lefta

lefta PowerHome formula function
Description
Obtains a specified number of bytes from the beginning (left side) of a string.
Syntax
lefta ( string, n )
Argument | Description
string | String containing the bytes you want to search.
n | Integer . A number specifying the number of bytes you want to return.
Return value
String. Returns the leftmost n bytes in string if it succeeds and the empty string ("") if an error occurs.

If n is greater than or equal to the length of the string, LeftA returns the entire string. It does not add spaces to make the return value's length equal to n.
Examples
The following examples demonstrate typical syntax/ usage for this function.
. lefta("[LOCAL1]",10) --> get the first 10 bytes from the string.
. if( lefta( "[LOCAL1]", 12 ) = "HTTP/1.1 404", "ERROR", "Nextline")


lefttrim

lefttrim PowerHome formula function
Description
Removes spaces from the beginning of a string.
Syntax
lefttrim ( string )
Argument | Description
string | The string you want returned with leading spaces deleted
Return value
String. Returns a copy of string with leading spaces deleted if it succeeds and the empty string ("") if an error occurs.


len

len PowerHome formula function
Description
Reports the length of a string.
Syntax
len ( string )
Argument | Description
string | The string for which you want the length
Return value
Long. Returns a long containing the length of string if it succeeds and -1 if an error occurs.


len

lena PowerHome formula function
Description
Reports the length of a string in bytes.
Syntax
lena ( string )
Argument | Description
string | The string for which you want the length in bytes
Return value
Long. Returns a long containing the length of string in bytes if it succeeds and -1 if an error occurs.


match

match PowerHome formula function
Description
Determines whether a string's value contains a particular pattern of characters.
Syntax
match ( string, textpattern )
Argument | Description
string | The string in which you want to look for a pattern of characters
textpattern | A string whose value is the text pattern
Return value
Boolean. Returns TRUE if string matches textpattern and FALSE if it does not. Match also returns FALSE if either argument has not been assigned a value or the pattern is invalid.
Usage
Match enables you to evaluate whether a string contains a general pattern of characters. To find out whether a string contains a specific substring, use the Pos function.

Textpattern is similar to a regular expression. It consists of metacharacters, which have special meaning, and ordinary characters, which match themselves. You can specify that the string begin or end with one or more characters from a set, or that it contain any characters except those in a set.

A text pattern consists of metacharacters, which have special meaning in the match string, and nonmetacharacters, which match the characters themselves.
The following tables explain the meaning and use of these metacharacters:

Metacharacter | Meaning | Example
Caret (^) | Matches the beginning of a string | ^C matches C at the beginning of a string
Dollar sign ($) | Matches the end of a string | s$ matches s at the end of a string
Period (.) | Matches any character | . . . matches three consecutive characters
Backslash (\) | Removes the following metacharacter's special characteristics so that it matches itself | \$ matches $
Character class (a group of characters enclosed in square brackets [ ]) | Matches any of the enclosed characters | [AEIOU] matches A, E, I, O, or U. You can use hyphens to abbreviate ranges of characters in a character class. For example, [A-Za-z] matches any letter
Complemented character class (first character inside the brackets is a caret) | Matches any character not in the group following the caret | [^0-9] matches any character except a digit, and [^A-Za-z] matches any character except a letter

The metacharacters asterisk (*), plus (+), and question mark (?) are unary operators that are used to specify repetitions in a regular expression:

Metacharacter | Meaning | Example
* (asterisk) | Indicates zero or more occurrences | A* matches zero or more As (no As, A, AA, AAA, and so on)
+ (plus) | Indicates one or more occurrences | A+ matches one A or more than one A (A, AAA, and so on)
? (question mark) | Indicates zero or one occurrence | A? matches an empty string ("") or A

Sample patterns:
The following table shows various text patterns and sample text that matches each pattern:

This pattern | Matches
AB | Any string that contains AB; such as ABA, DEABC, graphAB_one
B* | Any string that contains 0 or more Bs; such as AC, B, BB, BBB, ABBBC, and so on
AB*C | Any string containing the pattern AC or ABC or ABBC, and so on (0 or more Bs)
AB+C | Any string containing the pattern ABC or ABBC or ABBBC, and so on (1 or more Bs)
ABB*C | Any string containing the pattern ABC or ABBC or ABBBC, and so on (1 B plus 0 or more Bs)
^AB | Any string starting with AB
AB?C | Any string containing the pattern AC or ABC (0 or 1 B)
^[ABC] | Any string starting with A, B, or C
[^ABC] | A string containing any characters other than A, B, or C
^[^abc] | A string that begins with any character except a, b, or c
^[^a-z]$ | Any single-character string that is not a lowercase letter (^ and $ indicate the beginning and end of the string)
[A-Z]+ | Any string with one or more uppercase letters
^[0-9]+$ | Any string consisting only of digits
^[0-9][0-9][0-9]$ | Any string consisting of exactly three digits
^([0-9][0-9][0-9])$ | Any consisting of exactly three digits enclosed in parentheses


mid

mid PowerHome formula function
Description
Obtains a specified number of characters from a specified (interior) position in a string.
Syntax
mid ( string, start, length )
Argument | Description
string | String from which you want characters returned
start | Number. A long specifying the position of the first character you want returned (the position of the first character of the string is 1)
length (optional) | Number. A long whose value is the number of characters you want returned. If you do not enter length or if length is greater than the number of characters to the right of start, Mid returns the remaining characters in the string
Return value
String. Returns characters specified in length of string starting at character start. If start is greater than the number of characters in string, the Mid function returns the empty string (""). If length is greater than the number of characters remaining after the start character, Mid returns the remaining characters. The return string is not filled with spaces to make it the specified length.
Examples
The following examples demonstrate typical syntax/ usage for this function.
. mid ( "[TEMP4]", 2,4)
. if( mid( "[LOCAL1]", 6, 12 ) = "HTTP/1.1 404", "ERROR", "Nextline")


mid

mida PowerHome formula function
Description
Obtains a specified number of bytes from a specified (interior) position in a string.
Syntax
mida ( string, start, length )
Argument | Description
string | String from which you want bytes returned
start | Number. A long specifying the position of the first byte you want returned (the position of the first byte of the string is 1)
length (optional) | Number. A long whose value is the number of bytes you want returned. If you do not enter length or if length is greater than the number of bytes to the right of start, MidA returns the remaining bytes in the string
Return value
String. Returns characters specified by the number of bytes in length of string starting at the byte specified by start. If start is greater than the number of bytes in string, the MidA function returns the empty string (""). If length is greater than the number of bytes remaining after the start byte, MidA returns the remaining bytes. The return string is not filled with spaces to make it the specified length.
Examples
The following examples demonstrate typical syntax/ usage for this function.
. mida ( "[TEMP4]", 2,4)
. if( mida( "[LOCAL1]", 6, 12 ) = "HTTP/1.1 404", "ERROR", "Nextline")


ph_extractval

ph_extractval PowerHome formula function
Description
Extracts a value from a string containing a structured list of name/value pairs
Syntax
ph_extractval ( as_data, as_id, as_sep )
Argument | Description
as_data | String. A string containing a list of name/value pairs. See Usage below.
as_id | String. The ID within the list to extract the value
as_sep | String. The separator character(s) that separate the ID and VALUE data
Return value
String. Returns the VALUE associated with the specified ID (as_id). Returns "*ERROR* - Unable to locate ID" if the ID cant be located. Returns "*ERROR* - Unable to locate value" if the value cant be returned.
Usage
Use this function to quickly search and return values from a structured list contained within as_data. This function expects 1 name/value pair per line with lines separated by carriage return line feed characters (~r~n). The name/value pair is separated from each other by one or more "separator" characters (as_sep). A sample as_data string containing 5 name/value pairs with a "," as the separator character could look like:

Temp,75.0
Humd,55.3
Forecast,Cloudy
Graphic,clouds.jpg
Level,32

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_extractval(ph_readfile("c:\powerhome\data.txt"),"Forecast",",") - Returns the string "Cloudy" if the list above is contained within a file located at c:\powerhome\data.txt


Blank

ph_fill PowerHome formula function
Description
The same as the "fill" function but will not bomb on negative repeat numbers. This function is used to build a repeating string of characters.
Syntax
ph_fill ( fill, repeat )
Argument | Description
fill | String. The string or character to use for the fill. This string will be repeated for the number of times in the repeat parameter.
repeat | Long. The number of times to repeat the fill parameter.
Return value
String. Returns the completed fill pattern.
Usage
Use this function to create repeated strings.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_fill(" ",30) This function will return a string of 30 spaces.
ph_fill("abc",40) This function will return the string "abcabcabcabc".


ph_number

ph_number PowerHome formula function
Description
Use this function to convert a string representation of a number into an actual number.
Syntax
ph_number ( value )
Argument | Description
value | String. The string you'd like to convert into a number.
Return value
Double. The string converted to a number.
Usage
This function will convert a string containing a number (including negative numbers and decimal numbers) into an actual number that can be used where required within formulas. This function primarily exists to handle the problems associated with the negative sign "-".
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_number("-56.25")


ph_pad

ph_pad PowerHome formula function
Description
Multi-purpose string padding function.
Syntax
ph_pad ( input, type, char, len )
Argument | Description
input | String. The string to which you will "pad" characters to.
type | String. The type of padding. Use "L" to leftpad the string. Use "R" to rightpad the string.
char | String. The text to be used to "pad" the input.
len | Long. The total desired length of the padded string.
Return value
String. The input data padded by the char data (L/R) truncated to the len.
Usage
Use this function to left or right pad a string to a desired length.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_pad("arf","L","123",8) This example will return "23123arf".
ph_pad("arf","R","123",8) This example will return "arf12312".


ph_pos

ph_pos PowerHome formula function
Description
Finds one string within another string.
Syntax
ph_pos ( string1, string2 , start )
Argument | Description
string1 | String. The string in which you want to find string2
string2 | String. The string you want to find in string1
start | Integer. A long indicating where the search will begin in string. Unlike the pos and posw functions, this parameter is not optional
Return value
Long. Returns a long whose value is the starting position of the first occurrence of string2 in string1 after the position specified in start. If string2 is not found in string1 or if start is not within string1, ph_pos returns 0.
Usage
The ph_pos function is case sensitive.
Examples
The following examples demonstrate typical syntax/ usage for this function.
Consider the following data which may have been returned by a ph_geturl() function (the data is simplified of course) and stored in LOCAL1 ...

<html>
<body>

<h4>Temperature</h4>
<b>78.5</b>
<h4>Humidity</h4>
<b>55.7</b>
<h4>Wind Speed</h4>
<b>7.5</b>
</body>
</html>

This function is often used in conjunction with other string extraction functions to locate the "sweet spot" where an extraction should take place. For instance ...
ph_pos("[LOCAL1]","Humidity",1)
will find the location of the "H" in the word Humidity in the string, allowing, for instance, a follow-on ph_regexsnap() to extract the data between the next <b> and </b> tags starting at that ph_pos() located starting position.

This function is also very useful in conjunction with the left() function to trim data off the end of a large string so that only the content of interest is being used to avoid "greedy" searches from finding unexpected data.


ph_replaceall

ph_replaceall PowerHome formula function
Description
Replaces all occurrences of a substring within a string with another substring.
Syntax
ph_replaceall ( s, s, s )
Argument | Description
s | The string in which you want to search and replace substrings.
s | The substring you want to search for.
s | The substring you want to replace with.
Return value
String. Returns the string with the replacements made.


ph_replaceallmulti

ph_replaceallmulti PowerHome formula function
Description
Searchs and replaces text within a string of data.
Syntax
ph_replaceallmulti ( input, search, replace )
Argument | Description
input | String. The data to be searched and replaced.
search | String. A ~255 separated list of searches.
replace | String. A ~255 separated list of replaces.
Return value
Returns the input string after all replacements have been completed.
Usage
Use this function to search and replace all occurences of data. You can search and replace multiple different searches by separating them with the PowerHome escape character ~255. If you have fewer replaces than you have searches, then the last replace will be used for the remaining searches.


ph_snapxml

ph_snapxml PowerHome formula function
Description
Retrieves element data within an XML string identified by a sequence of 1 or more element names and a specified instance number
Syntax
ph_snapxml ( as_xml, as_key )
ph_snapxml ( as_xml, as_key, ai_instance )
Argument | Description
as_xml | String. A string containing XML data whose element data you would to extract
as_key | String. An XML element name identifying the attribute. If you want to fully qualify a heirarchy of elements, separate element names with a "<" character. Only the rightmost element name will have its attribute retrieved
ai_instance | Integer (Optional). The matching instance number you would like to retrieve. Use a value of 1 to retrieve the first matching instance. If this parameter is omitted, a value of 1 will be implied
Return value
String. Returns the data between the opening and closing tags of the tag specified in the as_key parameter. Returns "*ERROR* - Could not locate key" if the specified element name sequence and instance could not be found
Usage
Use this function to extract specific attribute values contained within XML data
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_snapxml(ph_readfile("c:\powerhome\phdata.xml"),"row<temperature",3) - Returns the string of data appearing between the 3rd instance of the opening and closing tags of the specified key (temperature) contained in the c:\powerhome\phdata.xml file. The search that is performed must match the format of <row>...<temperature>...</temperature>...</row>


ph_split

ph_split PowerHome formula function
Description
Splits a formatted string that consists of smaller strings separated by a separator character and places the results into local variables.
Syntax
ph_split ( data, sep, local )
Argument | Description
data | String. The data you would like split.
sep | String. The separater character or string.
local | Integer. The starting index of the local variables to have the split strings copied into.
Return value
Long. Returns the number of strings that were split.
Usage
Use this function quickly break apart short strings into individual data. Useful for parsing out data from comma separated values.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_split("70.0,69.5,32.8,65.1,Windy",",",3)
The above example will set [LOCAL3] to 70.0, [LOCAL4] to 69.5, [LOCAL5] to 32.8, [LOCAL6] to 65.1, and [LOCAL7] to Windy.


ph_trim

ph_trim PowerHome formula function
Description
Trims the specified string using the specified trim type.
Syntax
ph_trim ( data, type, trim )
Argument | Description
data | String. The string you would to perform the trim operation on.
type | Integer. The type of trim operation to perform. See usage below.
trim | String. A set of characters that you would like to have trimmed from the string. Use an empty string "" to trim only spaces.
Return value
String. Returns the trimmed string.
Usage
Use this function to perform trim operations on a string. Most trim operations only remove space characters but by specifiying a group of characters in the trim parameter, you can trim other characters as well.

The valid values for the type parameter are detailed below:
0 | Performs a left trim. Characters will be removed from the left
1 | Performs a right trim. Characters will be removed from the right
2 | Performs both a left and right trim. Characters will be removed from both the left and the right.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_trim(" , | & This is a test. & |",2," ,|&")
The above example will return "This is a test."


ph_updatexml

ph_updatexml PowerHome formula function
Description
Updates an attribute in an XML string identified by a sequence of 1 or more element names and a specified instance number
Syntax
ph_updatexml ( as_xml, as_key, ai_instance, as_value )
Argument | Description
as_xml | String. A string containing XML data whose attribute you wish to update
as_key | String. An XML element name identifying the attribute. If you want to fully qualify a heirarchy of elements, separate element names with a "<" character. Only the rightmost element name will have its attribute updated
ai_instance | Integer. The matching instance number you would like to update. Use a value of 1 to update the first matching instance
as_value | String. The value to assign to the matching element attribute
Return value
String. Returns the as_xml string with the identified element attribute updated with the string in as_value. Returns "*ERROR* - Could not locate key" if the specified element name sequence and instance could not be found
Usage
Use this function to update specific attributes within XML data
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_updatexml(ph_readfile("c:\powerhome\phdata.xml"),"row>temperature",3,"76.0") - Returns the full string of XML that was contained in the c:\powerhome\phdata.xml file with the 3rd instance of element names matching <row>...<temperature>...</temperature>...</row>. The value of the temperature element will be "<temperature>76.0</temperature>"


pos

pos PowerHome formula function
Description
Finds one string within another string.
Syntax
pos ( string1, string2 {, start } )
Argument | Description
string1 | String. The string in which you want to find string2
string2 | String. The string you want to find in string1
start (optional) | Integer. A long indicating where the search will begin in string. The default is 1
Return value
Long. Returns a long whose value is the starting position of the first occurrence of string2 in string1 after the position specified in start. If string2 is not found in string1 or if start is not within string1, Pos returns 0.
Usage
The Pos function is case sensitive.

NOTE: This function has a problem searching strings greater than approximately 32000 characters in length. The returned values will be unpredictable.

Use the posw() or ph_pos() functions instead if the string you're searching contains greater than 32000 characters.

Examples
The following examples demonstrate typical syntax/ usage for this function.
Consider the following data which may have been returned by a ph_geturl() function (the data is simplified of course) and stored in LOCAL1 ...

<html>
<body>

<h4>Temperature</h4>
<b>78.5</b>
<h4>Humidity</h4>
<b>55.7</b>
<h4>Wind Speed</h4>
<b>7.5</b>
</body>
</html>

This function is often used in conjunction with other string extraction functions to locate the "sweet spot" where an extraction should take place. For instance ...
pos("[LOCAL1]","Humidity")
will find the location of the "H" in the word Humidity in the string, allowing, for instance, a follow-on ph_regexsnap() to extract the data between the next <b> and </b> tags starting at that pos() located starting position.

This function is also very useful in conjunction with the left() function to trim data off the end of a large string so that only the content of interest is being used to avoid "greedy" searches from finding unexpected data.


pos

posa PowerHome formula function
Description
Finds one string within another string.
Syntax
posa ( string1, string2 {, start } )
Argument | Description
string1 | String. The string in which you want to find string2
string2 | String. The string you want to find in string1
start (optional) | Integer. A long indicating the position in bytes where the search will begin in string. The default is 1
Return value
Long. Returns a long whose value is the starting position of the first occurrence of string2 in string1 after the position in bytes specified in start. If string2 is not found in string1 or if start is not within string1, PosA returns 0.
Usage
The PosA function is case sensitive.

NOTE: This function has a problem searching strings greater than approximately 32000 characters in length. The returned values will be unpredictable.

Use the posw() or ph_pos() functions instead if the string you're searching contains greater than 32000 characters.

Examples
The following examples demonstrate typical syntax/ usage for this function.
Consider the following data which may have been returned by a ph_geturl() function (the data is simplified of course) and stored in LOCAL1 ...

<html>
<body>

<h4>Temperature</h4>
<b>78.5</b>
<h4>Humidity</h4>
<b>55.7</b>
<h4>Wind Speed</h4>
<b>7.5</b>
</body>
</html>

This function is often used in conjunction with other string extraction functions to locate the "sweet spot" where an extraction should take place. For instance ...
posa("[LOCAL1]","Humidity")
will find the location of the "H" in the word Humidity in the string, allowing, for instance, a follow-on ph_regexsnap() to extract the data between the next <b> and </b> tags starting at that pos() located starting position.

This function is also very useful in conjunction with the lefta() function to trim data off the end of a large string so that only the content of interest is being used to avoid "greedy" searches from finding unexpected data.


posw

posw PowerHome formula function
Description
Finds one string within another string.
Syntax
posw ( string1, string2 {, start } )
Argument | Description
string1 | String. The string in which you want to find string2
string2 | String. The string you want to find in string1
start (optional) | Integer. A long indicating where the search will begin in string. The default is 1
Return value
Long. Returns a long whose value is the starting position of the first occurrence of string2 in string1 after the position specified in start. If string2 is not found in string1 or if start is not within string1, Posw returns 0.
Usage
The Posw function is case sensitive.
Examples
The following examples demonstrate typical syntax/ usage for this function.
Consider the following data which may have been returned by a ph_geturl() function (the data is simplified of course) and stored in LOCAL1 ...

<html>
<body>

<h4>Temperature</h4>
<b>78.5</b>
<h4>Humidity</h4>
<b>55.7</b>
<h4>Wind Speed</h4>
<b>7.5</b>
</body>
</html>

This function is often used in conjunction with other string extraction functions to locate the "sweet spot" where an extraction should take place. For instance ...
posw("[LOCAL1]","Humidity")
will find the location of the "H" in the word Humidity in the string, allowing, for instance, a follow-on ph_regexsnap() to extract the data between the next <b> and </b> tags starting at that posw() located starting position.

This function is also very useful in conjunction with the left() function to trim data off the end of a large string so that only the content of interest is being used to avoid "greedy" searches from finding unexpected data.


replace

replace PowerHome formula function
Description
Replaces a portion of one string with another.
Syntax
replace ( string1, start, n, string2 )
Argument | Description
string1 | The string in which you want to replace characters with string2
start | A long whose value is the number of the first character you want replaced. (The first character in the string is number 1)
n | A long whose value is the number of characters you want to replace
string2 | The string that will replace characters in string1. The number of characters in string2 can be greater than, equal to, or fewer than the number of characters you are replacing
Return value
String. Returns the string with the characters replaced if it succeeds and the empty string ("") if it fails.
Usage
If the start position is beyond the end of the string, Replace appends string2 to string1. If there are fewer characters after the start position than specified in n, Replace replaces all the characters to the right of character start.

If n is zero, then in effect Replace inserts string2 into string1.


replacea

replacea PowerHome formula function
Description
Replaces a portion of one string with another.
Syntax
replacea ( string1, start, n, string2 )
Argument | Description
string1 | The string in which you want to replace bytes with string2
start | A long whose value is the number of the first byte you want replaced. (The first byte in the string is number 1)
n | A long whose value is the number of bytes you want to replace
string2 | The string that will replace bytes in string1. The number of bytes in string2 can be greater than, equal to, or fewer than the number of bytes you are replacing
Return value
String. Returns the string with the bytes replaced if it succeeds and the empty string ("") if it fails.
Usage
If the start position is beyond the end of the string, Replace appends string2 to string1. If there are fewer bytes after the start position than specified in n, Replace replaces all the bytes to the right of character start.

If n is zero, then in effect Replace inserts string2 into string1.


right

right PowerHome formula function
Description
Obtains a specified number of characters from the end of a string.
Syntax
right ( string, n )
Argument | Description
string | The string from which you want characters returned
n | A long whose value is the number of characters you want returned from the right end of string
Return value
String. Returns the rightmost n characters in string if it succeeds and the empty string ("") if an error occurs.

If n is greater than or equal to the length of the string, Right returns the entire string. It does not add spaces to make the return value's length equal to n.
Examples
The following examples demonstrate typical syntax/ usage for this function.
• right("[LOCAL1]",10) --> get the last 10 characters from the string.
• if( right( "[LOCAL1]", 12 ) = "HTTP/1.1 404", "ERROR", "Nextline") --> Return "ERROR" if the last 12 characters indicate an HTTP error.


righta

righta PowerHome formula function
Description
Obtains a specified number of bytes from the end of a string.
Syntax
righta ( string, n )
Argument | Description
string | The string from which you want bytes returned
n | A long whose value is the number of bytes you want returned from the right end of string
Return value
String. Returns the rightmost n bytes in string if it succeeds and the empty string ("") if an error occurs.

If n is greater than or equal to the length of the string, Right returns the entire string. It does not add spaces to make the return value's length equal to n.
Examples
The following examples demonstrate typical syntax/ usage for this function.
. righta("[LOCAL1]",10) --> get the last 10 bytes from the string.
. if( righta( "[LOCAL1]", 12 ) = "HTTP/1.1 404", "ERROR", "Nextline") --> Return "ERROR" if the last 12 bytes indicate an HTTP error.


righttrim

righttrim PowerHome formula function
Description
Removes spaces from the end of a string.
Syntax
righttrim ( string )
Argument | Description
string | The string you want returned with trailing blanks deleted
Return value
String. Returns a copy of string with trailing blanks deleted if it succeeds and the empty string ("") if an error occurs.


space

space PowerHome formula function
Description
Builds a string of the specified length whose value consists of spaces.
Syntax
space ( n )
Argument | Description
n | A long whose value is the length of the string you want filled with spaces
Return value
String. Returns a string filled with n spaces if it succeeds and the empty string ("") if an error occurs.


trim

trim PowerHome formula function
Description
Removes leading and trailing spaces from a string.
Syntax
trim ( string )
Argument | Description
string | The string you want returned with leading and trailing spaces deleted.
Return value
String. Returns a copy of string with all leading and trailing spaces deleted if it succeeds and the empty string ("") if an error occurs.


clipboard

clipboard PowerHome formula function
Description
Retrieves or replaces the contents of the system clipboard with text.
Syntax
clipboard ( { string } )
Argument | Description
string (optional) | A string whose value is the text you want to place in the clipboard. The string replaces the current contents of the clipboard, if any.
Return value
String. Returns the current contents of the clipboard if the clipboard contains text. If string is specified, Clipboard returns the current contents and replaces it with string.

Returns the empty string ("") if the clipboard is empty or it contains nontext data, such as a bitmap. If string is specified, the nontext data is replaced with string. If string is NULL, Clipboard returns NULL.


ph_closewindow

ph_closewindow PowerHome formula function
Description
Sends both WM_CLOSE and WM_SYSCOMMAND windows messages to the supplied window handle to force the window closed.
Syntax
ph_closewindow ( handle )
Argument | Description
handle | Long. The handle of the window you wish to close.
Return value
Integer. Returns a 0.
Usage
Use the ph_findwindow function or it's derivatives to get the handle of the window you wish to close.


ph_debuginfo

ph_debuginfo PowerHome formula function
Description
Returns debug information associated with the active PowerHome controllers and internal PowerHome variables. This is the same information that is returned by the menu option "Debug Info" under the "File" menu
Syntax
ph_debuginfo ( )
Argument Description
Return value
String. Returns the generated debug information for internal PowerHome variables and controls as well as internal information for each of the active controllers defined within PowerHome.
Usage
Use this function to peek at what is going on within PowerHome in order to debug potential issues or problems
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_debuginfo()


ph_exporteventlog

ph_exporteventlog PowerHome formula function
Description
Allows you to export the PowerHome eventlog into a file format of your choice with the option to trim the log.
Syntax
ph_exporteventlog ( start, end, type, filename, colheading, trim )
Argument | Description
start | A datetime representing the first row to export.
end | A datetime representing the last row to export.
type | An integer representing the type of file to export to. See Usage for details.
filename | A string representing the directory and filename to export to.
colheading | An integer representing whether column headings should be exported or not. A value of 0 will save without column headings. Any other value will save with column headings.
trim | An integer representing whether to trim the exported records or not. A value of 0 will cause the log NOT to be trimmed. Any other value will have the exported records trimmed from the weblog and eventlog tables.
Return value
Long. Returns the number of rows actually exported. Returns a negative number if an error occurs. - 1 is returned if an error occurs during the retrieval. - 2 is returned if an error occurs while exporting the rows. - 3 is returned if an error occurs while trimming the weblog table. - 4 is returned if an error occurs while trimming the eventlog table.
Usage
The following export types are supported. 0 = Excel, 1 = Text, 2 = Comma separated values, 3 = SYLK, 4 = WKS (Lotus), 5 = WK1 (Lotus), 6 = DIF, 7 = Dbase2, 8 = Dbase3, 9 = SQL Insert statements, 10 = Clipboard, 11 = PSR Report, 12 = Windows Metafile, 13 = HTML Table, 14 = Excel 5, 15 = XML, 16 = XSLFO, 17 = PDF, 18 = Excel 8. Any other value will default to type 1 which is text.


ph_findwindow

ph_findwindow PowerHome formula function
Description
Finds a window of a currently running application.
Syntax
ph_findwindow ( s, n )
Argument | Description
s | The title or classname of the window you wish to retrieve the handle of.
n | An integer representing the type of find window to be performed. Use a 0 if you wish to search using the classname of the window. Use a 1 if you wish to search using the title of the window.
Return value
Long. Returns the handle of the window if found.


ph_findwindowex

ph_findwindowex PowerHome formula function
Description
Finds a child window of a currently running parent window.
Syntax
ph_findwindowex ( n, n, n, s, n )
Argument | Description
n | The handle of the parent window.
n | The handle at which to start searching for child windows. Normally, set this value to 0.
n | The instance of the desired child window. A parent window may have multiple matching child windows for the specified criteria. This parameter determines which instance is returned. Use 0 for the first matching child window, 1 for the second matching child window, etc.
s | The title or classname of the child window you wish to retrieve the handle of.
n | An integer representing the type of find window to be performed. Use a 0 if you wish to search using the classname of the child window. Use a 1 if you wish to search using the title of the child window.
Return value
Long. Returns the handle of the child window if found.


ph_funcdef

ph_funcdef PowerHome formula function
Description
This function will return the function definition of any of the PowerHome specific functions (ph_???)
Syntax
ph_funcdef ( function )
Argument | Description
function | String. The name of the function you'd like to return the definition of.
Return value
String. Returns the function definition of the specified function showing argument types and names.
Usage
Use this function to view the definition for any PowerHome specific function that may not be documented in the help file. Use the ph_funclist function to return a list of all PowerHome specific functions.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_funcdef("ph_insteonwithret") The result of this function will be: integer ph_insteonwithret (string as_id, integer ai_cmd1, integer ai_cmd2)


ph_funclist

ph_funclist PowerHome formula function
Description
Retrieves a list of all PowerHome specific function names.
Syntax
ph_funclist ( )
Argument Description
Return value
String. Returns the list of function names separated by carriage return / linefeed characters.
Usage
Use this function to retrieve a list of function names of PowerHome internal functions. This is useful in case an update does not have the function documented yet. Once you have a name, you can use the ph_funcdev function to retrieve its definition.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_funclist()
This example will return all of the function names. The first few lines of a typical call is displayed below:
d2h
f_phfnver
h2d
h2s
ph_addtoglobal
ph_addtovar


ph_getclassname

ph_getclassname PowerHome formula function
Description
Returns the Classname of the specified handle.
Syntax
ph_getclassname ( n )
Argument | Description
n | The handle for which you want the classname.
Return value
String. Returns up to the first 256 characters of the classname for the specified handle.


ph_getexefromhandle

ph_getexefromhandle PowerHome formula function
Description
Given a Windows handle, returns the path and filename of the executable that launched it.
Syntax
ph_getexefromhandle ( handle )
Argument | Description
handle | Long. The handle whose executable you wish returned.
Return value
String. Returns the path and filename for the specified handle.


ph_gethandle

ph_gethandle PowerHome formula function
Description
Returns the handle of an internal PowerHome window.
Syntax
ph_gethandle ( type )
Argument | Description
type | An integer representing the particular window whose handle you wish to be returned. Use 0 for the PowerHome frame window (returns same value as ph_handle). Use 1 for the Client Control Center. Use 2 for the Device Status window. Use 3 for the PowerHome Web window. Use 4 for the Insteon Explorer window.
Return value
Long. Returns the Windows handle of the specified window. Returns 0 if the window is not open or an invalid type is specified.


ph_getlasterror

ph_getlasterror PowerHome formula function
Description
Returns the error number of the last error for certain functions.
Syntax
ph_getlasterror ( )
Return value
Integer. Returns the error number associated with the last error. Available after calling the following functions: ph_evalscript, ph_executescript, ph_runscript_0, ph_runscript_1, ph_runscript_2, ph_runscript_3, ph_runscript_4, ph_runscript_5


ph_getlasterrorstring

ph_getlasterrorstring PowerHome formula function
Description
Returns a text representation of the last error that occured within PowerHome
Syntax
ph_getlasterrorstring ( )
Argument Description
Return value
String. The last error that occured as a text string.
Usage
Use this function to retrieve the last error description.
Examples
The following examples demonstrate typical syntax/usage for this function. This function should be executed immediately after detecting an internal error.
ph_getlasterrorstring()


ph_getmode

ph_getmode PowerHome formula function
Description
Returns the operating mode that PowerHome is currently running in.
Syntax
ph_getmode ( )
Return value
Integer. Returns the mode that PowerHome is currently running in. Returns a 0 if PowerHome is operating in "Normal" mode and returns a 1 if PowerHome is running in "Restricted" mode.


ph_getparent

ph_getparent PowerHome formula function
Description
Returns the parent handle of the specified handle.
Syntax
ph_getparent ( n )
Argument | Description
n | The handle of the window you are retrieving the parent handle for.
Return value
Long. Returns the parent handle of the specified window.


ph_getsyspwrstat

ph_getsyspwrstat PowerHome formula function
Description
This function retrieves power related status from the Windows system.
Syntax
ph_getsyspwrstat ( parm )
Argument | Description
parm | String. The specific power parameter you're requesting information on. See Usage info for valid values.
Return value
Long. Returns the requested parameter status.
Usage
This function will return values associated with power from the Windows OS. If a UPS is connected (serial or USB) to the PowerHome PC for monitoring, PowerHome can query and retrieve the various status values.

Below are the valid values for the parm parameter.
aclinestat | Returns the status of the AC power. Returns 1 if AC is up, 0 if the UPS is running on battery.
batteryflag | Returns the status of the battery. 1 is returned if the battery level is at least 66%. 2 is returned if the battery is less than 33%. 4 is returned if the battery level is less than 5%. 8 is returned if the battery is charging. 128 is returned if there is no battery. 255 is returned if the battery is not able to be read.
batterylifepct | Returns the remaining level of battery as a percentage. This would be 100 at fully charged and 0 at fully discharged.
batterylifetime | Returns the number of seconds of battery life remaining.
batteryfulllifetime | Returns the number of seconds of battery life when at full charge.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_getsyspwrstat("batterylifepct")
The above example will return the a number from 0 to 100 (255 if unknown) representing the battery percentage.


ph_getsysvol

ph_getsysvol PowerHome formula function
Description
Returns the current system volume level.
Syntax
ph_getsysvol ( )
Return value
Long. Returns the volume level that the system is currently set to. This value will be between the min and max volume levels as returned by the ph_getsysvolmin and ph_getsysvolmax functions respectively. If a negative value is returned, then an error occurred.


ph_getsysvolmax

ph_getsysvolmax PowerHome formula function
Description
Returns the maximum level that the system volume can be set to.
Syntax
ph_getsysvolmax ( )
Return value
Long. Returns the maximum volume level that the system can be set to. If a negative value is returned, then an error occurred.


ph_getsysvolmin

ph_getsysvolmin PowerHome formula function
Description
Returns the minimum level that the system volume can be set to.
Syntax
ph_getsysvolmin ( )
Return value
Long. Returns the minimum volume level that the system can be set to. If a negative value is returned, then an error occurred.


ph_gettimezoneinfo

ph_gettimezoneinfo PowerHome formula function
Description
Returns information concerning the timezone currently configured on the PowerHome computer
Syntax
ph_gettimezoneinfo ( ai_type )
Argument | Description
ai_type | Integer. The type of information to be returned. Valid values are 0 thru 7. See Usage below
Return value
String. Returns the specified timezone information based upon the ai_type parameter
Usage
Use this function to return timezone information concerning the PowerHome computer.

Valid values for the ai_type parameter:

  • 0 - Returns the Timezone ID. A 0 return indicates the Timezone ID is Unknown. 1 indicates standard time. 2 indicates daylight savings time.
  • 1 - Returns the text equivalent for standard time.
  • 2 - Returns the text equivalent for daylight savings time.
  • 3 - Returns the base offset from UTC in minutes.
  • 4 - Returns the standard time offset bias
  • 5 - Returns the daylight savings time offset bias
  • 6 - Returns the date that standard time starts for the current year
  • 7 - Returns the date that daylight savings starts for the current year
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_gettimezoneinfo(3) - Returns the base offset from UTC in minutes. Assuming a timezone of EST, this value will be "300"
    . 0 - integer(ph_gettimezoneinfo(3)) + integer(ph_gettimezoneinfo(if(integer(ph_gettimezoneinfo(0)) < 2,4,5))) - Returns the actual offset (as an integer) in minutes of the current timezone. This takes into account whether its currently standard time or daylight savings time. In the case of EST on May 7th, 2020, the return value will be -240


ph_getvarsub

ph_getvarsub PowerHome formula function
Description
Returns the value of the variable substitution parameter.
Syntax
ph_getvarsub ( )
Argument | Description
Return value
Integer. The value of the variable substitution parameter. If variable substitution is enabled, then 1 is returned. If variable substitution is disabled then 0 is returned.
Usage
Within the pwrhome.ini file under the [Script] section is a parameter named VARSUBSTITUTION. If this parameter is set to NO, then variable substitution is disabled and syntax such as [LOCAL1] or {TEMP} within formulas will NOT be substituted and will instead be interpreted as literal text. If the parameter is set to YES, then variable substitution will be performed.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_getvarsub()


ph_getversion

ph_getversion PowerHome formula function
Description
Returns the version of your currently running PowerHome
Syntax
ph_getversion ( )
ph_getversion ( ai_type )
Argument | Description
ai_type | Integer (Optional). A numeric value representing what type of the version you wish returned. If this parameter is omitted then a value of 0 is assumed. See Usage below for other allowed values
Return value
String. Returns the version of PowerHome that you are running formatted as a string.
Usage
Use this function to return the PowerHome version that is running. Prior to version 2.2, a single value was used to determine the PowerHome version. Starting with PowerHome version 2.2, a subversion value was added to track minor version differences.

The optional ai_type parameter determines the components that are returned that make up the version number. A value of 0 will return the main PowerHome version number. A value of 1 will return the sub version information. A value of 2 will return the combined version and sub version values together (this is what would be displayed in the Help->About window). Any other value will be treated as a 0. It should be noted that the sub version value may be blank in some versions of PowerHome

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getversion(2) - Returns "2.2 beta2" for the 2nd beta version of PowerHome 2.2


ph_getwindow

ph_getwindow PowerHome formula function
Description
Retrieves a handle to a window that has the specified relationship to the specified window.
Syntax
ph_getwindow ( n, n )
Argument | Description
n | The handle of the master window.
n | A flag representing the relationship between the master window and the window being searched for.
Return value
Long. Returns the handle of window specified based upon the master window and the relationship flags.
Usage
This function calls the Windows API function GetWindow. The following relationship flags are available: 0 = GW_HWNDFIRST, 1 = GW_HWNDLAST, 2 = GW_HWNDNEXT, 3 = GW_HWNDPREV, 4 = GW_OWNER, 5 = GW_CHILD


ph_getwindowstate

ph_getwindowstate PowerHome formula function
Description
Returns the state of the PowerHome frame window.
Syntax
Return value
Integer. Returns 1 if the PowerHome frame is minimized. Returns 2 if the PowerHome frame is maximized. Returns 0 if the PowerHome frame is in a normal state.


ph_getwindowtext

ph_getwindowtext PowerHome formula function
Description
Retrieves the title of the window specified by handle.
Syntax
ph_getwindowtext ( n )
Argument | Description
n | The handle of the window whose title you wish returned.
Return value
String. Returns the title of the specified window.


ph_guid

ph_guid PowerHome formula function
Description
Generates a random Windows GUID value.
Syntax
ph_guid ( )
Return value
String. Returns a random GUID value.


ph_handle

ph_handle PowerHome formula function
Description
Returns the handle of the PowerHome frame.
Syntax
ph_handle ( )
Return value
Long. Returns the Windows handle of the Main PowerHome frame.


ph_handle1

ph_handle1 PowerHome formula function
Description
Returns the handle of the PowerHome Lookup window.
Syntax
ph_handle1 ( )
Return value
Long. Returns the handle of the PowerHome Lookup window.


ph_isssrunning

ph_isssrunning PowerHome formula function
Description
Returns whether or not a screensaver is currently running on the PowerHome machine
Syntax
ph_isssrunning ( )
Argument | Description
Return value
Integer. Returns 1 if a screensaver is currently active. Returns 0 if not.
Usage
Use this function to detect if the PowerHome machine is currently unattended or not.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_isssrunning()


ph_iswslocked

ph_iswslocked PowerHome formula function
Description
Determines whether the PowerHome machine is currently locked or not.
Syntax
ph_iswslocked ( )
Argument | Description
Return value
Integer. Returns 1 if the PowerHome workstation machine is currently locked. Returns 0 if its not locked. Returns - 1 if there is error getting a handle to the desktop.
Usage
Use this function to determine if the PowerHome machine is locked or not.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_iswslocked()


ph_killprocess

ph_killprocess PowerHome formula function
Description
Kills the specified running Windows process.
Syntax
ph_killprocess ( process )
Argument | Description
process | Long. The process you wish to kill.
Return value
Long. Returns nonzero if the function succeeds and 0 if the function fails. Use ph_listprocesses or ph_locateprocess to determine the process you wish to kill.
Usage
Terminating a process can cause problems and should only be used if other methods fail.


ph_listprocesses

ph_listprocesses PowerHome formula function
Description
Returns a list of currently running processes
Syntax
ph_listprocesses ( type )
Argument | Description
type | Integer. The type of list to return. 0 returns only the EXE name. 1 returns the full path and EXE name.
Return value
String. Returns the list in a string of lines with 1 line per process. Lines are separated by cr/lf pairs. Each line contains two values separated by a tab character. The first value is either the EXE filename or the path and EXE filename. The second parameter is the actual process number. Use ph_getline/ph_parseline or the ph_regex functions to extract individual values.


ph_locatehandle

ph_locatehandle PowerHome formula function
Description
Locates and returns the handle of a process identifed by the specified parameters.
Syntax
ph_locatehandle ( parentexe, parentclass, parenttitle, parentinstance, parentflags, childclass, childtitle, childinstance, childflags )
Argument | Description
parentexe | String. A string representing the filename of the parent processes executable.
parentclass | String. The class of the process that is the parent of the process to be located.
parenttitle | String. The title of the window that is the parent of the process to be located.
parentinstance | Integer. The instance of the parent whose child process you're locating. The first instance is 0.
parentflags | Integer. Flags representing which of the previous parameters to use for locating the parent. Individual values should be added. 1 - Use parentexe, 2 - Use parentclass, 4 - Use parenttitle exact, 8 - Use parenttitle partial.
childclass | String. The class of the child process you're searching for.
childtitle | String. The title of the child process you're searching for.
childinstance | Integer. The instance of the child process you're searching for. The first instance is 0.
childflags | Integer. Flags that determine which of the child parameters to use. Individual values should be added. If the handle to locate is identified by the parent, use 0 to ignore the child parameters. 1 - Use child parameters, 2 - Use childclass, 4 - Use childtitle exact, 8 - Use childtitle partial.
Return value
Long. Returns the handle of the located process. Use the PowerHome "Object Spy" window for help in populating this function.


ph_locatehandle1

ph_locatehandle1 PowerHome formula function
Description
Locates and returns the handle of a process identifed by the specified parameters.
Syntax
ph_locatehandle1 ( handle, exe, class, title, instance, flags )
Argument | Description
handle | Long. The handle from where to begin the search. If 0, then the search begins with top windows processes. If other than 0, then the search will begin with children of the specified handle.
exe | String. The executable name of the process to match. Controlled by the flags parameter.
class | String. The class name of the process to match. Controlled by the flags parameter.
title | String. The title of the process to match. Can be an exact match or a partial match and is controlled by the flags parameter.
instance | Integer. The matching instance to return the handle of. For a specific set of parameters, multiple matches may be returned as determined by the Z-order. If instance = 0, then the handle of the first match will be found. If 1, then the second match handle will be returned, etc.
flags | Integer. Controls which of the 3 parameters above (exe, class, title) to use in the search. See usage below.
Return value
Long. Returns the handle of the specified matching process.
Usage
Use this function to retrieve the handle of specified processes.

The flags parameter is detailed in the table below:
1 | Add 1 to the flags parameter to match on the specified exe.
2 | Add 2 to the flags parameter to match on the specified class name.
4 | Add 4 to the flags parameter to exactly match on the specified title.
8 | Add 8 to the flags parameter to partially match on the specified title. The way this match works is if the title you specifiy is 10 characters long, it must match the first 10 characters of the searched title in order to be a match.
To match on exe and the exact title, you would add 1 and 4 together to arrive at 5 for the flags parameter. Values 4 and 8 should be considered mutually exclusive of one another (you would never add both 4 and 8 to the flags parameter).
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_locatehandle1(0,"Explorer.EXE","","logs",0,5)
The above example will search for the first instance of Windows Explorer whose title is "logs" and returns the handle if found.


ph_locateprocess

ph_locateprocess PowerHome formula function
Description
Locates the process value for the specified exe.
Syntax
ph_locateprocess ( exe, instance )
Argument | Description
exe | String. The exe filename or path and exe filename whose process you want.
instance | Integer. The instance of the exe to locate. The first instance is 0.
Return value
Long. Returns the process of the specified EXE. If the exe value contains a full path, then the search will be on the full path and filename, otherwise, the search will be just for the filename.


ph_lockworkstation

ph_lockworkstation PowerHome formula function
Description
This function will lock the PowerHome workstation.
Syntax
ph_lockworkstation ( )
Argument | Description
Return value
Long. This function will return non-zero if the lock operation has been successfully initiated (it does not return success since the process executed asynchronously). 0 is returned if there is an error.
Usage
Use this function lock the PowerHome workstation.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_lockworkstation()


ph_openframe

ph_openframe PowerHome formula function
Description
Returns the PowerHome main frame window to its last saved state (with ph_saveframe)
Syntax
ph_openframe ( )
Return value
Integer. Returns a 0. Use this function in conjunction with the ph_saveframe function.


ph_openphwin

ph_openphwin PowerHome formula function
Description
Opens a specific PowerHome Window.
Syntax
ph_openphwin ( type )
Argument | Description
type | Integer. The type of PowerHome window to open. 1 - Control Center, 2 - Device Status, 3 - Web Center, 4 - PowerHome Explorer, 5 - Insteon Explorer, 6 - PowerHome Status, 7 - Palmpad, 8 - Eventlog, 9 - Multi-Editor
Return value
Long. Returns the handle to the newly opened window.


ph_playsound

ph_playsound PowerHome formula function
Description
Plays a WAV file.
Syntax
ph_playsound ( wav, flags )
Argument | Description
wav | A string defining the path and wav file to be played.
flags | An unsignedinteger which represents how the wav file is to be played. Valid values which can be added (OR'ed) together are: 0 - Function returns after wav is played. 1 - Function returns immediately after wav starts playing. 2 - If file not found, play nothing. 4 - Play wav from memory instead of disk. 8 - Loop until function is called again with flags set to null. Should be combined with 1. 16 - If sound system is busy, don't stop the currently playing sound and return without playing.
Return value
Integer. Returns a 0 if a wav capable device is present in the system, otherwise a 1 is returned.


ph_playwinmsg

ph_playwinmsg PowerHome formula function
Description
Plays back Windows messages to multiple located handles.
Syntax
ph_playwinmsg ( parentexe, parentclass, parenttitle, parentinstance, parentflags, childinfo, messages )
Argument | Description
parentexe | String. A string representing the filename of the parent processes executable.
parentclass | String. The class of the process that is the parent of the process to be located.
parenttitle | String. The title of the window that is the parent of the process to be located.
parentinstance | Integer. The instance of the parent whose child process you're locating. The first instance is 0.
parentflags | Integer. Flags representing which of the previous parameters to use for locating the parent. Individual values should be added. 1 - Use parentexe, 2 - Use parentclass, 4 - Use parenttitle exact, 8 - Use parenttitle partial.
childinfo | String. A string identifying the multiple child processes whose handles to have messages played to.
messages | String. The string of Windows messages to be played.
Return value
Integer. Returns 0 if successful. 1 if the parent cannot be found, 2 if a child cannot be found, 3 if an index referenced in the message does not exist, 4 if childinfo is malformed on childtitle, 5 if childinfo is malformed on childinstance, 6 if childinfo is malformed on childflags, 7 if messages is malformed on msg, 8 if messages is malformed on wparam, 9 if messages is malformed on lparam
Usage
Use this function to playback complicated sequences of Windows messages to multiple dynamic Windows processes and handles. Use the PowerHome Object Spy window to assist in creating functions of this type.

The childinfo parameter contains 0 or more child process "indexes", each index entry containing class, title, instance, and flags all separated by tabs. The parent is considered index 1 with the first child entry considered index 2. See ph_locatehandle for an explanation of the childinfo entries. A typical childinfo entry containing two indexes may look like this: "Notepad~tUntitled - Notepad~t0~t7~tEdit~t~t0~t3~t".

The messages parameter consists of 1 or more messages to be sent to an index. Each individual message consists of 4 parameters separated by commas. These parameters are: index, msgnum, wparam, and lparam.


ph_postcopydata

ph_postcopydata PowerHome formula function
Description
Posts a Windows WM_COPYDATA message.
Syntax
ph_postcopydata ( handle, wparam, longdata, stringdata )
Argument | Description
handle | The handle to which you want to send the message.
wparam | The wparam data. This would typically be the handle of the calling program.
longdata | An unsigned long representing the dwdata parameter of a COPYDATASTRUCT.
stringdata | A string of data that will be placed in the lpdata parameter of a COPYDATASTRUCT.
Return value
Long. Returns a 0. This formula will populate a COPYDATASTRUCT and send a WM_COPYDATA message (message number 74) to the window pointed to by handle. The wparam argument can be any long value but is typically the handle of the calling program. The longdata argument will be copied into the dwdata parameter of the COPYDATASTRUCT. The stringdata will be pointed to by the lpdata parameter of a COPYDATASTRUCT.


ph_postmsg

ph_postmsg PowerHome formula function
Description
Posts a Windows message.
Syntax
ph_postmsg ( handle, msgnum, wparam, lparam )
Argument | Description
handle | The handle to which you want to send the message.
msgnum | The message number you wish to send.
wparam | The wparam you want sent with the message.
lparam | The lparam you want sent with the message.
Return value
Long. Returns a 0. This formula will send a Windows message to the window pointed to by handle. Please refer to the Microsoft Windows SDK for additional information concerning Windows messages.


ph_postmsg_s

ph_postmsg_s PowerHome formula function
Description
Posts a Windows message. The address in memory of the string parameter will be passed as the lparam value.
Syntax
ph_postmsg_s ( handle, msgnum, wparam, string )
Argument | Description
handle | The handle to which you want to send the message.
msgnum | The message number you wish to send.
wparam | The wparam you want sent with the message.
string | A string whose address in memory will be sent as the lparam.
Return value
Long. Returns a 0. This formula will send a Windows message to the window pointed to by handle. The address of the string parameter in memory will be automatically calculated and this value will be passed as the lparam value. Please refer to the Microsoft Windows SDK for additional information concerning Windows messages.


ph_processfromhandle

ph_processfromhandle PowerHome formula function
Description
Returns the process that is associated with the specified handle
Syntax
ph_processfromhandle ( al_handle )
Argument | Description
al_handle | Long. The handle you would like to get the process for
Return value
Long. Returns the process associated with the handle in al_handle
Usage
Use this function to get the process for a handle.

A handle is a numeric reference that identifies an object in the operating system. A window has a handle. A menu has a handle. Individual components on a window may also have a handle. The ph_handle( ) function returns the handle that is assigned to the PowerHome program. You can use the Window Spy screen under the PowerHome Maintenance menu to inspect the handles of various operating system objects. You can also use the ph_locatehandle( ) and ph_locatehandle1( ) functions to programmatically determine the handles of objects.

A process is a numeric reference that is assigned to an executing program. If you launch a notepad.exe window, the window will have a handle, the menu will have a different handle, the area where you type characters will have a handle. All of these handles are ultimately associated with the process that spawned their creation. By supplying any of the handles associated with a particular running instance of notepad.exe, this function will return the process. When you have a process, you can then use functions such as ph_killprocess( ) to terminate the execution of a process.

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_processfromhandle(ph_findwindow("Untitled - Notepad",1)) - Returns the process associated with the handle of a running instance of notepad.exe


ph_regactivex

ph_regactivex PowerHome formula function
Description
Registers the activex controls (as the current PowerHome user) that are listed in the activex table.
Syntax
ph_regactivex ( )
Return value
Integer. Returns a 0.
Usage
Use this function to register the activex controls listed in the PowerHome activex table. This table default contains all the activex controls that are default used by PowerHome. This function is useful to allow PowerHome to run properly as a service. This function performs the same action as the menu option File|Register ActiveX.


ph_savedesktopimage

ph_savedesktopimage PowerHome formula function
Description
Takes a snapshot of the current desktop window and saves it to a graphic file.
Syntax
ph_savedesktopimage ( filename, width, height )
Argument | Description
filename | String. The path and filename to save the desktop image to.
width | Long. The optional resize width of the saved image.
height | Long. The optional resize height of the saved image.
Return value
Integer. Returns a 0.
Usage
Use this funciton save a snapshot of the current desktop window to a graphic file. The graphic type to save as will be determined by the filename extension. Supported types are BMP, JPEG, PNG, TIFF, WBMP, and GIF. Setting the width and height values to 0 will cause the saved graphic file to be at the current desktop resolution. If you wish to resize the graphic before saving, set the width and height values appropriately.


ph_saveframe

ph_saveframe PowerHome formula function
Description
Save the current state of the PowerHome frame window (position, size, etc). You can restore to this saved state using the ph_openframe function.
Syntax
ph_saveframe ( )
Return value
Integer. Returns a 0. Use this function in conjunction with the ph_openframe function.


ph_scrapetext

ph_scrapetext PowerHome formula function
Description
Retrieves text associated with a handle via Windows message 13.
Syntax
ph_scrapetext ( handle )
Argument | Description
handle | Long. The handle whose text you wish to retrieve.
Return value
String. Returns the text associated with the handle by issuing a Windows message 13 to the handle.


ph_sendcopydata

ph_sendcopydata PowerHome formula function
Description
Sends a Windows WM_COPYDATA message.
Syntax
ph_sendcopydata ( handle, wparam, longdata, stringdata )
Argument | Description
handle | The handle to which you want to send the message.
wparam | The wparam data. This would typically be the handle of the calling program.
longdata | An unsigned long representing the dwdata parameter of a COPYDATASTRUCT.
stringdata | A string of data that will be placed in the lpdata parameter of a COPYDATASTRUCT.
Return value
Long. Returns the result of the sendmsg. This formula will populate a COPYDATASTRUCT and send a WM_COPYDATA message (message number 74) to the window pointed to by handle. The wparam argument can be any long value but is typically the handle of the calling program. The longdata argument will be copied into the dwdata parameter of the COPYDATASTRUCT. The stringdata will be pointed to by the lpdata parameter of a COPYDATASTRUCT. This function will wait for a return from the sendmsg.


ph_sendmsg

ph_sendmsg PowerHome formula function
Description
Sends a Windows message.
Syntax
ph_sendmsg ( handle, msgnum, wparam, lparam )
Argument | Description
handle | The handle to which you want to send the message.
msgnum | The message number you wish to send.
wparam | The wparam you want sent with the message.
lparam | The lparam you want sent with the message.
Return value
Long. Returns the result of the sendmsg. This formula will send a Windows message to the window pointed to by handle. Please refer to the Microsoft Windows SDK for additional information concerning Windows messages. This formula will wait for the return value of the sendmsg.


ph_sendmsg_s

ph_sendmsg_s PowerHome formula function
Description
Sends a Windows message. The address in memory of the string parameter will be passed as the lparam value.
Syntax
ph_sendmsg_s ( handle, msgnum, wparam, string )
Argument | Description
handle | The handle to which you want to send the message.
msgnum | The message number you wish to send.
wparam | The wparam you want sent with the message.
string | A string whose address in memory will be sent as the lparam.
Return value
Long. Returns the result of the sendmsg. This formula will send a Windows message to the window pointed to by handle. The address of the string parameter in memory will be automatically calculated and this value will be passed as the lparam value. Please refer to the Microsoft Windows SDK for additional information concerning Windows messages.


ph_setforegroundwindow1

ph_setforegroundwindow1 PowerHome formula function
Description
Brings the window of the specified handle to the foreground.
Syntax
ph_setforegroundwindow1( n )
Argument | Description
n | The handle of the window you wish to bring to the foreground.
Return value
Integer. Returns 0 if successful. Returns 1 if the helper EXE does not run. Returns 2 if the function fails. Returns 3 if PowerHome is shutdown while the function is executing.
Usage
Use this function as an alternative to the ph_setforegroundwindow function. This function uses a different technique to set the foreground window that may be more successful depending upon the window being brought to the foreground and the current status of PowerHome including the user that PowerHome is being run under. The PHSETFG.EXE file is a helper executable for this function.


ph_setframe

ph_setframe PowerHome formula function
Description
Allows you to programmatically control the state and size/position of the PowerHome main application window.
Syntax
ph_setframe ( state, x, y, width, height )
Argument | Description
state | Integer. Controls the state of the frame. Use 0 for normal. Use 1 for minimized. Use 2 for maximized.
x | Integer. The x position of the upper left corner of the frame. Set this value to a negative number to not change the x position.
y | Integer. The y position of the upper left corner of the frame. Set this value to a negative number to not change the y position.
width | Integer. The desired width of the frame. Set this value to 0 or negative to not change the width.
height | Integer. The desired height of the frame. Set this value to 0 or negative to not change the height.
Return value
Integer. Returns 0 if successful. Returns 1 if the state parm is 0 and the frame is currently in kiosk mode (see ph_setmode function). Returns 1 if PowerHome is currently in kiosk mode and any of the x, y, width, or height parms are not 0.
Usage
Use this function to control size, position, and state of the main PowerHome application window.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_setframe (0,100,100,1200,1000)
The above example will set the main PowerHome window to normal mode and position it at 100,100 with dimensions of 1200 x 1000.


ph_setmode

ph_setmode PowerHome formula function
Description
Sets the operating mode of PowerHome.
Syntax
ph_setmode ( n )
Argument | Description
n | The mode to set PowerHome to. use 0 for "Normal" mode, 1 thru 3 for "Kiosk" mode. A value of 1 places PowerHome in Kiosk mode with the main window being the Control Center. A value of 2 is Kiosk mode with the main window being the X10 Status screen. A value of 3 is Kiosk mode with the main screen being the Web Center.
Return value
Integer. Returns a 0.
Usage
While in "Kiosk" mode, PowerHome is maximized and can't be closed or minimized. The menu is also restricted to just macros and PowerHome cannot be used for any database maintenance, etc. You will be able to programmatically affect aspects of PowerHome such as using ph_windowstate to minimize PowerHome while in Kiosk mode however. Once placing PowerHome in Kiosk mode, be sure you have a way to get back to "Normal" mode either through a trigger, macro, or similar.


ph_setsysvol

ph_setsysvol PowerHome formula function
Description
Sets the system volume level.
Syntax
ph_setsysvol ( n )
Argument | Description
n | A long representing the system volume level. This value should be between the min and max values as returned by the ph_getsysvolmin and ph_getsysvolmax functions respectively.
Return value
Integer. Returns 0 if successful. Returns a negative value if an error occurs.


ph_show

ph_show PowerHome formula function
Description
Brings the PowerHome application to the foreground.
Syntax
ph_show ( )
Return value
Integer. Returns a 0.


ph_shutdown

ph_shutdown PowerHome formula function
Description
Initiate a programmatic shutdown of PowerHome.
Syntax
ph_shutdown ( type )
Argument | Description
type | Integer. The type of shutdown to perform. See usage below.
Return value
Integer. Returns 1 if the allowphshutdownfunc parameter is not set to YES. Otherwise a 0 is returned.
Usage
Use this function for controlled and uncontrolled programmatic shutdowns of PowerHome. In order for this function to be allowed, you must have set the allowphshutdownfunc to YES under the [system] section of the pwrhome.ini file otherwise the function will be ignored.

Valid values for the type parameter are detailed below. Add individual values together to achieve the desired shutdown operation.
1 | Initiate a controlled user shutdown. This value is ignored if 8, 16, or 256 have been added to the type parameter.
2 | If any unsaved data exists, any save prompts will be skipped.
4 | Bypass the confirm shutdown message.
8 | If PowerHome is running as a service, then the shutdown is performed via a service kill message. If PowerHome is not running as a service then 16 will be OR'ed into the type parameter.
16 | Initiates a quick shutdown. Other type values are ignored.
256 | Perform a hard shutdown bypassing all prompts. PowerHome is immediately terminated as if the process was killed.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_shutdown(7)
The above example will initiate a controlled user shutdown, bypassing any save prompts and the confirm shutdown message.


ph_stacktrace

ph_stacktrace PowerHome formula function
Description
Returns a trace of the PowerHome execution stack
Syntax
ph_stacktrace ( )
Argument Description
Return value
String. Returns a trace of the execution stack. Returns "*ERROR - Runtime Error" if a runtime error occurs. Returns "*ERROR - Stack Trace Failed" if the stack trace fails
Usage
Use this function for debugging purposes to analyze the sequence of function calls and events that have taken place.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_stacktrace() Returns the following string assuming the function was executed from the PowerHome multi-editor and no other routines are currently on the stack:

ph_stacktrace Line: 7
uo_function.f_evalformula Line: 16
w_wshedit.f_executeph Line: 23
m_editor.m_executescript.+clicked Line: 14


ph_system

ph_system PowerHome formula function
Description
Updates and retrieves various system related functions within PowerHome
Syntax
ph_system ( type, parm1, parm2, local )
Argument | Description
type | String. The type of system function you wish to interact with. Current valid value is "ws" for webserver.
parm1 | Long. Parm1 to be passed for the specific function.
parm2 | String. Parm2 to be passed for the specific function
local | Integer. The local variable that you want extended data to be returned in (1 thru 10). Use a value of 0 to discard this data.
Return value
Double. Returns either a value requested for the system parameter or a success/error indicator. Returns -3 if the type parameter is "ws" and the other parameters are invalid. Returns -999 if the type parameter is invalid.
Usage
Use this function to access various system related parameters. See the table below for valid usage parameters:
type | parm1 | parm2 | local | Return value | Notes
ws | 0 | enable | 0 | 0 if successful -1 if the webserver is already enabled -2 if an error occurs | Use to enable the webserver
ws | 0 | disable | 0 | 0 if successful -1 if the webserver is already disabled | Use to disable the webserver
ws | 0 | status | 0 | 0 if the webserver is disabled 1 if the webserver is enabled | Check the current status of the webserver
ws | 0 to only read count 1 to read and reset count | getbadlogincnt | 0 | Returns the total count of bad login attempts -1 if the webserver is not active | Get and optionally reset the count of bad login attempts
ws | 0 to only read count 1 to read and reset count | getblacklistcnt | 0 | Returns the total count of hits from blacklisted IP's -1 if the webserver is not active | Get and optionally reset the count of hits from blacklisted IP's
ws | 0 to only read count 1 to read and reset count | gettrustedcnt | 0 | Returns the total count of hits from trusted IP's -1 if the webserver is not active | Get and optionally reset the count of hits from trusted IP's
ws | 0 to only read count 1 to read and reset count | getguestcnt | 0 | Returns the total count of hits using the guest account -1 if the webserver is not active | Get and optionally reset the count of hits from the guest account
ws | 0 to only read count 1 to read and reset count | getmastercnt | 0 | Returns the total count of hits using the master account -1 if the webserver is not active | Get and optionally reset the count of hits from the master account
ws | 0 to only read count 1 to read and reset count | getunauthcnt | 0 | Returns the total count of unauthorized hits -1 if the webserver is not active | Get and optionally reset the count of unauthorized hits
ws | 0 to only read count 1 to read and reset count | gethitcnt | 0 | Returns the total hit count of all access types -1 if the webserver is not active | Get and optionally reset the total count of hits
ws | 0 to only read count 1 to read and reset count | gethitovercnt | 0 | Returns the total overflows of the gethitcnt counter. -1 if the webserver is not active | The gethitcnt value overflows and is reset to 0 at 4,200,000,000 and this counter is incremented by 1.
ws | 0 | clearcounts | 0 | 0 if successful -1 if the webserver is not active | Clears all above counts
ws | 0 | getallcounts | 1 thru 10. The number of the LOCAL variable to return the counts in. | 0 if successful -1 if the webserver is not active | Retrieves all the counts into a formatted string and returns it in the specified LOCAL variable.
userdata | 1 thru 5 for table userdata1 thru userdata5 | truncate | 0 | 0 if successful -1 if parm1 is out of range -2 if parm2 is out of range | Truncates the specified userdata (1 - 5) table. Keep in mind a truncate will delete all existing data. Useful resetting the autoincrement count in the userdata2 thru userdata5 tables.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_system("ws",0,"enable",0) - Enable the webserver
ph_system("ws",0,"disable",0) - Disable the webserver
ph_system("ws,1,"getbadlogincnt",0) - Retrieve the bad login attempts count and reset the count to 0.


ph_timedeventsctrl

ph_timedeventsctrl PowerHome formula function
Description
Allows control and status of PowerHome Timed Events.
Syntax
ph_timedeventsctrl ( command, data )
Argument | Description
command | String. The command or query you wish to perform.
data | Integer. Data to be passed for the command.
Return value
Long. Returns data if the command is a query otherwise returns 0.
Usage
Use this command to programmatically control and query PowerHome Timed Events. Use "on" for command to turn timed events on. Use a data value of 1 to execute past due timed events. Use a data value of 0 to not execute past due timed events. Use "off" for command to turn timed events off. Use "status" for command to determine whether timed events are currently on or off. If timed events are on, 1 will be returned. If timed events are off, 0 will be returned. Use "pdec" for command (Past Due Event Count) to return how many timed events are past due.
Examples
The following examples demonstrate typical syntax/usage for this function.
• ph_timedeventsctrl ( "on", 1 )
• ph_timedeventsctrl ( "off", 0 )


ph_tracemsg

ph_tracemsg PowerHome formula function
Description
Allows the user to Insert a reference number and message into a currently active trace file
Syntax
ph_tracemsg ( ai_type, al_number, as_message )
Argument | Description
ai_type | Integer. The type of trace message to insert. A value of 1 inserts a traceerror message. Any other value inserts a traceuser message
al_number | Long. A reference number you would like to insert in the trace file
as_message | String. A string message you would like to insert in the trace file
Return value
Integer. Returns 0
Usage
Use this function to create user inserted messages within an active trace file. The tracing and profiling functionality within PowerHome consists of three functions. The ph_traceon( ) function allows you to define and start a trace session. The ph_traceoff( ) function allows you to terminate a trace session. The ph_tracemsg( ) function allows the user to insert a user defined message into the trace file.

Tracing is not something a user would typically do on his own. The resulting trace file is not human readable and must be decoded by the developer using the PowerBuilder development environment in which PowerHome was written in. Tracing will usually be initiated at the developers request to help a user track down problems or issues they may be having

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_tracemsg(0,999,"Start of Macro ID: TRIGGERON")


ph_traceoff

ph_traceoff PowerHome formula function
Description
Terminates a currently active tracing session previously initiated with the ph_traceon( ) function
Syntax
ph_traceoff ( )
Argument Description
Return value
Integer. Returns 0 if successful. Returns 1 if function fails
Usage
Use this function to terminate an active trace session that was previously initiated with the ph_traceon( ) function. The tracing and profiling functionality within PowerHome consists of three functions. The ph_traceon( ) function allows you to define and start a trace session. The ph_traceoff( ) function allows you to terminate a trace session. The ph_tracemsg( ) function allows the user to insert a user defined message into the trace file.

Tracing is not something a user would typically do on his own. The resulting trace file is not human readable and must be decoded by the developer using the PowerBuilder development environment in which PowerHome was written in. Tracing will usually be initiated at the developers request to help a user track down problems or issues they may be having

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_traceoff()


ph_traceon

ph_traceon PowerHome formula function
Description
Initiates a tracing session within PowerHome
Syntax
ph_traceon ( )
ph_traceon ( as_filename, as_label, ai_clocktype, ai_options )
Argument | Description
as_filename | String (Optional). The full path and filename to save the trace results to. If set to an empty string "", PowerHome will default create the trace file in the current directory (typically c:\powerhome) with a filename of "phtrace_yyyymmddhhmmss.pbp" where yyyymmddhhmmss is the current date and time
as_label | String (Optional). An optional user defined label to be stored at the top of the trace file. If set to empty string "", PowerHome will default use a label of "Start Trace yyyymmddhhmmss" where yyyymmddhhmmss is the current date and time
ai_clocktype | Integer (Optional). The clock type to use during the trace. Valid values are 0 for none, 1 for clock, 2 for process, and 3 for thread. Using values of 1, 2, or 3 will cause clock and timing information to also be written to the trace file. Storing clock info can be expensive in terms of efficiency and may not always be necessary to solve certain problems
ai_options | Integer (Optional). The options to use for the tracing session. Values are added together to achieve the desired mode of operation with each value specifying a particular operation type to store in the trace file. Valid values are 1 for Object Create/Destroy, 2 for Routine, 4 for Line, 8 for User, 16 for SQL, 32 for Error, and 64 for Garbage Collection
Return value
Integer. Returns 0 if the trace session is successfully initiated. Returns 1 if the trace file cannot be created/opened. Returns 2 if the trace fails to initialize
Usage
Use this function to initiate a tracing session for PowerHome. The tracing and profiling functionality within PowerHome consists of three functions. The ph_traceon( ) function allows you to define and start a trace session. The ph_traceoff( ) function allows you to terminate a trace session. The ph_tracemsg( ) function allows the user to insert a user defined message into the trace file.

If the overload for this function without parameters is used. It will use the default value for as_filename and as_label. The clocktype will be 1 and the options will be 10 (Routine and User)

Tracing is not something a user would typically do on his own. The resulting trace file is not human readable and must be decoded by the developer using the PowerBuilder development environment in which PowerHome was written in. Tracing will usually be initiated at the developers request to help a user track down problems or issues they may be having

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_traceon("","",0,46) - Returns 0 if successful. This example uses the default values for the filename and label and specifies no timing values to be saved. The trace session will log all routines that are executed and all lines within a routine. It will also log User messages (ph_tracemsg) and errors that occur


ph_trimeventlog

ph_trimeventlog PowerHome formula function
Description
Trims the eventlog to the specified number of days.
Syntax
ph_trimeventlog ( n )
Argument | Description
n | A long representing the number of days of data to keep.
Return value
Integer. Returns a 0 if successful and a 1 if an error occurs. The number of days to keep is dependent upon the current date. If a value of 1 is passed and the current date is July 5, 2002 and the time is 00:15, then the event log will only contain 1 days worth of data (the current day) or actually only the first 15 minutes of July 5, 2002. A value of 2 would contain any data on July 5, 2002 and all data on July 4, 2002.


ph_usererrmsg

ph_usererrmsg PowerHome formula function
Description
Inserts a user defined/generated error message into the PowerHome eventlog
Syntax
ph_usererrmsg ( as_message )
Argument | Description
as_message | String. The error message to be inserted into the eventlog
Return value
Integer. Returns 0
Usage
Use this function insert your own error messages into the PowerHome eventlog. The event number will be a value of 45. Similar to the ph_usermessage function in that a user generated message is added to the eventlog but this one would be for errors vs the informational messages typically generated using ph_usermessage
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_usererrmsg("Macro ID: GETTEMPERATURE returned an invalid value")


ph_usermessage

ph_usermessage PowerHome formula function
Description
Adds a user message to the eventlog.
Syntax
ph_usermessage ( s )
Argument | Description
s | A string representing the message you would like to have added to the eventlog.
Return value
Integer. Returns a 0. The type of message added to the eventlog is a user message and is identified by an eventlog type of 28.


ph_varsub

ph_varsub PowerHome formula function
Description
Use this function to enable or disable variable substitution.
Syntax
ph_varsub ( value )
Argument | Description
value | Integer. Use 0 to turn off variable substitution. Use any other value to turn variable substitution on.
Return value
Integer. Returns 0.
Usage
Variable substitution is typically performed on all formulas before they are executed. Using variable notation such as [LOCAL1] and {TEMP} within your formula and variable substitution enabled will cause PowerHome to search the formula and replace the [LOCAL1] notation with the actual value contained in LOCAL1 and {TEMP} will be replaced with the actual value contained with the TEMP global variable. Disabling variable substitution will cause this variable notation to NOT be substituted and will instead be interpreted literally.

Disabling variable substitution will have the benefit of making PowerHome a little more efficient and faster. Without having to do a search and replace on every formula prior to execution, you will recover precious CPU cycles. If you do disable variable substitution, you can use the ph_getvar_X and ph_getglobal_X functions to utilize global and system variables within your formulas.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_varsub(1)
The above example will enable variable substitution.


ph_windowstate

ph_windowstate PowerHome formula function
Description
Sets the state of the PowerHome frame window.
Syntax
ph_windowstate ( n )
Argument | Description
n | An integer representing the state the PowerHome frame should be set to. A value of 0 makes the frame normal, a value of 1 makes the frame minimized, and a value of 2 makes the frame maximized.
Return value
Integer. Returns a 0.
Usage
If in Kiosk mode (ph_setmode), ph_windowstate(0) will return a 1 and NOT set the window to normal. The only valid values for Kiosk mode are 1 and 2.


ph_x10refreshstat

ph_x10refreshstat PowerHome formula function
Description
Queries the PowerHome database and refreshes the Device status screen.
Syntax
ph_x10refreshstat ( )
Return value
Integer. Returns a 0.
Usage
Identical to the ph_devicerefreshstat function.


ph_x10setstat

ph_x10setstat PowerHome formula function
Description
Directly updates the PowerHome stored X10 status tables.
Syntax
ph_x10setstat ( n, s, n, d, d )
Argument | Description
n | The X10 command you wish to use as the update command. Valid values are the standard X10 commands 0 thru 15.
s | The housecode of the unit you wish to update. Valid values are 'A' thru 'P' for standard X10 modules and 'Q' thru 'Z' for virtual X10 modules.
n | The unitcode of the unit you wish to update. Valid values are 1 thru 16 for standard X10 modules and 1 - 99 for virtual X10 modules. Use a value of 0 if the specific command does not require a unitcode such as command 0 (All units off) and command 1 (All lights on).
d | The percent change in level for commands 4 (dim) and 5 (brighten). Valid values are 0 thru 100. Also the command byte in decimal for command 7 (extended code). Valid values would be 0 thru 255 however only values 48 thru 58 have any effect in PowerHome. Also the preset dim value for command 10 (preset dim 1) and command 11 (preset dim 2). Valid values with these commands would be 1 thru 16. Use a 0 if this value is not needed for the particular command you are using.
d | The data byte in decimal for command 7 (extended code). Valid values are 0 thru 255 however only certain values will have an effect in PowerHome. Please refer to the X10 document for extended commands for an explanation of the various command and data bytes available for extended commands.
Return value
Integer. Returns a 0. It is important to note that the ph_x10setstat function only simulates the sending of commands using the specified parameters. The actual X10 tables will only be updated based upon the defined X10 modules and the X10 module types. If you use ph_x10setstat to simulate a extended command being sent to a module whose type does not support extended commands, then no change will appear in the X10 status tables. Also, this command does not cause any triggers to fire.


ph_chggrammar

ph_chggrammar PowerHome formula function
Description
Changes the current grammar of the voice recognition engine.
Syntax
ph_chggrammar ( string )
Argument | Description
string | The grammar you would like to be the current grammar
Return value
Integer. Returns 0 if the grammar was changed successfully. Returns 1 if an error occurred while retrieving the grammar from the database. Returns 2 if no records exist in the grammar detail.


ph_chgspeaker

ph_chgspeaker PowerHome formula function
Description
Changes the current speaker for the voice recognition engine.
Syntax
ph_chgspeaker ( string )
Argument | Description
string | The name of the speaker you would like to be current
Return value
Integer. Returns 0.


ph_tts

ph_tts PowerHome formula function
Description
Pass a phrase to the Text to Speech engine.
Syntax
ph_tts ( s )
Argument | Description
s | A string that you would like to have spoken via the TTS engine.
Return value
Integer. Returns a 0. It is important to note that TTS is asynchronous and the function returns as soon as the phrase is passed to the TTS engine. The TTS engine will speak the phrase when it has a chance. This command is equivalent to the Send Keys command {tts+phrase}.


ph_ttsctrl

ph_ttsctrl PowerHome formula function
Description
Allows control over both the normal TTS engine and Alert TTS engine.
Syntax
ph_ttsctrl ( cmd, control, data )
Argument | Description
cmd | Integer. The particular command you wish to issue to an engine. Use 0 to speak the data parameter asynchronously. Use 1 to speak the data parameter synchronously with no timeout. Use 2 to set the voice TTS voice to the value in the data parameter. Use 3 to pause the TTS engine. Use 4 to resume the TTS engine. Use 5 to wait until the TTS engine is done speaking with the timeout specified in the data parameter. Use 6 to get the current status of the TTS engine.
control | Integer. The engine you wish to control. Use 0 for the default TTS engine. Any other value for the Alert TTS engine.
data | String. Optional data to be passed depending upon the command type. Commands 0 and 2 will speak the text in the data parameter. Command 2 will set the TTS engine to the voice contained in the data parameter. Commands 3, 4, and 6 should have this value set as the empty string (""). Command 5 will convert the data parameter to a number and use that as the timeout value.
Return value
Integer. Returns a 0 on commands 0, 1, 2, 3, 4, and 5. Returns the status of the TTS engine on command 6. With command 6, a return of 0 means the TTS engine is not currently speaking. A value of 1 means that the TTS engine is currently speaking or is paused in speaking.
Usage
The Alert TTS engine allows you override the default TTS engine. If the default TTS engine is in the middle of speaking, you can issue an Alert TTS command and the default engine will be paused, the Alert TTS will be spoken and when done, will resume speaking where it left off in the default TTS engine. The default and alert TTS engines may have different voices. In order to use the Alert TTS engine, you must have your TTS engine in the Setup section of PowerHome set to "SAPI 5/w Alert".


ph_ttsgetstatus

ph_ttsgetstatus PowerHome formula function
Description
Returns the speaking status of the default TTS engine.
Syntax
ph_ttsgetstatus ( )
Return value
Integer. Returns the speaking status of the default TTS engine. A value of 0 means that the default TTS engine is not speaking. A value of 1 means that the default TTS engine is either speaking or paused in speaking.


ph_ttspause

ph_ttspause PowerHome formula function
Description
Pauses the default TTS engine.
Syntax
ph_ttspause ( )
Return value
Integer. Returns a 0.


ph_ttsresume

ph_ttsresume PowerHome formula function
Description
Resumes the default TTS engine.
Syntax
ph_ttsresume ( )
Return value
Integer. Returns a 0.


ph_ttssetvoice

ph_ttssetvoice PowerHome formula function
Description
Sets the voice to be used by the default TTS engine.
Syntax
ph_ttssetvoice ( voice )
Argument | Description
voice | String. The text representation of the TTS voice.
Return value
Integer. Returns a 0.


ph_ttssync

ph_ttssync PowerHome formula function
Description
Speaks the supplied text synchronously (execution of PowerHome is paused until the speaking is complete) using the default TTS engine.
Syntax
ph_ttssync ( phrase )
Argument | Description
phrase | String. The phrase to be spoken.
Return value
Integer. Returns a 0.


ph_ttswait

ph_ttswait PowerHome formula function
Description
Pauses the specified number of milliseconds or until the default TTS engine is done speaking.
Syntax
ph_ttswait ( ms )
Argument | Description
ms | Long. The number of milliseconds in which to wait. Use - 1 to wait indefinately until speaking is done. If the speaking is done before the timeout value, the function will return.
Return value
Integer. Returns 0 if the function returns because speaking was done. Returns 1 if the function returns because of a timeout.
Usage
Use this function when speaking TTS asynchronously and you wish to pause PowerHome execution.


ph_vrdisable

ph_vrdisable PowerHome formula function
Description
Disables the voice recognition engine.
Syntax
ph_vrdisable ( )
Return value
Integer. Returns a 0. The VR engine can be re-enabled by calling either the ph_chggrammar or ph_chgspeaker function. This function is equivalent to the Send Keys command {vrdisable}.


isnull

isnull PowerHome formula function
Description
Reports whether the value of a column or expression is NULL.
Syntax
isnull ( any )
Argument | Description
any | A column or expression that you want to test to determine whether its value is NULL
Return value
Boolean. Returns TRUE if any is NULL and FALSE if it is not.


ph_getwebauth

ph_getwebauth PowerHome formula function
Description
Returns the authorization level within a webpage.
Syntax
ph_getwebauth ( )
Return value
Integer. Returns a 0 if the webpage was accessed without a userid or password. Returns a 1 if the guest account was used. Returns a 2 if the master account was used or a trusted IP.


ph_getwebbase64auth

ph_getwebbase64auth PowerHome formula function
Description
Returns the base64 encoding of a userid / password used to access a webpage.
Syntax
ph_getwebbase64auth ( )
Return value
String. Returns the actual base64 representation of the userid / password that was used to access the webpage. Use this function when you are validating userid / password combinations other than the master and guest accounts.


ph_isnull

ph_isnull PowerHome formula function
Description
Checks to see if a supplied string parameter is NULL or empty and returns an alternate value instead
Syntax
ph_isnull ( as_value, as_return, ai_flags )
Argument | Description
as_value | String. The string value you wish to test for NULL or empty
as_return | String. The value to be returned if the test on as_value (controlled by the ai_flags parameter) comes back NULL or empty
ai_flags | Integer. A flags parameter that indicates which tests are to be performed. See Usage below
Return value
String. Returns as_value if as_value passes the tests indicated by the ai_flags parameter. If as_value fails the tests, then as_return will be returned instead
Usage
Use this function to check for NULL, empty (blank), or strings containing nothing but whitespace and return an alternate value instead.

While NULL values will not often be found in normal PowerHome usage, it is possible that a NULL value will surface. Any type of variable can be NULL but this function only checks for String values. When a NULL string is concatenated with another string, the result will ALWAYS be NULL. A numeric value that is NULL added to another numeric value will be NULL. Whenever a NULL is part of an equation, the result will be NULL. This function will allow you to check and substitute an alternate value.

The ai_flags parameter controls which type of checking to use. Add together the values below for each check you would like performed:

  • 1 - Check for NULL values
  • 2 - Check for empty string values
  • 4 - Check for string values containing ONLY whitespace (you MUST include value 2 in order for this option to take effect)

    If you supply an ai_flags parameter of 0, no checks will be performed. If you would like to perform all 3 checks, use an ai_flags value of 7

    If you need to check for NULL values for datatypes other than Strings, see the isnull( ) function

    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_isnull(ph_getvar_s(1,1),"Blank",7) - Tests the LOCAL1 system variable for either NULL, empty, or whitespace only. Returns the value for LOCAL1 if LOCAL1 is not NULL, empty, or whitespace otherwise returns the string "Blank"


ph_wcclose

ph_wcclose PowerHome formula function
Description
Closes the Web Center window if it is open.
Syntax
ph_wcclose ( )
Return value
Integer. Returns a 0.


ph_wcgethome

ph_wcgethome PowerHome formula function
Description
Returns the current home page for the Web Center window.
Syntax
ph_wcgethome ( )
Return value
String. Returns the URL of the Web Center home page.


ph_wcgethtml

ph_wcgethtml PowerHome formula function
Description
Returns the raw HTML of the currently displayed Web Center page.
Syntax
ph_wcgethtml ( )
Return value
String. Returns the URL of the currently displayed Web Center page if it is open. Returns an empty string if the Web Center is not open.


ph_wcgoback

ph_wcgoback PowerHome formula function
Description
Forces the Web Center to go back a page in its history list
Syntax
ph_wcgoback ( )
Return value
Integer. Returns a 0 if successful. Returns a 1 if there is no history to go back. Returns a 2 if the Web Center is not open.


ph_wcgoforward

ph_wcgoforward PowerHome formula function
Description
Forces the Web Center to go forward a page in its history list
Syntax
ph_wcgoforward ( )
Return value
Integer. Returns a 0 if successful. Returns a 1 if there are no pages to go forward to. Returns a 2 if the Web Center is not open.


ph_wcgohome

ph_wcgohome PowerHome formula function
Description
Forces the Web Center to open its home page
Syntax
ph_wcgohome ( )
Return value
Integer. Returns a 0 if successful. Returns a 2 if the Web Center is not open.


ph_wcgourl

ph_wcgourl PowerHome formula function
Description
Forces the Web Center to open the specified URL
Syntax
ph_wcgourl ( URL )
Argument | Description
URL | A string representing the URL to go to
Return value
Integer. Returns a 0 if successful. Returns a 2 if the Web Center is not open.


ph_wcisbusy

ph_wcisbusy PowerHome formula function
Description
Returns whether the Web Center window is busy or not.
Syntax
ph_wcisbusy ( )
Return value
Integer. Returns a 1 if the Web Center is currently busy. Returns a 0 if the Web Center is not busy. Returns a 2 if the Web Center window is not currently open.
Usage
When controlling the Web Center in realtime, use this function within a loop in conjunction with the Macro "Wait" command to delay processing until the Web Center is no longer busy.


ph_wcopen

ph_wcopen PowerHome formula function
Description
Opens the Web Center window and optionally navigates to a specified URL.
Syntax
ph_wcopen ( type, URL )
Argument | Description
type | An integer representing the type of Web Center window to open. A value of 0 will open the Web Center as a window. A value of 1 will open the Web Center as a background. If PowerHome is currently in Kiosk mode, the Web Center will open as a background regardless of this value.
URL | A string representing the URL to navigate to when the Web Center is open. Pass an empty string if you wish the Web Center to just open its home page.
Return value
Integer. Returns a 0.
Usage
If the Web Center is already open, this function will just cause the Web Center to navigate to the specified URL if it is not blank.


ph_wcrefresh

ph_wcrefresh PowerHome formula function
Description
Refreshes the current page in the Web Center
Syntax
ph_wcrefresh ( )
Return value
Integer. Returns a 0 if successful. Returns a 2 if the Web Center is not open


ph_wcsethome

ph_wcsethome PowerHome formula function
Description
Sets the home page for the Web Center.
Syntax
ph_wcsethome ( URL )
Argument | Description
URL | The URL of the new home page.
Return value
Integer. Returns a 0. The Web Center does not have to be open. This function does not force the Web Center to navigate to the new home page.


ph_wcsethtml

ph_wcsethtml PowerHome formula function
Description
Causes the Web Center to render the specified HTML as a web page within its window.
Syntax
ph_wcsethtml ( html )
Argument | Description
html | A string representing a valid HTML page to be rendered by the Web Center
Return value
Integer. Returns a 0 if successful. Returns a 2 if the Web Center is not open.
Usage
In order for this function to operate, the internal PowerHome webserver must be enabled. The HTML is rendered by using the /ph-cgi/directhtml webserver function.


ph_wcshow

ph_wcshow PowerHome formula function
Description
Causes the Web Center to either hide or display the open URL edit control.
Syntax
ph_wcshow ( type )
Argument | Description
type | A value of 0 will cause the URL edit control to be hidden. A value of 1 makes the URL edit visible.
Return value
Integer. Returns a 0 if successful. Returns a 2 if the Web Center is not open.


ph_wcstop

ph_wcstop PowerHome formula function
Description
Causes the Web Center to halt the task currently being processed.
Syntax
ph_wcstop ( )
Return value
Integer. Returns a 0 if successful. Returns a 2 if the Web Center is not open.


ph_getipfromhostname

ph_getipfromhostname PowerHome formula function
Description
Returns the IP address associated with a hostname.
Syntax
ph_getipfromhostname ( host )
Argument | Description
host | String. The hostname for which you want to obtain the IP.
Return value
String. Returns a standard IP address. Returns a negative number in string format if an error occurs. Returns "- 1" if a system error occurs. Returns "- 2" if initialization fails. Returns "- 3" if the lookup command fails.


ph_getitcurl

ph_getitcurl PowerHome formula function
Description
Retrieves the HTML from the specified URL using a Microsoft ITC (Internet Transfer Control)
Syntax
ph_getitcurl ( s, n )
Argument | Description
s | The URL you wish to retrieve the HTML for.
n | Specifies the timeout in seconds for the control to return the HTML. Specify a 0 for infinity.
Return value
String. Returns the HTML of the specified URL.
Usage
This function is similar to the ph_geturl and ph_getwburl in that the HTML for a specified URL is returned. This particular function uses the Microsoft ITC to accomplish this task.


ph_geturl

ph_geturl PowerHome formula function
Description
Gets the resulting HTML code from a URL.
Syntax
ph_geturl ( url )
Argument | Description
url | String identifying the URL you wish to retrieve.
Return value
String. The HTML text from the URL. You can include the http:// but it is not necessary. You may also embed any passed parameters to be used in a GET request. This function will use the proxy server defined under Setup / Preferences if you have the appropriate check made in the Setup / Scripts section.
Usage
Use this function to retrieve and save HTML, text, graphic, or binary data from a URL to a file.
Examples
The following examples demonstrate typical syntax/ usage for this function.
• ph_geturl( "mobile.wunderground.com/cgi-bin/findweather/getForecast?brand=mobile&query=48118")
• ph_geturl( "www.adp.com/status&myhomenum=5551212" )

NOTE: This function makes the access call using a Microsoft Internet Explorer activeX control. The user agent that this control and function makes will depend upon your OS and version of IE installed. Depending on your system user agent parameters, the geturl function may not get the source code exactly matching the page, as it is only exposed the interface that passes the URL and can only retrieve what it says is the returned data.

After fetching a web page, if you encounter unexplained issues trying to do string matches, that seem to fail when they shouldn't, consider using the ph_writefile() function to grab the page's HTML code for detailed examination. You may be surprised to find that there can be some significant differences from what you expect, such as capitalization changes or dropped quotation (") marks.

You can capture a web page to a file for more detailed analysis using something like the following example, where "save.txt" is a file to save to, and the getvar function extracts the contents of LOCAL1, which contains the data fetched by the the guturl function.

ph_writefile("C:\save.txt",1,ph_getvar_s(1,1)) function


ph_geturl1

ph_geturl1 PowerHome formula function
Description
Gets the resulting HTML code from the specified URL.
Syntax
ph_geturl1 ( as_url, ai_type, al_timeout )
ph_geturl1 ( as_url, as_headers, ai_type, al_timeout )
Argument | Description
as_url | String. The URL whose HTML you wish to retrieve
as_headers | String (Optional). Additional HTTP headers you would like to be sent as part of the request. Specify headers in the same format that would be used for structuring a valid HTTP request. Separate multiple headers with either a carriage return / linefeed pair or a linefeed (use the same separator for ALL the headers). An example header may look like: "Accept-Type: text/html~r~nPragma: no-cache". If this parameter is omitted, an empty string "" will be used
ai_type | Integer. A number representing the method of HTML retrieval from the URL. See usage below for an explanation of the valid types
al_timeout | Long. The max length of time in either seconds or milliseconds (dependent upon the ai_type value) to wait for the HTML return before the function times out
Return value
String. The raw HTML returned from the requested URL. Various errors may be encountered depending upon the method used to retrieve the HTML specified by the ai_type parameter. If an error occurs, the return value will start with "*ERROR* - " followed by a description of the error
Usage
This function is an upgraded and expanded version of the original ph_geturl function.

The following table details the valid values for the ai_type parameter:
0 | A type of 0 will cause the HTML to be retrieved via a raw socket (this is the same as the ph_geturl function). The HTTP request is constructed internally and then sent via a raw socket. The al_timeout parameter is in seconds
1 | A type of 1 will retrieve the HTML using a Catalyst HTTP control. The al_timeout parameter is in seconds
2 | A type of 2 will also retrieve the HTML using a Catalyst HTTP control but does so using slightly different methods than type 1 in case one or the other has compatibility problems. The al_timeout parameter is in seconds
3 | A type of 3 will also retrieve the HTML using a Catalyst HTTP control but does so using a different method than type 1 or type 2. The al_timeout parameter is in seconds
4 | Retrieves the HTML using an PowerBuilder internal HTTP control. This method does not support additional HTTP headers and any specified headers will be ignored. The al_timeout parameter is in seconds
5 | Retrieves the HTML using an "msxml2.xmlhttp" control. The al_timeout parameter is in milliseconds
6 | Retrieves the HTML using an "msxml2.serverxmlhttp" control. The al_timeout parameter is in milliseconds
7 | Retrieves the HTML using a "winhttp.winhttprequest" control. The al_timeout parameter is in milliseconds
8 | Retrieves the HTML using a C# WebRequest object. The al_timeout parameter is in milliseconds
9 | Retrieves the HTML using a C# HttpWebRequest object. The al_timeout parameter is in milliseconds
10 | Retrieves the HTML using a C# WebClient object with the DownloadString function. The al_timeout parameter is not relevant since this method does not allow specifying a timeout
11 | Retrieves the HTML using a C# WebClient object with the OpenRead function. The al_timeout parameter is not relevant since this method does not allow specifying a timeout
12 | Retrieves the HTML using a C# WebClient object with the DownloadString function. The C# WebClient object has been extended such that it supports timeout values. The al_timeout parameter is in milliseconds
13 | Retrieves the HTML using a C# WebClient object with the OpenRead function. The C# WebClient object has been extended such that it supports timeout values. The al_timeout parameter is in milliseconds
Any other value | Any other value will result in an empty string "" being returned
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_geturl1("https://weather.com/weather/today/l/28.69,-81.53?par=google&temp=f",1,5)
The above example will retrieve the raw HTML for the weather.com website using an HTTP Catalyst control. The function will timeout in 5 seconds if the result hasnt been returned by then.


ph_geturlviaproxy

ph_geturlviaproxy PowerHome formula function
Description
Gets the resulting HTML code from a URL using the specified proxy server values.
Syntax
ph_geturlviaproxy ( s, s, n, s )
Argument | Description
s | A string identifying the URL you wish to retrieve.
s | A string identifying the proxy server you wish to use.
n | An integer identifying the port of the proxy server.
s | A string identifying the userid and password for the proxy server. Separate the userid from the password using a colon character. Example: userid:password.
Return value
String. The HTML text from the URL. You can include the http:// but it is not necessary. You may also embed any passed parameters to be used in a GET request.


ph_geturlviaproxy1

ph_geturlviaproxy1 PowerHome formula function
Description
Gets the resulting HTML code from a URL using the specified proxy server values.
Syntax
ph_geturlviaproxy ( as_url, as_proxy, al_proxyport, as_authorization, ai_type, ai_timeout)
ph_geturlviaproxy ( as_url, as_headers, as_proxy, al_proxyport, as_authorization, ai_type, ai_timeout)
Argument | Description
as_url | String. The URL whose HTML you wish to retrieve.
as_headers | String (Optional). Additional HTTP headers you would like to be sent as part of the request. Specify headers in the same format that would be used for structuring a valid HTTP request. Separate multiple headers with either a carriage return / linefeed pair or a linefeed (use the same separator for ALL the headers). An example header may look like: "Accept-Type: text/html~r~nPragma: no-cache". If this parameter is omitted, an empty string "" will be used
as_proxy | String. The proxy server the request will made through.
al_proxyport | Long. The proxy server port
as_authorization | String. The userid and password for the proxy server. Separate the userid from the password using a colon character. Example: userid:password.
ai_type | Integer. A number representing the method of HTML retrieval from the URL. See usage below for an explanation of the valid types.
ai_timeout | Integer. The max length of time in seconds to wait for the HTML before the function times out.
Return value
String. The raw HTML returned from the requested URL.
Usage
This function is an upgraded and expanded version of the original ph_geturlviaproxy function.

The following table details the valid values for the type parameter:
0 | A type of 0 will cause the HTML to be retrieved via a raw socket (this is the same as the ph_geturlviaproxy function). The HTTP request is constructed internally and then sent via a raw socket.
1 | A type of 1 will retrieve the HTML using a Catalyst HTTP control.
2 | A type of 2 will also retrieve the HTML using a Catalyst HTTP control but does so using slightly different methods than type 1 in case one or the other has compatibility problems.
Any other value | Any other value will cause the function to retrieve HTML using a Catalyst HTTP control using yet another method different from type 1 or type 2. Each of the types have various levels of compatibility and each type should be attempted to retrieve the most satisfactory results for a particular website.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_geturlviaproxy1("https://weather.com/weather/today/l/28.69,-81.53?par=google&temp=f","192.168.0.150",80,"userid:password",1,5)
The above example will retrieve the raw HTML for the weather.com website using an HTTP Catalyst control. The function will timeout in 5 seconds if the result hasnt been returned by then.


ph_getwburl

ph_getwburl PowerHome formula function
Description
Gets the resulting HTML code from a URL.
Syntax
ph_getwburl ( s, i )
Argument | Description
s | A string identifying the URL you wish to retrieve.
i | An integer representing the timeout for this function in seconds.
Return value
String. The HTML text from the URL. This function will use the proxy server defined within Internet Explorer if one is defined.
Usage
This function uses the Microsoft Web Browser control rather than a raw socket such as that used in the ph_geturl function. This means that any cookies or other constructs used by Internet Explorer will be available to this function.

In most cases, the ph_geturl function is preferable as it will be faster. However, some websites require the use of cookies and will not return the expected HTML. In these situations, use this function.


ph_getwebcookie

ph_getwebcookie PowerHome formula function
Description
Returns the value associated with the specified cookie.
Syntax
ph_getwebcookie ( name )
Argument | Description
name | String. The cookie whose value you wish returned.
Return value
String. Returns the value for the cookie. This function only has meaning when executed from within the context of a PSP page.


ph_getwebheader

ph_getwebheader PowerHome formula function
Description
Returns the raw http header that was sent by the browser when accessing a web page.
Syntax
ph_getwebheader ( )
Return value
String. Returns the raw http header that was used to access the web page. Only useful within a formula from within a PSP page. Any other usage will result in an empty string being returned.


ph_getwebheaderparm

ph_getwebheaderparm PowerHome formula function
Description
Returns the value associated with a specific parameter in the http header used to access a web page.
Syntax
ph_getwebheaderparm ( s )
Argument | Description
s | String representing the parameter whose value you wish to have parsed from the http header.
Return value
String. Returns the value associated with the specified parameter from an http header that was used to access the web page. Only useful within a formula from within a PSP page. Any other usage will result in an empty string being returned. Sample parameters are "user-agent", "accept", and "content-type".


ph_getwebmethod

ph_getwebmethod PowerHome formula function
Description
Returns the http method that was used by the browser when accessing a web page.
Syntax
ph_getwebmethod ( )
Return value
String. Returns either "GET" or "POST" depending on the method used to access a web page. Only useful within a formula from within a PSP page. Any other usage will result in an empty string being returned.


ph_getwebparm

ph_getwebparm PowerHome formula function
Description
Returns the value associated with the specified web parm
Syntax
ph_getwebparm ( as_id )
ph_getwebparm ( as_id, as_parms )
Argument | Description
as_id | String. The web parm you wish to receive. When using PSP (PowerHome Server Pages) to serve dynamic content from PowerHome via the web, you can create forms and pass information from a web page back to PowerHome via either an HTML GET or POST command. This data is then stored within PowerHome and accessible within a PSP page via this function
as_parms | String (Optional). A full list of parameters and their values from which you would like to search for as_id and return its value. If this parameter is omitted, it will use the web parameters that are currently within memory for the active webpage that is being processed.
Return value
String. The data associated with the specified web parm.
Usage
Use this function to retrieve a value associated with a specific web parameter. Typically you would call this function from within a PSP page to get the results of a previously submitted form value and structure the new web page output accordingly. In this use case scenario, you would use the syntax that does not include the as_parms parameter. The syntax that includes the as_parms parameter is for more general usage and allows the user to specify the full parameter list from which to retrieve the value instead of using the parameters loaded in memory from within an executing PSP page
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getwebparm("familyroom_lightlevel") - Returns the value associated with the web parameter FAMILYROOM_LIGHTLEVEL assuming that this value is a member of the current web parameters that have been passed to the active webpage


ph_getwebremoteip

ph_getwebremoteip PowerHome formula function
Description
Returns IP address of the remote machine accessing the PowerHome web server.
Syntax
ph_getwebremoteip ( )
Argument Description
Return value
String. Returns the IP address of the remote machine.


ph_getweburl

ph_getweburl PowerHome formula function
Description
Returns the URL that was requested by the browser when accessing a web page.
Syntax
ph_getweburl ( )
Return value
String. Returns the URL that was requested by the browser. Only useful within a formula from within a PSP page. Any other usage will result in an empty string being returned.


ph_htmlescape1

ph_htmlescape1 PowerHome formula function
Description
This function accepts a string and searches for HTML reserved characters and substitutes them as needed.
Syntax
ph_htmlescape1 ( input, flags )
Argument | Description
input | String. The data you'd like to have HTML reserved characters replaced.
flags | Integer. A numeric value specifying which type of HTML characters will be replaced. See usage below for details
Return value
String. Returns the string with the HTML reserved characters replaced.
Usage
The table below details the flags parameter. Add each number together for each type of replacement desired to get the value for the flags parameter.

1 | Less than (<), greater than (>), and double quote (") characters will be replaced with &lt;, &gt;, &quot;
2 | Ampersand (&) characters will be replaced with &amp;
4 | Space characters will be replaced with &nbsp;
8 | Carriage return/line feed pairs will be replaced with <br>
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_htmlescape("Mike & Ike are home.",6)
The above example will replace & and space characters (2 and 4 added together = 6) with HTML equivalents. The return value will be: Mike&nbsp;&amp;&nbsp;Ike&nbsp;are&nbsp;home.


ph_httprequest

ph_httprequest PowerHome formula function
Description
Makes an HTTP request to a server and returns the result. This function is very similar to the ph_geturl1 function but allows more detailed control
Syntax
ph_httprequest ( as_url, as_headers, as_method, as_data, ai_type, al_timeout, ai_ignoresslcert )
Argument | Description
as_url | String. The URL for the HTTP Request
as_headers | String. Optional HTTP headers you would like to supply with the request
as_method | String. The HTTP method for the request. Some valid values are "GET", "POST", "PUT", "DELETE" and "HEAD"
as_data | String. Optional data you would like to pass as part of the HTTP request
ai_type | Integer . Specifies the specific control to use for making the request. Valid values are 0, 1, 2, 3, 5, 6, 7, and 9. See Usage below
al_timeout | Long. The timeout for the request in milliseconds. Unlike the ph_geturl1 function, ALL valid ai_type values will use milliseconds
ai_ignoresslcert | Integer. Specifies whether to ignore SSL certificate errors or not. If 0, then SSL certificate errors are NOT ignored. A value of 1 (or any other value) means SSL certificate errors are ignored. Only supported when the ai_type value is 6, 7, or 9
Return value
String. Returns the resulting HTML or other data returned by the HTTP server
Usage
Use this function instead of the ph_geturl1 or ph_posturl1 functions when you need to ignore SSL certificate errors or need to utilize HTTP methods other than GET or POST.

The as_headers parameter allows you to specify additional HTTP headers that are not included by default such as "Content-Type", "Cache-Control", "Pragma", etc. For any headers you wish to specify, you must have the header followed by a ":" followed by a single space followed by the header value and then terminated with either a carriage return line feed or just a line feed. So if you wish to specify a content-type and content-length header, it would look like this:

"Content-Type: application/x-www-form-urlencoded~r~nContent-Length: 2231~r~n"

The as_data parameter is where you would place the "body" of the HTTP request such as the data to be sent with a "POST" method.

The ai_type parameter specifies the specific internal control/method used to make the HTTP request. Valid values are:

  • 0 - Uses a Catalyst controls raw socket
  • 1 - Uses a Catalyst controls Hypertext Transfer Protocol control
  • 2 - Same as 1
  • 3 - Same as 1
  • 5 - Uses an MSXML2.XMLHTTP control
  • 6 - Uses an MSXML2.SERVERXMLHTTP control
  • 7 - Uses a WINHTTP.WINHTTPREQUEST control
  • 9 - Uses a C# HttpWebRequest object
    • Examples
    The following examples demonstrate typical syntax/usage for this function.
    . ph_httprequest("https://192.168.0.55/api/form1","Content-Type: application/x-www-form-urlencoded~r~n","POST","function= lights&action=on&level=128",9,5000,1)- This example specifies the Content-Type header and is using an HTTP POST method. The data to post is URLEncoded. The request is made using a C# HttpWebRequest object with a timeout of 5 seconds and ignoring SSL certificate errors.


ph_isvalidip

ph_isvalidip PowerHome formula function
Description
Checks that the supplied as_ip string is a valid IPV4 IP address
Syntax
ph_isvalidip ( as_ip )
Argument | Description
as_ip | String. An IPV4 address
Return value
Integer. Returns 0 if as_ip contains a valid IP address. 1 or 2 is returned (depending upon which check fails) if as_ip contains any characters that would not be in an IP address or if as_ip does not meet the format of xxx.xxx.xxx.xxx where "x" is a number 0 thru 9. Returns 3 if any of the IP segments is out of the range of 0 to 255.
Usage
This function ONLY checks that the supplied value in as_ip COULD be a valid IP. It does NOT go out on the network to verify that the IP address is reachable.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_isvalidip("192.168.0.45") - Returns 0
. ph_isvalidip("256.123.123.55") - Returns 3 because the first IP segment is outside of the range of 0 thru 255


ph_itccancel

ph_itccancel PowerHome formula function
Description
Cancels any currently executing operation in the specified Internet Transfer Control.
Syntax
ph_itccancel ( n )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish to cancel operations for.
Return value
Integer. Returns a 0 if successful. If the specified ITC has not been created, then 1 is returned. 2 is returned if the specified ITC is outside of the range of 1 to 10.


ph_itccreate

ph_itccreate PowerHome formula function
Description
Creates an Internet Transfer Control and assigns it to the specified ITC handle.
Syntax
ph_itccreate ( n )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish create.
Return value
Integer. Returns a 0 if successful. If the specified ITC has already been created, then 1 is returned. 2 is returned if the specified ITC is outside of the range of 1 to 10.


ph_itcdestroy

ph_itcdestroy PowerHome formula function
Description
Destroys the Internet Transfer Control in the specified ITC handle.
Syntax
ph_itcdestroy ( n )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish destroy.
Return value
Integer. Returns a 0 if successful. If the specified ITC has not been created, then 1 is returned. 2 is returned if the specified ITC is outside of the range of 1 to 10.


ph_itcexecuteftp

ph_itcexecuteftp PowerHome formula function
Description
Executes an FTP request in the specified Internet Transfer Control.
Syntax
ph_itcexecuteftp ( n, s, s, n )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish to execute an FTP request.
s | A string representing the FTP operation. See Usage below.
s | The ID of a macro to be executed when the operation completes.
n | The request timout in seconds. Use 0 for infinity.
Return value
Integer. Returns a 0 if successful. If the specified ITC has not been created, then 1 is returned. 2 is returned if the specified ITC is outside of the range of 1 to 10. 3 is returned if the ITC is currently busy. 4 is returned if a runtime error occurs.
Usage
This function call is asynchronous. When an FTP request is made, this function returns immediately and the request is processed in the background. When the operation is complete, the specified Macro will then be executed. When the macro is executed, it will have a complete copy of LOCAL and TEMP variables that were assigned when the function was executed. However, the [TEMP1] variable will contain the response code. A value of 10 means that the control has disconnected. A value of 11 means that an error occurred. A value of 12 means that the request completed successfully. If an error occurs (response code 11 in [TEMP1]), then the error code will be in the [TEMP2] variable and the error info will be in the [TEMP3] variable. The FTP operation is contained within a single string with multiple parameters separated by a space. Below is a list of valid parameters:

Operation | Description
CD file1 | Change Directory. Changes to the directory specified in file1.
CDUP | Change to parent directory. Equivalent to "CD.."
CLOSE | Closes the current FTP connection.
DELETE file1 | Deletes the file specified in file1.
DIR file1 | Directory. Searches the directory specified in file1. (Wildcards are permitted but the remote host dictates the syntax.) If no file1 is specified, a full directory of the current working directory is returned. Use ph_itcgetdata or ph_itcsavedata to access the returned data.
GET file1 file2 | Retrieves the remote file specified in file1, and creates a new local file specified in file2.
LS file1 | List. Searches the directory specified in file1. (Wildcards are permitted but the remote host dictates the syntax.) Use ph_itcgetdata or ph_itcsavedata to access the returned data.
MKDIR file1 | Make Directory. Creates a directory as specified in file1. Success is dependent on user privileges on the remote host.
PUT file1 file2 | Copies a local file specified in file1 to the remote host specified in file2.
PWD | Print Working Directory. Returns the current directory name. Use ph_itcgetdata or ph_itcsavedata to access the returned data.
QUIT | Terminates the current user.
RECV file1 file2 | Retrieves the remote file specified in file1, and creates a new local file specified in file2. Equivalent to GET.
RENAME file1 file2 | Renames the remote file named in file1 to the new name specified in file2. Success is dependent on user privileges on the remote host.
RMDIR file1 | Remove Directory. Removes the remote directory specified in file1. Success is dependent on user privileges on the remote host.
SEND file1 file2 | Copies a local file, specified in file1, to the remote host, specified in file2. Equivalent to PUT.
SIZE file1 | Returns the size of the directory specified in file1.


ph_itcexecutehttp

ph_itcexecutehttp PowerHome formula function
Description
Executes an HTTP request in the specified Internet Transfer Control.
Syntax
ph_itcexecutehttp ( n, s, s, s, s, n )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish to execute an HTTP request.
s | A string representing the HTTP operation. See Usage below.
s | A string that specifies the DATA to be used for operations (POST and PUT). Use empty string ("") for GET and HEAD operations.
s | A string representing additional HEADERS to be returned from the server. For most operations, use the empty string ("").
s | The ID of a macro to be executed when the operation completes.
n | The request timout in seconds. Use 0 for infinity.
Return value
Integer. Returns a 0 if successful. If the specified ITC has not been created, then 1 is returned. 2 is returned if the specified ITC is outside of the range of 1 to 10. 3 is returned if the ITC is currently busy. 4 is returned if a runtime error occurs.
Usage
This function call is asynchronous. When an HTTP request is made, this function returns immediately and the request is processed in the background. When the operation is complete, the specified Macro will then be executed. When the macro is executed, it will have a complete copy of LOCAL and TEMP variables that were assigned when the function was executed. However, the [TEMP1] variable will contain the response code. A value of 10 means that the control has disconnected. A value of 11 means that an error occurred. A value of 12 means that the request completed successfully. If an error occurs (response code 11 in [TEMP1]), then the error code will be in the [TEMP2] variable and the error info will be in the [TEMP3] variable. The HTTP operation is contained within a single string. Below is a list of valid parameters:

Operation | Description
GET | Retrieve data from the URL specified.
HEAD | Sends the Request headers.
POST | Posts data to the server. The data is located in the DATA argument. This is an alternate method to GET, for which additional instructions are specified in the DATA argument.
PUT | Put operation. The name of the page to be replaced is located in the DATA argument.


ph_itcgetdata

ph_itcgetdata PowerHome formula function
Description
Returns previously retrieved data in the specified Internet Transfer Control.
Syntax
ph_itcgetdata ( n )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish to return retrieved data from.
Return value
String. Returns the retrieved data as a string if successful. If the specified ITC has not been created, then "*ERROR* - ITC IS NOT VALID" is returned. "*ERROR* - ITC NUMBER OUT OF RANGE" is returned if the specified ITC is outside of the range of 1 to 10. "*ERROR* - ITC IS BUSY" is returned if the ITC is currently busy. "*ERROR* - RUNTIME ERROR" is returned if a runtime error occurs.


ph_itcisbusy

ph_itcisbusy PowerHome formula function
Description
Returns whether the specified Internet Transfer Control is currently busy (ph_itcexecuteftp or ph_itcexecutehttp).
Syntax
ph_itcisbusy ( n )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish to check.
Return value
Integer. Returns 0 if the specified ITC is busy. If the ITC is NOT busy, then 1 is returned. If the specified ITC has not been created, then 3 is returned. 2 is returned if the specified ITC is outside of the range of 1 to 10.


ph_itcisvalid

ph_itcisvalid PowerHome formula function
Description
Returns whether the specified Internet Transfer Control has been created or not.
Syntax
ph_itcisvalid ( n )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish to check.
Return value
Integer. Returns 0 if the specified ITC is has been created. If the ITC has NOT been created, then 1 is returned. 2 is returned if the specified ITC is outside of the range of 1 to 10.


ph_itcsavedata

ph_itcsavedata PowerHome formula function
Description
Saves previously retrieved data in the specified Internet Transfer Control to the specified file.
Syntax
ph_itcsavedata ( n, s, n )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish to save data from.
s | A string representing the file to save to.
n | The writemode to use. A 0 will append data to the file. Any other value will overwrite the file.
Return value
Integer. Returns 0 if successful. If the ITC has NOT been created, then 1 is returned. 2 is returned if the specified ITC is outside of the range of 1 to 10. 3 is returned if the ITC is busy. 4 is returned if a runtime error occurs. 5 is returned if the file cannot be opened.


ph_itcseturl

ph_itcseturl PowerHome formula function
Description
Specifies the URL to be used for subsequent execute operation in the specified Internet Transfer Control.
Syntax
ph_itcseturl ( n, s )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish to save data from.
s | The URL you wish to be used for subsequent operations.
Return value
Integer. Returns 0 if successful. If the ITC has NOT been created, then 1 is returned. 2 is returned if the specified ITC is outside of the range of 1 to 10. 3 is returned if the ITC is busy.


ph_itcsetuserpass

ph_itcsetuserpass PowerHome formula function
Description
Specifies the userid / password to be used for subsequent execute operations in the specified Internet Transfer Control.
Syntax
ph_itcsetuserpass ( n, s, s )
Argument | Description
n | A number from 1 to 10 representing the ITC you wish to save data from.
s | The userid you wish to be used for subsequent operations.
s | The password you wish to be used for subsequent operations.
Return value
Integer. Returns 0 if successful. If the ITC has NOT been created, then 1 is returned. 2 is returned if the specified ITC is outside of the range of 1 to 10. 3 is returned if the ITC is busy.


ph_processemail

ph_processemail PowerHome formula function
Description
Processes and executes any Control Email using the default MAPI client .
Syntax
ph_processemail ( )
Argument Description
Return value
Integer. Returns a 0 if successful. Returns a 1 if an error occurs while logging into the mail system. Returns a 2 if an error occurs while retrieving email. Returns a 3 if an error occurs while reading the envelope. Returns a 4 if an error occurs while reading the message. Returns a 5 if an error occurs while deleting the email.


ph_processemailthread

ph_processemailthread PowerHome Formula function
Description
Processes and executes any Control Email (in a separate helper application) using the default MAPI client.
Syntax
ph_processemailthread ( type, seconds )
Argument | Description
type | An integer representing the method to launch the process email heper application. A value of 0 will launch the helper application for processing and causes the function to return a 0 immediately with no knowledge of whether the processing was successful or not. A value of 1 will launch the helper application but cause the function to wait up to the specified number of seconds and return an error code indicating success or not.
seconds | The maximum number of seconds to wait when processing email with a type of 1.
Return value
Integer. If the processing type is 0, the function will always return 0. If the type is 1, the function will wait up to the number of seconds specified in the seconds parameter. Returns a 0 if successful. Returns a 1 if an error occurs while logging into the mail system. Returns a 2 if an error occurs while retrieving email. Returns a 3 if an error occurs while reading the envelope. Returns a 4 if an error occurs while reading the message. Returns a 5 if an error occurs while deleting the email. Error values of -1 thru -5 are equivalent to their positive counterparts but means that the function timed out while waiting for the MAPI client to respond. This most likely means that the MAPI client helper application is hung waiting for some form of user response.


ph_posturl1

ph_posturl1 PowerHome formula function
Description
Use this function to retrieve HTML from the specified URL using an HTTP POST command (vs the GET command that is used in the ph_geturl functions). This allows you to pass large amounts of data (such as form data) to the specified URL
Syntax
ph_posturl1 ( as_url, as_postdata, ai_type, al_timeout )
ph_posturl1 ( as_url, as_headers, as_postdata, ai_type, al_timeout )
Argument | Description
as_url | String. The URL whose HTML you wish to retrieve
as_headers | String (Optional). Additional HTTP headers you would like to be sent as part of the request. Specify headers in the same format that would be used for structuring a valid HTTP request. Separate multiple headers with either a carriage return / linefeed pair or a linefeed (use the same separator for ALL the headers). An example header may look like: "Accept-Type: text/html~r~nPragma: no-cache". If this parameter is omitted, an empty string "" will be used
as_postdata | String . The data and parameters you would like to "POST" to the specified URL via HTTP. This data is passed in the body of the request. If you have no data to post, use an empty string ""
ai_type | Integer. A number representing the internal method of HTML retrieval from the URL. See usage below for an explanation of the valid types
al_timeout | Long. The max length of time in either seconds or milliseconds (dependent upon the ai_type value) to wait for the HTML return before the function times out
Return value
String. The raw HTML returned from the requested URL. Various errors may be encountered depending upon the internal method used to retrieve the HTML specified by the ai_type parameter. If an error occurs, the return value will start with "*ERROR* - " followed by a description of the error
Usage
Most of the time, the ph_geturl or ph_geturl1 function is all that is needed in order to retrieve raw HTML from a website. This is accomplished via an HTTP GET command. Some websites though, for whatever reason, don't support an HTTP GET and instead require an HTTP POST. This function allows you to retrieve data from these websites. A very good explanation of the differences between POST and GET can be found here: http://www.w3schools.com/tags/ref_httpmethods.asp

The following table details the valid values for the ai_type parameter:
0 | A type of 0 will cause the HTML to be retrieved via a raw socket (this is the same as the ph_posturl function). The HTTP POST request is constructed internally and then sent via a raw socket. The al_timeout parameter is in seconds
1 | A type of 1 will retrieve the HTML using a Catalyst HTTP control. The al_timeout parameter is in seconds
2 | A type of 2 will also retrieve the HTML using a Catalyst HTTP control but does so using slightly different methods than type 1 in case one or the other has compatibility problems. The al_timeout parameter is in seconds
3 | A type of 3 will also retrieve the HTML using a Catalyst HTTP control but does so using a different method than type 1 or type 2. The al_timeout parameter is in seconds
4 | Retrieves the HTML using a PowerBuilder internal HTTP control. Unlike the equivalent internal method in ph_geturl1, this type does support the use of additional headers. The al_timeout parameter is in seconds
5 | Retrieves the HTML using an "msxml2.xmlhttp" control. The al_timeout parameter is in milliseconds
6 | Retrieves the HTML using an "msxml2.serverxmlhttp" control. The al_timeout parameter is in milliseconds
7 | Retrieves the HTML using a "winhttp.winhttprequest" control. The al_timeout parameter is in milliseconds
8 | Retrieves the HTML using a C# WebRequest object. The al_timeout parameter is in milliseconds
9 | Retrieves the HTML using a C# HttpWebRequest object. The al_timeout parameter is in milliseconds
10 | Retrieves the HTML using a C# WebClient object with the DownloadString function. The al_timeout parameter is not relevant since this method does not allow specifying a timeout
11 | Not Supported. Returns an error message
12 | Retrieves the HTML using a C# WebClient object with the DownloadString function. The C# WebClient object has been extended such that it supports timeout values. The al_timeout parameter is in milliseconds
13 | Not Supported. Returns an error message
Any other value | Any other value will result in an empty string "" being returned
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_posturl1("https://mobile.weather.gov/index.php","lat=28.6867&lon=-81.5133&unit=0&lg=english",5,5000)
The above example will retrieve the raw HTML for the mobile.weather.gov website via an "msxml2.xmlhttp" control using an HTTP POST command. The function will timeout in 5 seconds (5000 milliseconds) if the result hasnt been returned by then.


ph_posturlviaproxy1

ph_posturlviaproxy1 PowerHome formula function
Description
Gets the resulting HTML code from a URL (via an HTTP POST operation) using the specified proxy server values
Syntax
ph_posturlviaproxy1 ( as_url, as_postdata, as_proxy, al_proxyport, as_authorization, ai_type, ai_timeout )
ph_posturlviaproxy1 ( as_url, as_headers, as_postdata, as_proxy, al_proxyport, as_authorization, ai_type, ai_timeout )
Argument | Description
as_url | String. The URL whose HTML you wish to retrieve.
as_headers | String (Optional). Additional HTTP headers you would like to be sent as part of the request. Specify headers in the same format that would be used for structuring a valid HTTP request. Separate multiple headers with either a carriage return / linefeed pair or a linefeed (use the same separator for ALL the headers). An example header may look like: "Accept-Type: text/html~r~nPragma: no-cache". If this parameter is omitted, an empty string "" will be used
as_postdata | String. The data to post to the URL
as_proxy | String. The proxy server the request will made through.
al_proxyport | Long. The proxy server port
as_authorization | String. The userid and password for the proxy server. Separate the userid from the password using a colon character. Example: userid:password.
ai_type | Integer. The method in which to post the data. A type value of 0 will post the data using a raw socket control with the data appropriately structured. Any other value will post the data using a Catalyst HTTP control.
ai_timeouot | Integer. The max length of time in seconds to wait for the HTML before the function times out.
Return value
String. The returned raw HTML from the HTTP POST operation.
Usage
Most of the time, the ph_geturlviaproxy or ph_geturlviaproxy1 function is all that is needed in order to retrieve raw HTML from a website through a proxy server.. This is accomplished via an HTTP GET command. Some websites though, for whatever reason, don't support an HTTP GET and instead require an HTTP POST. This function allows you to retrieve data from these websites. A very good explanation of the differences between POST and GET can be found here: http://www.w3schools.com/tags/ref_httpmethods.asp
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_posturlviaproxy1("http://www.weatherunderground.com","Host: power-home.com","192.168.0.150",80,"userid:password",1,5)
The above example will retrieve the raw HTML for the weatherundergound.com website using an HTTP Catalyst control. The function will timeout in 5 seconds if the result hasnt been returned by then.


ph_saveurl1

ph_saveurl1 PowerHome formula function
Description
Retrieves the resulting HTML / data from the specified URL. and saves the results to a file
Syntax
ph_saveurl1 ( as_url, as_file, ai_writemode, ai_type, al_timeout )
ph_saveurl1 ( as_url, as_headers, as_file, ai_writemode, ai_type, al_timeout )
Argument | Description
as_url | String. The URL whose HTML / data you wish to save to a file
as_headers | String (Optional). Additional HTTP headers you would like to be sent as part of the request. Specify headers in the same format that would be used for structuring a valid HTTP request. Separate multiple headers with either a carriage return / linefeed pair or a linefeed (use the same separator for ALL the headers). An example header may look like: "Accept-Type: text/html~r~nPragma: no-cache". If this parameter is omitted, an empty string "" will be used
as_file | String. The full path and filename that you wish to save the results of the URL to
ai_writemode | Integer. Specifies how to save the data to the file. A value of 0 will append the data if the file already exists. Any other value will overwrite the file if it already exists
ai_type | Integer. A number representing the method of HTML retrieval from the URL. See usage below for an explanation of the valid types
al_timeout | Long. The max length of time in either seconds or milliseconds (dependent upon the ai_type value) to wait for the HTML return before the function times out
Return value
String. Returns either the HTTP headers from the URL request or an error message. Various errors may be encountered depending upon the method used to retrieve the HTML specified by the ai_type parameter. If an error occurs, the return value will start with "*ERROR* - " followed by a description of the error
Usage
This function is an upgraded and expanded version of the original ph_saveurl function.

The following table details the valid values for the ai_type parameter:
0 | A type of 0 will cause the HTML to be retrieved via a raw socket (this is the same as the ph_saveurl function). The HTTP request is constructed internally and then sent via a raw socket. The al_timeout parameter is in seconds
1 | A type of 1 will retrieve the HTML using a Catalyst HTTP control. The al_timeout parameter is in seconds
2 | A type of 2 will also retrieve the HTML using a Catalyst HTTP control but does so using slightly different methods than type 1 in case one or the other has compatibility problems. The al_timeout parameter is in seconds
3 | A type of 3 will also retrieve the HTML using a Catalyst HTTP control but does so using a different method than type 1 or type 2. The al_timeout parameter is in seconds
4 | Returns "*ERROR* - Not supported"
5 | Retrieves the HTML using an "msxml2.xmlhttp" control. The al_timeout parameter is in milliseconds
6 | Retrieves the HTML using an "msxml2.serverxmlhttp" control. The al_timeout parameter is in milliseconds
7 | Retrieves the HTML using a "winhttp.winhttprequest" control. The al_timeout parameter is in milliseconds
8 | Retrieves the HTML using a C# WebRequest object. The al_timeout parameter is in milliseconds
9 | Retrieves the HTML using a C# HttpWebRequest object. The al_timeout parameter is in milliseconds
10 | Retrieves the HTML using a C# WebClient object with the DownloadString function. The al_timeout parameter is not relevant since this method does not allow specifying a timeout
11 | Returns "*ERROR* - Not supported"
12 | Retrieves the HTML using a C# WebClient object with the DownloadString function. The C# WebClient object has been extended such that it supports timeout values. The al_timeout parameter is in milliseconds
13 | Returns "*ERROR* - Not supported"
Any other value | Any other value will result in an empty string "" being returned
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_saveurl1("https://www.power-home.com/images/ph.png","c:\powerhome\ph.png",1,8,5000)
The above example will retrieve the binary data for the ph.png graphic file using a C# WebRequest object and save it to the c:\powerhome directory. The function will timeout in 5 seconds (5000 millseconds) if the result hasnt been returned by then.


ph_saveurlviaproxy1

ph_saveurlviaproxy1 PowerHome formula function
Description
Retrieves the output from a URL using the specified proxy server values and saves it to a file.
Syntax
ph_saveurlviaproxy1 ( as_url, as_proxy, al_proxyport, as_authorization, as_file, ai_writemode, ai_type, ai_timeout )
ph_saveurlviaproxy1 ( as_url, as_headers, as_proxy, al_proxyport, as_authorization, as_file, ai_writemode, ai_type, ai_timeout )
Argument | Description
as_url | String. The URL whose HTML you wish to retrieve
as_headers | String (Optional). Additional HTTP headers you would like to be sent as part of the request. Specify headers in the same format that would be used for structuring a valid HTTP request. Separate multiple headers with either a carriage return / linefeed pair or a linefeed (use the same separator for ALL the headers). An example header may look like: "Accept-Type: text/html~r~nPragma: no-cache". If this parameter is omitted, an empty string "" will be used
as_proxy | String. The proxy server the request will made through
al_proxyport | Long. The proxy server port
as_authorization | String. The userid and password for the proxy server. Separate the userid from the password using a colon character. Example: userid:password
as_file | String. The full path and filename to save the URL output to
ai_writemode | Integer. Controls how the data is saved. Use 0 to append the output to the file. Use 1 to replace the file if it currently exists
ai_type | Integer. A number representing the method of HTML retrieval from the URL. See usage below for an explanation of the valid types
ai_timeouot | Integer. The max length of time in seconds to wait for the HTML before the function times out
Return value
String. Returns either the HTTP headers from the URL or an error message
Usage
Use this function to retrieve the output from a URL via a proxy server and directly save it to a file. This will allow you to retrieve binary data that isnt possible to retrieve using the ph_geturl functions.

See the table below for an explanation of options available to the type parameter:
0 | Retrieves the URL output using a raw socket. This would be identical to the method used by the ph_saveurlviaproxy function.
1 | Retrieves the URL output using a Catalyst HTTP control using method 1.
2 | Retrieves the URL output using a Catalyst HTTP control using method 2.
3 | Retrieves the URL output using a Catalyst HTTP control using method 3.
Multiple methods are provided as certain websites, operating systems, etc. may have a problem with one method or the other. Choose the method that produces the most desireable results.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_saveurlviaproxy1("www.power-home.com/images/phwiki.gif","192.168.0.150",80,"userid:password","c:\powerhome\phwiki.gif",1,1,5)


ph_sendemail

ph_sendemail PowerHome formula function
Description
Sends an email message.
Syntax
ph_sendemail ( s, s, s )
Argument | Description
s | The email addresses you wish to send a message to. Separate multiple email addresses with commas.
s | The subject of the email.
s | The text of the email message.
Return value
Integer. Returns 0 if successful, 1 if an error occurred while logging in to the mail system, and 2 if an error occurred while sending the email message. You can specify multiple recipients by separating the email addresses with commas.


ph_sendsmtpemail

ph_sendsmtpemail PowerHome formula function
Description
Sends an email message using SMTP.
Syntax
ph_sendsmtpemail ( Server, Port, fromAddr, toAddr, Subject, text )
Argument | Description
Server | String. The IP or DSN of the SMTP server.
Port | Number. The port of the SMTP server. This is typically port 25.
fromAddr | String. The email address you are sending the email from. Most SMTP servers require you to enter a valid email address registered on the SMTP server. You may optionally enter a userid and password if your SMTP server requires authentication.
toAddr | String. The email addresses you wish to send a message to. Separate multiple email addresses with commas.
Subject | String. The subject of the email.
text | String. The text of the email message.
Return value
Integer. Returns 0 if successful. Any other value signifies an error occurred. You can specify multiple recipients by separating the email addresses with commas.
Usage
Use this function to send email using raw SMTP rather than the MAPI interface that the ph_sendemail function uses. If an error occurs while sending using SMTP, the PowerHome system will not hang like it does when sending using MAPI.

If your SMTP server requires authentication, then supply the userid and password in the third parameter after the "From" email address. Separate the "from" email address, userid, and password with commas (do not add spaces).

If your SMTP server uses SSL or TLS, then use a negative port number. In the case of Gmail, the port number is 465 and uses SSL so you would specify a port of -465
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_sendsmtpemailfile("smtp.mail.yahoo.com",465,"yourmail@yahoo.com,login,password", "someone@gmail.com","Motion Alert","Driveway Motion Detected.")
{Sends a plain email message}
. ph_sendsmtpemail("smtp.gmail.com", -465,"johndoe@gmail.com,johndoe,121239", "4075551212@cingularme.com","Motion Alert","Motion on DrvCam detected at " + ph_getglobal_s ("LASTRIGDRV")
{Sends an SMS text mesage to a smartphone.}


ph_sendsmtpemailasync

ph_sendsmtpemailasync PowerHome formula function
Description
Sends email via SMTP asynchronously with the option to automatically perform a PowerHome action once the email is sent.
Syntax
ph_sendsmtpemailasync ( type, id, server, port, from, to, subject, message )
Argument | Description
type | Integer. The type of PowerHome action you'd like executed when the email is sent. Use 0 to not trigger any action. Use 1 to trigger a macro. Use 2 to execute a named formula ID. Use 3 to execute a raw formula. This parameter goes hand in hand with the id parameter.
id | String. Data for the triggered action. If type is 0, then set this parameter to an empty string. If type is 1, then set ID to a valid macro ID. If type is 2, then set ID to a valid formula ID. If type is 3, then ID should contain a valid raw formula you'd like to be executed.
server | String. The IP or URL of the SMTP server.
port | Long. The port for the SMTP server. Typically, this will be 25.
from | String. An email address for who the mail is from. If your SMTP server requires authentication then this field will also contain the userid and password. See usage below for more detail.
to | String. The email address to send the email to. If you're sending to multiple recipients, then separate the email addresses with a comma.
subject | String. The subject of the email.
message | String. The message body of the email.
Return value
Integer. This function will return a 0.
Usage
Use this function to send email via SMTP asynchronously. Email will be sent in the background and PowerHome will operate without hanging for the email to complete. If you'd like to trigger an action once the email is sent, set the type and id parameters appropriately.

If you trigger a process (type = 1, 2, 3) when the email is sent, then your macro or formula will have access to the results of the SMTP email send operation. Three return values are available. Use ph_getmtret to retrieve the results of the send process. If successful, this value will be 0. If a failure occured, this value will be a positive number from 1 to 9 indicating at what step in the send process the failure occured. Use ph_getlasterror to retrieve a numeric value indicating what the specific error was. This value will be 0 if there is no failure, otherwise non-zero if a failure occured. Use ph_getlasterrorstring to retrieve a string representation of what step in the send process a failure occured. If email transmission was successful, then this string will indicate success.

If your SMTP server requires authentication, then embed the credentials in the from parameter. The from parameter should first contain the from email address followed by a comma (don't use any spaces) followed by the SMTP userid followed by a comma followed by the SMTP password.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_sendsmtpemailasync(1,"EMAILCOMPLETE","www.smtpserver.com",25,"power-home.com,ph,mypass","dhoward@myx10.com","Test Message","This is a test message body")
The above example will send email asynchronously and when complete, will execute the EMAILCOMPLETE macro.


ph_sendsmtpemailfile1

ph_sendsmtpemailfile1 PowerHome formula function
Description
Sends email (and optionally files) using SMTP via a C# SmtpClient control
Syntax
ph_sendsmtpemailfile1 ( as_server, al_port, as_user, as_password, ai_usessl, as_from, as_to, as_subject, as_message, as_attachments )
Argument | Description
as_server | String. The IP or URL of the SMTP server to use
al_port | Long. The port for the SMTP server. Typically this is 25
as_user | String. The username to send SMTP email as for the server
as_password | String. The password for the above username. Supply an empty string "" if username/password is not required
ai_usessl | Integer. A flag to specify whether to use SSL/TLS or not. Use 0 to NOT enable SSL/TLS. Any other value to enable it
as_from | String. The "from" email address
as_to | String. The "to" email address
as_subject | String. The subject for the email
as_message | String. The email message body
as_attachments | String. The full path and filename of files to attach to the email. Separate multiple files with a vertical bar "|" character. Set this parameter to an empty string "" if there are no file attachments
Return value
Integer. Returns 0 if successful. Returns 1 if an exception occurs
Usage
Use this function as an alternative to the ph_sendsmtpemail( ) and ph_sendsmtpemailfile( ) functions (both of which use a Catalyst SMTP control). Depending upon the particular SMTP server one function over the other may perform better
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_sendsmtpemailfile1("smtp.gmail.com",465,"dhoward@gmail.com","yourpassword",1,"dhoward@gmail.com","support@power-home.com","Problem with controller","An error occurred at 2020-05-17 18:10 with the Insteon controller","c:\powerhome\screenshot1.jpg|c:\powerhome\screenshot2.jpg") - Returns 1 if successful. NOTE: Google has recently updated their service and by default no longer allows what they deem "less secure apps" to send SMTP unless youturn on "allow less secure apps" in your GMail settings. Even though this example uses SSL and follows GMail guidelines, "allow less secure apps" must be enabled in order for the example to work
. ph_sendsmtpemailfile1()


ph_sendsmtpemailfileasync

ph_sendsmtpemailfileasync PowerHome formula function
Description
Sends email via SMTP asynchronously with the option to automatically perform a PowerHome action once the email is sent. This function also allows for file attachments to be sent.
Syntax
ph_sendsmtpemailfileasync ( type, id, server, port, from, to, subject, message, attach )
Argument | Description
type | Integer. The type of PowerHome action you'd like executed when the email is sent. Use 0 to not trigger any action. Use 1 to trigger a macro. Use 2 to execute a named formula ID. Use 3 to execute a raw formula. This parameter goes hand in hand with the id parameter.
id | String. Data for the triggered action. If type is 0, then set this parameter to an empty string. If type is 1, then set ID to a valid macro ID. If type is 2, then set ID to a valid formula ID. If type is 3, then ID should contain a valid raw formula you'd like to be executed.
server | String. The IP or URL of the SMTP server.
port | Long. The port for the SMTP server. Typically, this will be 25.
from | String. An email address for who the mail is from. If your SMTP server requires authentication then this field will also contain the userid and password. See usage below for more detail.
to | String. The email address to send the email to. If you're sending to multiple recipients, then separate the email addresses with a comma.
subject | String. The subject of the email.
message | String. The message body of the email.
attach | String. The full path and filename of the file attachment you'd like to send. Separate multiple attachments with a vertical bar character "|". Don't use spaces.
Return value
Integer. This function will return a 0.
Usage
Use this function to send email with attachments via SMTP asynchronously. Email will be sent in the background and PowerHome will operate without hanging for the email to complete. If you'd like to trigger an action once the email is sent, set the type and id parameters appropriately.

If you trigger a process (type = 1, 2, 3) when the email is sent, then your macro or formula will have access to the results of the SMTP email send operation. Three return values are available. Use ph_getmtret to retrieve the results of the send process. If successful, this value will be 0. If a failure occured, this value will be a positive number from 1 to 9 indicating at what step in the send process the failure occured. Use ph_getlasterror to retrieve a numeric value indicating what the specific error was. This value will be 0 if there is no failure, otherwise non-zero if a failure occured. Use ph_getlasterrorstring to retrieve a string representation of what step in the send process a failure occured. If email transmission was successful, then this string will indicate success.

If your SMTP server requires authentication, then embed the credentials in the from parameter. The from parameter should first contain the from email address followed by a comma (don't use any spaces) followed by the SMTP userid followed by a comma followed by the SMTP password.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_sendsmtpemailfileasync(1,"EMAILCOMPLETE","www.smtpserver.com",25,"power-home.com,ph,mypass","dhoward@myx10.com","Test Message","This is a test message body","c:\powerhome\phwiki.gif|c:\powerhome\pwrhome.ini")
The above example will send email asynchronously along with the two specified attachments and when complete, will execute the EMAILCOMPLETE macro.


ph_sendudp

ph_sendudp PowerHome formula function
Description
Broadcast UDP data to the network using a socket
Syntax
ph_sendudp ( as_url, al_port, as_data )
ph_sendudp ( as_url, al_port, as_data, ai_flags )
Argument | Description
as_url | String. The URL or IP to send UDP data to
al_port | Long. The port to send UDP data to
as_data | String. The data you wish to send via UDP
ai_flags | Integer (Optional). A flags parameter specifying how the data is sent. See Usage below for details. If this parameter is omitted, a value of 0 will be used
Return value
Integer. Returns 0 if the function is successful. Returns 1 if there is a problem connecting. Returns 2 if there is a problem sending
Usage
Use this function to send data via UDP. If you need to broadcast non-typeable characters, use the overload that includes the ai_flags parameter and set it to 1. If your message doesnt contain special characters, set the ai_flags parameter to 0 or use the overload that does not include the ai_flags parameter

If the ai_flags parameter is 1, then escaped characters are allowed in the as_data parameter. Escaped characters can be coded as either hexadecimal or decimal. Escaped characters are preceeded by a backslash "\" character. If encoding in hexadecimal, follow the "\" character with "x" followed by two hexadecimal digits (0 - 9 and A-F) for an ASCII value of 0 to 255. If encoding in decimal, follow the "\" character with 3 decimal digits in the range of 0 to 255. The carriage return character can be escaped as either "\x0D" or "\013". If escaped characters are allowed (ai_flags = 1) then any backslash characters "\" you wish to send in the data MUST also be escaped as either "\x5C" or "\092".

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_sendudp("192.168.0.255",8100,"First floor Thermostat Cool Setpoint changed to 78",0) - Returns 0 if successful. No special characters were included in the message so the ai_flags value was set to 0 or could have been omitted


ph_setwebcontenttype

ph_setwebcontenttype PowerHome formula function
Description
Sets the content-type value to be returned by a PSP web page.
Syntax
ph_setwebcontenttype ( type )
Argument | Description
type | A string representing the content type to be returned. The content-type is default set to "text/html" but can be changed to suit the type of content being returned by the PSP page.
Return value
Integer. Returns a 0.


ph_setwebcookie

ph_setwebcookie PowerHome formula function
Description
Sets a web cookie within the PowerHome web server.
Syntax
ph_setwebcookie ( name, value, path, domain, expires )
Argument | Description
name | String. The name of the cookie.
value | String. The value to assign to the cookie.
path | String. An optional path parameter for the cookie.
domain | String. An optional domain parameter for the cookie.
expires | Double. An optional parameter for setting the expiration of a cookie. The expiration date will be calculated using this parameter in minutes from the current time.
Return value
Integer. Returns 0.
Usage
This function only has meaning when run from within the context of a PowerHome PSP page.


ph_setwebnexturl

ph_setwebnexturl PowerHome formula function
Description
Sets the URL of the next web page to be displayed.
Syntax
ph_setwebnexturl ( nexturl )
Argument | Description
nexturl | A string representing the URL for the next web page.
Return value
Integer. Returns a 0. This function is useful for navigation between web pages where PowerHome executing a formula or macro. A common use would be for a Control Center web page where a formula or macro button would be used for navigation. When pressing this button, you could perform PowerHome functions and when done, set the next web page that will be displayed. Not all PowerHome web pages support changing the next URL. Functions that do support the next URL are: CCBUTTON, PLAYMACRO, EVALFORMULA, and EXECSENDKEYS.


ph_setwebreturn

ph_setwebreturn PowerHome formula function
Description
Sets the return value to be returned by a PSP web page.
Syntax
ph_setwebreturn ( value )
Argument | Description
value | An integer representing the return value for the PSP. This is default set to 200 and signifies success. Typical values are 401 to require a userid/password, 404 for not found, and 500 for server error.
Return value
Integer. Returns a 0.


ph_urlescape

ph_urlescape PowerHome formula function
Description
Escapes a URL or string based upon the flags parameter.
Syntax
ph_urlescape ( input, flags )
Argument | Description
input | String. The URL or string to escape
flags | Integer. Controls what characters are escaped. See usage below.
Return value
String. Returns the escaped URL or string.
Usage
Use this function to escape a URL or string for proper transmission.

The flags parameter is detailed below. Add individual values together to achieve the desired flags parameter.
1 | Add 1 to flags parm to escape these characters: # < > @ ;. The characters will be escaped as %xx where xx is the hexadecimal value for the character.
2 | Add 2 to flags parm to escape these characters: { } | \ ^ ~ [ ] ` $. The characters will be escaped as %xx where xx is the hexadecimal value for the character.
4 | Add 4 to flags parm to escape the % character. The % character will be escaped with %25.
8 | Add 8 to flags parm to escape the / character. The / character will be escaped with %2f.
16 | Add 16 to flags parm to escape the ? character. The ? character will be escaped with %3f.
32 | Add 32 to flags parm to escape the & character. The & character will be escaped with %26.
64 | Add 64 to flags parm to escape the = character. The = character will be escaped with %3d.
128 | Add 128 to flags parm to escape the : character. The : character will be escaped with %3a.
256 | Add 256 to flags parm to escape the " and ' characters. The " character is escaped with %22. The ' character is escaped with %27.
512 | Add 512 to flags parm to escape the + character. The + character will be escaped with %2b.
1024 | Add 1024 to flags parm to escape the space character. The space character will be escaped with %20.
2048 | Add 2048 to flags parm to escape carriage return, line feed, and tab characters. The carriage return character will be escaped with %0d. The line feed character is escaped with %0a. The tab character is escaped with %09.
4096 | Add 4096 to flags parm to escape every character. The characters will be escaped as %xx where xx is the hexadecimal value for the character.
8192 | Add 8192 to flags parm to cause the escape process to ONLY escape characters after the first ? character.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_urlescape("http://www.power-home.com/ph-cgi/macro?id=TEST MACRO&parm1=<data>",9217)
The above example will return "http://www.power-home.com/ph-cgi/macro?id=TEST%20MACRO&parm1= %3cdata%3e"


ph_webaddblob

ph_webaddblob PowerHome formula function
Description
Adds blob data to a PSP blob output page.
Syntax
ph_webaddblob ( type, parm1 )
Argument | Description
type | The type of blob data to add. Use 1 to convert parm1 string data into blob data. Use 2 to read the file specified in parm1 and add it to the blob output. Use 3 to retrieve the URL specified in parm1 into the blob output. Use 4 to add binary data contained in parm1 that has been previously encoded using the s2h function. The data will be decoded to binary and added to the blob output.
parm1 | String. If the type is 1, the string is converted to a blob and added to the blob output page. If the type is 2, then parm1 should point to the full path and filename of a file to append to the blob output page. If type is 3, then parm1 should contain the URL of a file or webpage to be retrieved and appended to the blob output file. If type is 4, then parm1 should contain data that was encoded using the s2h function.
Return value
Integer. Returns 0 if successful, 1 if an error ocurrs.
Usage
This function is only useful from within PSP pages. Every PSP page contains a blob output page. In a normal PSP page, output blob page is empty and the file is searched for formulas enclosed within PSP tags that are evaluated and then replaced with the results. The resulting file is then returned from the webserver. If data is added to the blob output page using the ph_webaddblob function, then the blob output page is instead returned from the webserver instead of the evaluated PSP.

See also ph_webclearblob.


ph_webclearblob

ph_webclearblob PowerHome formula function
Description
Clears blob data in a PSP blob output page.
Syntax
ph_webclearblob ( )
Return value
Integer. Returns 0 if successful, 1 if an error ocurrs.
Usage
This function is only useful from within PSP pages. Every PSP page contains a blob output page. In a normal PSP page, output blob page is empty and the file is searched for formulas enclosed within PSP tags that are evaluated and then replaced with the results. The resulting file is then returned from the webserver. If data is added to the blob output page using the ph_webaddblob function, then the blob output page is instead returned from the webserver instead of the evaluated PSP. Use this function to clear data contained in the blob output page so that the evaluated PSP page will be returned.


ph_webds

ph_webds PowerHome formula function
Description
Returns a dynamic HTML table containing the PowerHome Device Status screen.
Syntax
ph_webds ( dstype, location, filter, sort, nexturl, cols )
Argument | Description
dstype | Integer. The type of web based Device Status screen to return. Currently only a value of 0 is supported.
location | String. Filter the device status list by location. Use empty string "" to return all.
filter | String. Filter the device status list with a user defined filter. Use empty string "" to not filter.
sort | String. Sort the device status list using a user defined sort. Use empty string "" to retain the default sort.
nexturl | String. A string representing the URL of the next page to open after processing a device status control button.
cols | String. A string the columns and column order that would like used in the HTML table. See Usage below.
Return value
String. Returns a complete HTML table source code for the PowerHome Device Status screen at that moment.
Usage
Use this function to quickly incorporate the Device Status screen directly into your own PSP code creations with virtually no coding. Using this function, you can create your own menus and mix or match individual PowerHome web elements.

See the table below for the available columns to use in the cols parameter:
1 | Control
2 | Status
3 | Device Name
4 | Location
5 | Type
6 | ID
7 | Last Change
Leave the "cols" parameter blank to accept the default columns and order. This will be equivalent to "1,2,3,4,5,6,7".
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_webds(0,"Family Room","","","ds.psp","2,1,3,7") - Generates a version of the Device Status screen that displays only devices with a location of Family Room and only shows the columns of Status, Control, Device Name, and Last Change in that order. If any Control options are used on this screen, the reload page will be "ds.psp" (typically the file that is used to create this screen in the first place).


ph_webdschg

ph_webdschg PowerHome formula function
Description
Generates a JSON string containing all Device Status changes that occurred after the specified timestamp
Syntax
ph_webdschg ( dt_timestamp )
Argument | Description
dt_timestamp | Datetime. The reference datetime from which all Device Status changes will be included in the JSON output
Return value
String. Returns a JSON string containing all Device Status changes that occurred after the datetime in the dt_timestamp parameter
Usage
This function is used by the web based Device Status screen to update status changes periodically after they occur using AJAX. Typically would not be call by a user but included for those who may want to write their own status screens
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_webdschg(datetime(date("2020-05-17"),time("17:00:00"))) - Returns JSON data containing all Device Status changes that have occurred since May 17th, 2020 at 5:00 pm


ph_webml

ph_webml PowerHome formula function
Description
Returns a dynamic HTML table containing a dropdown list of PowerHome macros along with a Play button.
Syntax
ph_webml ( ai_type, as_nexturl )
Argument | Description
ai_type | Integer. Specifies the "target" value to be used for the "playmacro" form. A value of 0 will set the "target" = "blankframe" and the as_nexturl to "/ph-cgi/blank. Any other value will not specify a "target" and will use the value supplied in the as_nexturl parameter
as_nexturl | String. A string representing the URL of the next page to open after playing the selected macro.
Return value
String. Returns the resulting HTML containing a table with a Macro dropdown list and a Play button
Usage
Use this function to quickly incorporate a dropdown list of PowerHome macros directly into your own PSP code creations with virtually no coding. Using this function, you can create your own menus and mix or match individual PowerHome web elements.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_webml(0,"") - Specifies to use a nexturl of "/ph-cgi/blank" and a target value of "blankframe". The resulting HTML will look something like this:

<table width=100% cellpadding=0 cellspacing=2 class="ht3">
<tr class="ht3r1">
<td align=left valign=center class="ht3r1c1">Macro: <form method="get" name="playmacro" action="/ph-cgi/playmacro" target="blankframe"><input type="hidden" name="nexturl" value="/ph-cgi/blank"><select name="id" size=1 class="ht3r1c1e1">
<option value=""></option>
<option value="SENSORARRAY">SENSORARRAY</option>
<option value="TEST1">TEST1</option>
<option value="TRIGGER DISABLE">TRIGGER DISABLE</option>
<option value="WAITFORMULA">WAITFORMULA</option></select>
<input type="button" value="Play" class="ht3r1c1e2" onclick="document.playmacro.submit();document.playmacro.reset();">
</form>
</td>
</tr>
</table>


ph_webmu

ph_webmu PowerHome formula function
Description
Returns a dynamic HTML table containing the PowerHome web menu as defined in the Webserver setup screen.
Syntax
ph_webmu ( type )
Argument | Description
type | Integer. An integer representing the type of menu to be generated. A 0 will generate the HTML for the entire menu as defined in the PowerHome Webserver setup screen. A value of 1 will create a menu containing only the defined Main URL.
Return value
String. Returns a complete HTML table source code for the PowerHome Webserver menu. Use this function to quickly incorporate the defined PowerHome web menu directly into your own PSP code creations with virtually no coding. Using this function, you can mix or match individual PowerHome web elements to create your personalized web screens.


ph_websl

ph_websl PowerHome formula function
Description
Returns a dynamic HTML table containing the standard PowerHome web status line.
Syntax
ph_websl ( )
Return value
String. Returns a complete HTML table source code for the PowerHome web interface status line. Use this function to quickly incorporate the PowerHome web status line directly into your own PSP code creations with virtually no coding. Using this function, you can mix or match individual PowerHome web elements to create your personalized web screens.


ph_clearx10hist

ph_clearx10hist PowerHome formula function
Description
Clears the incoming X10 history buffers
Syntax
ph_clearx10hist ( id, type )
Argument | Description
id | A string representing the buffer you would like to clear. A value of "ALL" will clear all housecode buffers as well as the global buffer and extended buffer. A value of "GLOBAL" will clear just the global buffer. A value of "A" thru "P" will clear the appropriate housecode buffer. A value of "EXT" will clear only the extended buffer.
type | An integer representing the type of clearing to perform. A value of 0 will clear the entire buffer area of the specified buffer(s). A value of 1 will clear only the first buffer entry of the specified buffer(s).
Return value
Integer. Returns 0.


ph_x10lookup

ph_x10lookup PowerHome formula function
Description
Returns the X10 device ID when given the housecode and unitcode.
Syntax
ph_x10lookup ( hc, uc )
Argument | Description
hc | String. The housecode to lookup.
uc | Integer. The unitcode to lookup.
Return value
String. Returns the X10 device ID from the X10 Devices table. Returns an empty string if the housecode/unitcode combination is not found.


ph_x10other

ph_x10other PowerHome formula function
Description
This function is used to send non-standard X10 commands via the specified controller.
Syntax
ph_x10other ( ctlr, house, cmd )
Argument | Description
ctlr | String. The ID of the controller to send the X10 command to.
house | String. The housecode for the X10 command.
cmd | String. The X10 command to send.
Return value
Integer. Returns - 1 if an error occurs (such as the controller does not exist or the controller does not support X10 other commands). Otherwise, 0 is returned.
Usage
This function is currently only supported by the CM15A RF controller. This function is for sending the non-standard X10 commands to this controller such as camera control commands. See the ActiveHome Scripting SDK for a complete list of valid commands.
Examples
The following examples demonstrate typical syntax/usage for this function.
ph_x10other("CM15ARF","K","CamGoPosition5")
The above example tells the X10 camera on housecode K to go to preset position 5.


ph_getzwavecalcval

ph_getzwavecalcval PowerHome formula function
Description
Retrieves the current calculated value of a Z-Wave device in the Device Status Screen. This function DOES NOT cause the controller to retrieve the values and only returns what is currently stored within PowerHome
Syntax
ph_getzwavecalcval ( )
ph_getzwavecalcval ( as_id )
Argument | Description
as_id | String (Optional). The ID of the Z-Wave device. If this parameter is not supplied, the System variable ZWAVE will be used for the ID.
Return value
String. Returns the currently stored calculated value for the specified Z-Wave device.
Usage
This function does not cause the controller to query the value. If you need to first have the controller query the Z-Wave device for it's current status, first call the ph_getzwaverawvalrt( ) and then call this function. You can also use the ph_zwaveget( ) function to have the controller queue a request for the Z-Wave device to update its status. When a request is made to query the status of a Z-Wave device, either real time with ph_getzwaverawvalrt( ) or queued with ph_zwaveget( ), the raw value will be retrieved and then the calculated value will be updated based upon the raw value.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getzwavecalcval("FAMILYRM") - Returns the calculated value for the FAMILYRM Z-Wave device that is currently stored in the database


ph_getzwavedata

ph_getzwavedata PowerHome formula function
Description
Retrieves specified data for a Z-Wave device defined within PowerHome from the internally stored JSON structure for all Z-Wave devices.
Syntax
ph_getzwavedata ( as_id, as_parm, ai_type )
Argument | Description
as_id | String. The ID of the Z-Wave device for which to retrieve values
as_parm | String. Based upon the Z-Wave ID in the as_id parameter, this field will specify the final portion of the name so that a fully qualified JSON identifier can be constructed
ai_type | Integer. The specific column of data you would to have returned from the JSON structure. Valid values are 0 thru 4. See Usage below
Return value
String. Returns the specified data for the Z-Wave device ID requested in the as_id parameter.
Usage
Use this function to access Z-Wave device related data that is not normally available from within the standard PowerHome database structures.

PowerHome maintains a JSON structure that contains the full device and status tree that is available within the current Z-Wave controller. This is a flattened JSON structure of name/value pairs and is accessed by a fully qualified JSON name. In the case of a Razberry controller, this would typically look like this:

devices.20.instances.0.commandClasses.114.data.serialNumber

Assuming a Z-Wave device defined within PowerHome on the Devices tab of the Zwave Explorer for Node ID 20, Instance 0, CC 114, PowerHome will build the JSON name up based solely upon the Z-Wave ID supplied in the as_id parameter. To retrieve the fully qualified JSON name above, you would need to set the as_parm parameter to "serialNumber". Everything prior to "serialNumber" will be automatically built for you by the function.

The ai_type parameter must have a value from 0 to 4. A value of 0 will return the string value associated with the JSON name. A value of 1 will return the data type of the string value. A value of 2 will return the Invalidate Time for the JSON name. A value of 3 will return the Update Time for the JSON name. A value of 4 will return the Other value associated with the JSON name.

In normal usage, this function and the ph_getzwavedataraw( ) function will probably never be called. These functions are for those who want to access the Z-Wave data within PowerHome at its lowest level

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getzwavedata("FAMILYRM","serialNumber",0) - Assuming that the Z-Wave device ID FAMILYRM equates to Node ID 20, Instance 0, CC 114, the function will return the string value for the "devices.20.instances.0.commandClasses.114.data.serialNumber" JSON name


ph_getzwavedataraw

ph_getzwavedataraw PowerHome formula function
Description
Retrieves specified data for a fully qualified Z-Wave entry from the internally stored JSON structure for Z-Wave devices. This is different from the ph_getzwavedata function in that the you must fully qualify the name of the JSON value you wish to retrieve and the device does NOT have to be defined within PowerHome
Syntax
ph_getzwavedataraw ( as_ctlr, as_id, ai_type )
Argument | Description
as_ctlr | String. The ID of the Z-Wave controller
as_id | String. The fully qualified JSON name for the requested value
ai_type | Integer. The type of data you wish to have returned. Valid values are 0 thru 4
Return value
String. Returns the specified data for the fully qualified JSON name specified in as_id from the Z-Wave controller specified in as_ctlr.
Usage
Use this function to access Z-Wave device data at its lowest level from the internal JSON structure for Z-Wave.

PowerHome maintains a JSON structure that contains the full device and status tree that is available within the specified Z-Wave controller. This is a flattened JSON structure of name/value pairs and is accessed by a fully qualified JSON name. In the case of a Razberry controller, this would typically look like this:

devices.20.instances.0.commandClasses.114.data.serialNumber

To retrieve the value for the fully qualified JSON name above, you would need to set the as_id parameter to "devices.20.instances.0.commandClasses.114.data.serialNumber". The specified Node ID and Command Class do NOT have to be defined within PowerHome.

The ai_type parameter must have a value from 0 to 4. A value of 0 will return the string value associated with the JSON name. A value of 1 will return the data type of the string value. A value of 2 will return the Invalidate Time for the JSON name. A value of 3 will return the Update Time for the JSON name. A value of 4 will return the Other value associated with the JSON name.

In normal usage, this function and the ph_getzwavedata( ) function will probably never be called. These functions are for those who want to access the Z-Wave data within PowerHome at its lowest level

Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getzwavedataraw("RAZ","devices.20.instances.0.commandClasses.114.data.serialNumber",0) - Returns the string value for the "devices.20.instances.0.commandClasses.114.data.serialNumber" JSON name contained within the "RAZ" Z-Wave controller


ph_getzwavedt

ph_getzwavedt PowerHome formula function
Description
Retrieves the current stored datetime value of a Z-Wave device from when it was last updated.
Syntax
ph_getzwavedt ( )
ph_getzwavedt ( as_id )
Argument | Description
as_id | String (Optional). The PowerHome defined Z-Wave ID for the desired device. If this parameter is not supplied, the System variable for ZWAVE will be used for the ID
Return value
Datetime. Returns the last change date/time for the specified Z-Wave device ID
Usage
Use this function to query when the Z-Wave device was last updated within PowerHome
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getzwavedt("FAMILYRM")


ph_getzwaverawval

ph_getzwaverawval PowerHome formula function
Description
Retrieves the current raw value of a Z-Wave device in the Device Status Screen. This function DOES NOT cause the controller to retrieve the values and only returns what is currently stored within PowerHome.
Syntax
ph_getzwaverawval ( )
ph_getzwaverawval ( as_id )
Argument | Description
as_id | String (Optional). The PowerHome Z-Wave device ID you wish to get the raw value for. If this parameter is not supplied, the System variable for ZWAVE will be used for the ID
Return value
Double. Returns the raw value associated with the Z-Wave device ID in as_id.
Usage
Use this function to retrieve the current stored value for the Z-Wave device ID. This function will NOT have the Z-Wave controller query the device.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getzwaverawval("FAMILYRM)


ph_getzwaverawvalrt

ph_getzwaverawvalrt PowerHome formula function
Description
Requests the Z-Wave controller to query the specified Z-Wave device and retrieve its current status in real time
Syntax
ph_getzwaverawvalrt ( as_id, ad_timeout )
Argument | Description
as_id | String. The PowerHome Z-Wave device ID whose status you would like to have queried in real time
ad_timeout | Double. The number of seconds to wait for the returned raw value before timing out
Return value
Long. Returns the raw value associated the the Z-Wave device after the controller has queried the device in real time
Usage
Use this function to force the Z-Wave controller to query the specified Z-Wave device and wait (up to the ad_timeout value in seconds) for the return value. Use care when using this function as all PowerHome processing will be "paused" while this function is waiting for the controller to return. It is advisable that you set your ad_timeout parameter appropriately. If you would like the Z-Wave controller to query the device for current status but don't necessarily need to wait for that status to be returned in real time, use the ph_zwaveget( ) instead.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_getzwaverawvalrt("FAMILYRM",10)


ph_setzwavedisplay

ph_setzwavedisplay PowerHome formula function
Description
Sets the internally stored display values (foreground color, background color, and graphic) for a Z-Wave device
Syntax
ph_setzwavedisplay ( al_foreground, al_background, as_graphic, ai_refresh)
ph_setzwavedisplay ( as_id, al_foreground, al_background, as_graphic, ai_refresh )
Argument | Description
as_id | String (Optional). The ID of the Z-Wave device. If this parameter is not supplied, the System variable ZWAVE will be used for the ID
al_foreground | Long. The foreground color you would like to be set. Use -1 to not update the foreground color
al_background | Long. The background color you would like to be set. Use -1 to not update the background color
as_graphic | String. The graphic file (full path and filename) that you would like to be associated with the device status. Use a single space " " if you don't wish to update the graphic
ai_refresh | Integer. Specifies whether the Device Status screen should be refreshed or not. A value of 0 will not refresh the Device Status screen. Any other value will force a refresh
Return value
Integer. Returns 0 if successful. Returns 1 if the ID does not exist. Returns 2 if an error occurs during update
Usage
Use this function to manually update the Device Status colors and graphic associated with a Z-Wave device
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_setzwavedisplay("KITCHENLIGHT",0,rgb(255,255,0),"c:\powerhome\web\graphics\on.jpg",1) - Returns 0 if successful. For the KITCHENLIGHT Z-Wave device, sets the foreground color to black, the background color to yellow, and sets the graphic file to c:\powerhome\web\graphics\on.jpg. The Device Status screen is refreshed to immediately show the changes


ph_zwaveget

ph_zwaveget PowerHome formula function
Description
Queues a request with the Z-Wave controller to retrieve the current status of the specified Z-Wave device
Syntax
ph_zwaveget ( as_id )
Argument | Description
as_id | String. The ID of the Z-Wave device whose status you would like the controller to request
Return value
Integer. Returns 0 if the request was successfully queued in the associated Z-Wave controller. Returns -100 if the Z-Wave ID is invalid. Returns -1 if the associated controller is not active. Returns -51 if the command is not supported. Returns -52, -53, -54 if internal parameters for the command are out of range
Usage
Use this function to have a Z-Wave controller request the current status for a Z-Wave device.
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_zwaveget("FRONTDOOR") - Returns 0 if the request for status for the Z-Wave device identified by FRONTDOOR is successfully queued in the controller. It is up to the controller as to when this request is actually realized as Z-Wave commands being transmitted to request status


ph_zwavegetconfig

ph_zwavegetconfig PowerHome formula function
Description
Queues a request with the Z-Wave controller to query and retrieve a configuration parameter for the specified Z-Wave node ID
Syntax
ph_zwavegetconfig ( as_controller, ai_nodeid, ai_instance, ai_parm )
Argument | Description
as_controller | String. The ID of the Z-Wave controller to queue the request with
ai_nodeid | Integer. The Z-Wave node number. Must be in the range of 1 to 255
ai_instance | Integer. The instance number for the node you wish to query. Must be in the range of 0 to 255
ai_parm | Integer. The parameter number you wish to query. Must be in the range of 0 to 255
Return value
Integer. Returns 0 if the request was successfully queued with the specified Z-Wave controller. Returns -1 if the specified controller does not exist or isnt active. Returns -51 if the command is not supported. Returns -52, -53, -54 if the node, instance, or parm parameters are out of range
Usage
Use this function to queue a request to retrieve a configuration parameter for a Z-Wave node/instance. This function queues a Z-Wave Command Class (CC) 112 with the specified controller. The parameter value to pass needs to be obtained from the particular Z-Wave device's documentation. Z-Wave configuration parameters are numbers from 0 to 255. Each number represents a different configuration parameter that is specific to that particular manufacturer and device type. PowerHome does not attempt to keep track of manufacturer device types and their specific configuration parameters and it is up to the user to glean this information from the device documentation. You can enter and store the configuration parameters for each unique node ID in the Z-Wave Explorer on the "Node Config" tab
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_zwavegetconfig("RAZ",3,0,20) - Returns 0 if successful. Assuming that node ID 3 is a Fibaro Motion sensor, parameter 20 is a request to retrieve the "Tamper Sensitivity"


ph_zwaverawset

ph_zwaverawset PowerHome formula function
Description
Allows the user to queue a raw "set" command for a specific Z-Wave node ID, instance, Command Class, and extra parameter with the specified Z-Wave controller
Syntax
ph_zwaverawset ( as_ctlr, ai_node, ai_instance, ai_cmdclass, as_extra, ai_value )
Argument | Description
as_ctlr | String. The Z-Wave controller ID to queue the set command on
ai_node | Integer. The node ID to send the set command to. Must be a value from 1 to 255
ai_instance | Integer. The instance for the above node ID to send the set command to. Must be a value from 0 to 255
ai_cmdclass | Integer. The CC for the node ID/instance that you wish to set. Must be a value from 0 to 255
as_extra | String. The extra parameter for the node ID/instance. Currently unused. Set to empty string ""
ai_value | Integer. The value you would like to set for the node ID/instance/CC. Must be a value from 0 to 255
Return value
Integer. Returns 0 if the request was successfully queued with the specified Z-Wave controller. Returns -1 if the specified controller does not exist or isnt active. Returns -51 if the command is not supported. Returns -52, -53, -54, -55 if the node, instance, CC, or value parameters are out of range
Usage
Use this function to queue a raw "set" command to a specific controller, node ID, instance, and CC. If the note ID, instance, CC is already defined as a Z-Wave device in the Z-Wave Explorer, you can achieve the same functionality using the ph_zwaveset( ) function with fewer parameters
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_zwaverawset("RAZ",8,0,38,"",255) - Returns 0 if successful. This example specifies a CC of 38 which is a Z-Wave standard "Switch Multilevel" command. The value that is queued to be set is 255 which tells the device to turn on at the last level it was previously on at


ph_zwaveset

ph_zwaveset PowerHome formula function
Description
Queues a "set" command to control a previously defined Z-Wave device (a node ID/instance/CC/extra associated to a PowerHome Z-Wave device ID)
Syntax
ph_zwaveset ( as_id, ai_value )
Argument | Description
as_id | String. The PowerHome Z-Wave Device ID to queue the "set" command for
ai_value | Integer. The value you wish to set. Must be in the range of 0 to 255
Return value
Integer. Returns 0 if the set command is successfully queued. Returns -100 if Z-Wave ID in as_id does not exist. Returns -1 if the controller associated with the Z-Wave ID is not found or active. Returns -52, -53, -54 if the internal node ID, instance, and CC are out of range. Returns -55 if the value to set (ai_value) is out of range
Usage
Use this function to queue a "set" command to a previously defined Z-Wave device within PowerHome. Similar to the ph_zwaverawset( ) function except all the extra parameters such as controller, node ID, instance, and CC are associate with the Z-Wave Device ID specified in as_id making this function simpler to call
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_zwaveset("KITCHENLIGHT",99) - Returns 0 if the set command is successfully queued. The example assumes that the Z-Wave Device ID "KITCHENLIGHT" is already defined within the Z-Wave Explorer (Devices tab) within PowerHome. This screen allows you to associate a Z-Wave controller, node ID, instance, and CC to a PowerHome Z-Wave Device ID. If the "KITCHENLIGHT" ID had a CC value of 38 (Switch Multilevel), the value to set of 99 would tell the light to turn on at 100%


ph_zwavesetcalc

ph_zwavesetcalc PowerHome formula function
Description
Allows the user to queue a "set" command for a previously defined Z-Wave Device ID. The value is a calculated value as opposed to a "raw" value
Syntax
ph_zwavesetcalc ( as_id, as_value )
Argument | Description
as_id | String. The PowerHome Z-Wave Device ID to queue the "set" command for
as_value | String. The calculated value you wish to set. This value will be converted internally using the Calc to Raw formula for the Device ID or a default value
Return value
Integer. Returns 0 if the set command is successfully queued. Returns -100 if Z-Wave ID in as_id does not exist. Returns -1 if the controller associated with the Z-Wave ID is not found or active. Returns -52, -53, -54 if the internal node ID, instance, and CC are out of range. Returns -55 if the value (converted from as_value) is out of range
Usage
Use this function to queue a "set" command for a previously defined Z-Wave device using a calculated value instead of a raw value like the ph_zwaveset( ) function. A calculated value is put through several routines to determine the appropriate raw value which is what a Z-Wave device actually understands. The first routine is to determine a base default value. If "off" or "unlock" is passed as the calculated value, the raw value will be 0. If "on" or "100" is passed as the calc value then the raw value will be 99. If the calc value is "last" or "lock", then the raw value is 255. If none of the previous defined calc values are used, then the raw value is determined by converting the string based calculated value into a numeric value. After this default value is determined, the next routine is to run the Calc to Raw formula for the specified device. If a Calc to Raw formula exists, then the previous determined "default" value will be overwritten by the formula
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_zwavesetcalc("KITCHENLIGHT","on") - Returns 0 if the set command is successfully queue. Assuming that KITCHENLIGHT is a previously defined device in the Z-Wave Explorer on the Devices tab and equates to a CC of 38 without a Raw to Calc formula defined, this set command will turn the light on at 100% brightness and would be equivalent to ph_zwaveset("KITCHENLIGHT",99)


ph_zwavesetconfig

ph_zwavesetconfig PowerHome formula function
Description
Queues a request with the Z-Wave controller to set a configuration parameter for the specified Z-Wave node ID
Syntax
ph_zwavesetconfig ( as_controller, ai_nodeid, ai_instance, ai_parm, al_value, ai_size )
Argument | Description
as_controller | String. The ID of the Z-Wave controller to queue the set command with
ai_nodeid | Integer. The Z-Wave node number. Must be in the range of 1 to 255
ai_instance | Integer. The instance number for the node you wish to query. Must be in the range of 0 to 255
ai_parm | Integer. The parameter number you wish to query. Must be in the range of 0 to 255
al_value | Long. The value you wish to set for the parameter. If ai_size is 1, should be in the range of 0 to 255. If ai_size is 2, should be in the range of 0 to 65,535. If ai_size = 4, should be in the range of 0 to 2,147,483,647
ai_size | Integer . The size of the parameter value in bytes. Must be 1, 2, or 4.
Return value
Integer. Returns 0 if the request was successfully queued with the specified Z-Wave controller. Returns -1 if the specified controller does not exist or isnt active. Returns -51 if the command is not supported. Returns -52, -53, -54 if the node, instance, or size parameters are out of range
Usage
Use this function to queue a request to set a configuration parameter for a Z-Wave node/instance. This function queues a Z-Wave Command Class (CC) 112 with the specified controller. The parameter value to pass needs to be obtained from the particular Z-Wave device's documentation. Z-Wave configuration parameters are numbers from 0 to 255. Each number represents a different configuration parameter that is specific to that particular manufacturer and device type. PowerHome does not attempt to keep track of manufacturer device types and their specific configuration parameters and it is up to the user to glean this information from the device documentation. You can enter and store the configuration parameters for each unique node ID in the Z-Wave Explorer on the "Node Config" tab. Usually it is not necessary to execute this function as the configuration parameters will already be set from the "Node Config" tab however if you wish to dynamically update a parameter on the fly, this would be the function to use
Examples
The following examples demonstrate typical syntax/usage for this function.
. ph_zwavesetconfig("RAZ",3,0,1,15,2) - Returns 0 if successful. Assuming that node ID 3 is a Fibaro Motion sensor, parameter 1 is a request to set the motion detection sensitivity. This example will set the parameter to a value of 15.


Functions

Windows Script Host Functions

PowerHome includes a number of PowerHome specific functions that extend the Windows Script Host environment and allows it to interact with PowerHome. Nearly ALL of the PowerHome "ph_" functions (only the functions that start with ph_ are extended to WSH) are available in a Windows Script Host version. For example, the ph_addtoglobal function available within the PowerHome internal formula environment is also available within Windows Script Host as ph.addtoglobal. Instead of duplicating every function listed in this Help file under the Formulas->Functions section ( Formula Functions) under the Windows Script Host functions, this section will only document the differences in between the two. To use a "ph_" function within Windows Script Host, you just have to change the "ph_" to "ph.".

Listed below are the differences:

ph_ Formula function | Windows Script Host equivalent
ph_and | ph.bitand
ph_not | ph.lognot
ph_or | ph.bitor
ph_xor | ph.bitxor
ph_debuginfo | Not available
ph_fromunixtime | Not available
ph_isnull | Not available
ph_n2b | Not available
ph_stacktrace | Not available
ph_tounixtime | Not available
ph_tracemsg | Not available
ph_traceoff | Not available
ph_traceon | Not available

The PowerHome formula functions ph_setglobal_a and ph_setglobal_s also have their equivalent in WSH as ph.setglobal_a and ph.setglobal_s. WSH also has some additional functions: ph.setglobal_d, ph.setglobal_dt, ph.setglobal_n and ph.setglobal_t.

The PowerHome formula functions ph.setvars_a and ph_setvars_s have WSH equivalents ph.setvars_a and ph.setvars_s. WSH also includes the functions ph.setvars_d, ph.setvars_dt, ph.setvars_n, and ph.setvars_t.

If you should encounter a "ph_" formula function that does not appear to be duplicated as a WSH "ph." function or doesnt work as intended, you can always embed the function in a formula string and execute it using the generic "ph.formula( )" function.


Changelog for PowerHome 2.1.5b

FAQ: Changelog for PowerHome 2.1.5c
Knowledge Notes

Here is the changelog for 2.1.5c:

Changed 1-wire controller to support an exponential moving average for 1-wire sensor values. The user can choose the number of samples from 1 to 99 by modifying the "Point" column in the Analog I/O screen. Sensors that normally use a value of 0 can now have a value from 101 to 199 with 101 being 1 sample (effectively the same as no averaging) and 199 being 99 samples. For a normal point value of 1 the averaging point values are 201 - 299. Normal point values of 2 have averaging values of 301 - 399. Changed 1-wire controller to support the "Raw to Calculated" formula column so that adjustments to the calculated value can be performed. This is useful in adding offsets to sensors that don't read properly.

Added bounds checking for the f_char function so that a critical error is prevented. When an out of range parameter is passed, an automessage will now appear along with an entry in the eventlog. The result of the out of bound function will return a 0.

Rewrote the Global Cache socket disconnect detection code and automatic reconnect routines. Also fixed an error that could cause the Global Cache to hang requiring a disconnect/reconnect when an unknown command was sent.

Rewrote the macro messagebox and inputbox routines so that blank parameters will no longer cause a hang or a messagebox that won't go away. Now an automessage error will appear when required parameters are blank.

Corrected a serious bug introduced in version 2.1.5b that prevented links from being created in the Insteon Explorer.

Modified webserver to reverse a change introduced in 2.1.5b that effected the viewport meta tag and how PowerHome webpages are displayed on iphone and android devices.

Corrected problem in PowerHome Explorer that prevented the window from staying maximized and always reverted to a windowed mode.

Added code to prevent a critical error that sometimes occurred in the ue_trayevent executing the OpenIcon function.

Corrected a problem in the PowerHome Remote Control Center application that would cause the system to crash when executed in the non-tab mode and global variables were updated. This also fixes the problem where the wrong data would sometimes be displayed in various global variable fields.

New Plugins:
None

New Functions:
None

Changed Functions:
None

Removed Functions:
None

PWRHOME.INI Changes:
None

Database Changes:
None

Here is the changelog for 2.1.5b:

Fixed major bug with PowerHome execution queue that resulted in random errors manifesting as queued
actions never being executed and disappearing, actions being executed multiple times when they were only submitted once, and actions being executed with the wrong parameters and variables (such as a formula trying to be executed as a macro). This fix should take care of all known execution queue problems.

Added new ini parameter priority under section [Device Status] allowing user to select the priority that device status actions are queued at.

Added new ini parameter priority under section [Control Center] allowing user to select the priority that control center actions are queue at.

Modified the Remove Device Status program to make use of the new Device Status priority setting.

Webserver processing modified to respect new control center and device status priorities. Also modified internal processing so there is a better chance that the change in status will be reflected when next page is loaded.

Modified webserver device status page to remove unnecessary form data for devices which are display only.

Modifed the webserver device status screen to allow for specifying the desired columns and order. Added new INI parameter DSCOLUMNS under the [WebServer] section to store this setting. The current allowed columns are numbered 1 thru 7 and are: Control, Status, Device Name, Location, Type, ID, Last Changed. The default is blank which is equivalent to 1,2,3,4,5,6,7

Added internal variables to webserver to track total requests, bad logins, trusted logins, etc. Also added the ability to programmatically enable and disable the webserver. Access these new variables and functions using the new ph_system function. See the help file for more details.

Added new DEVICECONTROL command to socketserver. Made this command use the new device status priority setting. Also modified the CCACTION command so that it uses the new control center button priority setting.

Added INI setting to store the status bar height for the PowerHome Multi-Editor.

Added code to prevent a critical error that could occur while using menu options in the PowerHome Multi-Editor.

Modified ph_webds function to allow for specifiying the device status columns and desired order for the web based Device Status screen.

Added new ini parameter reinitmethod under the [System] section allowing user to select the method used to reinitialize PowerHome. Setting parameter to 0 will use the current method where a portion of PowerHome stays active. Setting parameter to 1 will cause PowerHome to fully shutdown and then restart itself. The default is 1.

Modified PowerHome Status screen to allow for the hiding of titles and resize borders to maximize screen space. Modified some of the windows for a better fit. Also modified so that window size/position is saved automatically upon exiting. Minor changes to some screens.

Fixed bug in URLScraper plugin where a overflow runtime error 6 can occur with certain frequencies.

Created new URLScraper1 plugin that uses a raw socket vs an HTTP control in the URLScraper plugin. Solves obscure problems with certain websites that refuse to work with the HTTP control. URLScraper is still the preferred plugin to use since it supports SSL.

Added small mod to the load plugin routine to trim any leading/trailing spaces for the launch data string. If the launch data has an extraneous leading or trailing space then the plugin will not load properly and return -2.

Documented the SALOGDIR environment variable for the ph_backupdb function.

Modified w_msgbox window so that if oversized, it will fit on the screen and add a vertical scrollbar.

Fixed timeout issue associated with ph_getitcurl function.

Modified PowerHome Explorer macro detail window to allow for comments field to fit on screen. Currently, the formula field resizes to fill the screen pushing the comments field off to the right. The comments field size is not taken into account when doing a window resize. Also added a button to show/hide comments.

Modified PowerHome Explorer window title to reflect the actual screen type currently active. This has the benefit of being able to distinguish between multiple open Explorer windows under the open window list in the "Windows" menu option.

Rewrote the PowerHome Virtual serial port plugin to no longer be an activex exe. New version has gone back to being a standard OCX and previous issues have been fixed.

Corrected issue in Global Cache reconnect code. Critical error should no longer appear.

Added new Elk controller command to perform a full refresh of all Elk devices (also fires device change triggers as necessary if requested). New Elk controller command 1000. parm1 = 0 retrieves all. parm1 = 1 thru 7 retrieves individual sections. parm2 = 0 will fire triggers, parm2 > 0 will not fire triggers. See help file for more info.

Rewrote eventlog viewer to correct all known issues introduced with version 2.1.5. Viewer is still a multi-threaded viewer.

Completely rewrote Device Status screen update mechanism. This fixes an issue where the Device Status screen would require manually closing and reopening in order for changes made via Insteon group or group cleanup commands (and others) to appear. Changes now all appear in realtime.

Corrected reported errors concerning Timedevents. Rewrote the entire timedevents section. You can no longer create a timed event in the past (they will always have logic applied to bring them in the future). Also, when executing past due events, the past due event will ONLY be executed once and the reftime/starttime brought to the next logical event in the future.

Updated Insteon thermostat code to add support for the new extended insteon discrete get cool setpoint and get heat setpoint commands of the 2441 thermostat. Also added extended command support for older thermostats as well.

Added support for the 1-wire DS18B20 devices (family code 0x28) to the 1-wire controller.

Added the ability to have the formula builder popup window (the window that opens when double-clicking the formula field within macrodetail and other screens) resizeable. The current size will be stored when the window is closed and reopened at that size. The statusbar height is also saved and restored.

Added ability to Insteon Explorer Links screen so that non-standard Local Ramprates can be entered (0 thru 255) instead of just the dropdown values of 0 thru 31. Also added ability to enter a value in seconds and have it converted to the closest ramprate. To enter a value in seconds follow the value with a lowercase "s". Entering in "20s" would result in the value being changed to the closest ramprate to 20 seconds.

Added code to highlight when a critical error has occurred and that PowerHome must be restarted.

Added the x, y, height, and width info of a selected object to the Control Center design properties window.

Added Copy/Paste capability to the Control Center Objects screen in PowerHome Explorer (same mechanism as used for macro detail). Use control and shift click to highlight rows and then right click and choose desired action from popup menu.

New Plugins:
URLScraper1

New Functions:
ph_datetime,ph_system

Changed Functions:
ph_webds

Removed Functions:
ph_insteonprodlistimport

PWRHOME.INI Changes:
[WSH Editor]
statusheight=348

[WebServer]
DSCOLUMNS=

[System]
reinitmethod=1

[Device Status]
priority=1

[Control Center]
priority=1

[PowerHome Status]
titles=no

[FormulaEditor]
width=2377
height=1448
statusheight=348

Database Changes:
None

Here is the changelog for 2.1.5a:

Added code to automatically refresh a Control Center tab (if the Control Center is currently open) when changes are made to it via the CC Design screen or through the PowerHome Explorer.

Added routines to the Insteon controller to break out of the endless loop of trying to CREATE INITIAL I2CS LINK when it is failing. After 3 attempts, the device will be updated as if the initial link was created and will then be allowed to move on to the next step (SCAN I2CS LINKS).

Modified Insteon controller to properly update Insteon PLM controller groups in response to external actions (direct control, etc). Device Status screen will now auto update without having to close and reopen.

Updated Insteon PLC controller so that the PLC should now work with. Version 2.1.5 introduced a regression where the PLC was unable to be used.

Corrected critical error that would occur in PowerHome Explorer if the far left "child" button was double clicked.

Added message "No Options available for this device" to the Insteon options screen from the Devices tab in Insteon Explorer for devices that either don't have options or have not yet been implemented.

Modified the Set XY and Set HW popups in CC Design view so that if multiple objects are selected, the default of Overwrite or Add is set to Add. Default is still overwrite if a single object is selected. Removed control menu from these screens as closing the window could cause objects to disappear.

Modified the Set % popup in CC Design view so that when cancelling, the selected objects are no longer deleted.

Corrected issue in Devices tab of Insteon Explorer where the "Replace Address" column is unable to be used.

Fixed problem in both PowerHome Multi-editor and Formula builder where the dropdown for global variables was not showing.

PowerBuilder runtimes and PowerHome Executables have been upgraded to the latest version of PowerBuilder 12.5.2 build 5629.

Here is the changelog for 2.1.5.

NOTE: This changelog represents cumulative changes since version 2.1b.

Version 2.1.4 did not have a changelog, so changes in that version (that still exist in 2.1.5) will be listed here.

PowerHome code has been updated to the latest version of PowerBuilder libraries (version 12.5).

Database engine has been upgraded to SQL Anywhere 11 from Adaptive Server Anywhere 7.

New Insteon engine with full I2CS support. All previous Insteon bugs should be resolved. New Insteon tables hold all published Insteon device types and will be auto-added to the Insteon Types table during auto discovery. NOTE that some I2CS devices may be firewalled and not readily "discovered" by programatic methods. See discussion about this issue in "FAQs-Setting up Thermostats in PH 2.1.5" for more information on how to resolve this, should it be a problem.

I2CS Thermostats now fully supported. NOTE: PH Version 2.1.5 on, uses a significantly different approach to Thermostat support than previous PH Versions did. See Help File "FAQs-Setting up Thermostats in PH 2.1.5" for detailed information.

New Options window for Insteon devices. Allows for extended programming of various Insteon devices.

The Options window is accessed via the Options button in the Insteon Explorer Devices tab.

Options Window

Insteon KPL config has been updated to use the Insteon KPL configuration commands (instead of the old peek/poke memory locations). KPL tab has been removed from Insteon Explorer and added to the new Insteon Options window. Peek/Poke commands still available for legacy devices.

Added support for Insteon GarageHawk.

Changed most timing operations within PowerHome to a single background multi-threaded object. Should solve contention issues between multiple components.

All references to MSCOMM32 (Microsoft COMM control) have been removed. Serial port controls have all been replaced with COMM32 control. Allows COM ports 1 thur 255.

All references to MSWINSCK (Microsoft Winsock control) have been removed. All socket controls have been upgraded with Catalyst 8 controls.

All plugins have been brought up to current controls (serial/winsock) and current codebase (PowerBuilder plugins are 12.5). This should solve the problems people were having with the PH_CID plugin.

Eventlog and weblog tables have been moved to their own database (phlogs.db). No more corrupt databases due to the eventlog and weblog growing to very large sizes.

Eventlog report has been rewritten as a background thead with the option to cancel retrieval. No more hanging of PowerHome when retrieving very large logs. Start reviewing log immediately while retrieval continues in the background.

New log options. Resume Macro will fire when a macro is resumed from waiting. Verbose macro will cause the existing Macro and the new Resume Macro to also display in the Event Log the values of [LOCAL1] thru [LOCAL10] and [TEMP1] thru [TEMP10]. Now you'll be able to get a better idea of what is going on with your macros until the macro debugger is released.

These posting parameters are accessed in the PowerHome Explorer>Setup>Logs object.

LOGS-Posting

New Analog device types. Dedicated analog types for Insteon GarageHawk, IOLinc, EZRain/EZFlora, Insteon Responder Group (eliminates need for virtual Insteon devices), etc. Allows for complete control of these devices without having to do any scripting.

Thermostats table has been deprecated. Insteon and Elk Thermostats have their own individual device types (Temperature, Cool SetPoint, etc) in the Analog I/O table. While this is a substantial improvement, unfortunately it means that prior Thermostat coding in earlier versions of PH will have to be re-visited in order to obtain full benefits. See Help File "FAQs-Setting up Thermostats in PH 2.1.5" for detailed information.

Timed Events routine has been reworked to solve problem with disappearing timed events. Now using update instead of Delete/Insert during timed event processing.

New labeling system added. Add one or more user defined labels to devices, macros, triggers, etc. Filter by label in PowerHome Explorer and Device Status screen. Group devices, formulas, macros, etc. together logically.

New 1-wire controller type. Support 1-wire devices directly within PowerHome. This controller runs in a separate thread due to the overhead of 1-wire communications.

New generic parallel port controller type.

New CM15A controller type. Supports both PLC and RF capabilities of this device.

New Insteon SmartLinc/NetLinc/Hub controller type. Connect directly to Insteon IP capable PLM's without having to use a virtual serial port.

Virtual Serial Port plugin updated to use the latest version 7.2 of Eltima controls. Plugin rewritten to be an activex EXE (rather than OCX) for better reliability and stability.

Reworked execution queue to support priority and top items. See ph_postexequeue function.

Direct control and status of Controllers from the PowerHome UI. Under Help->About->Controllers, you'll be able to see the connect status of the controllers as well as change the status.

New options to select lines in a macro and delete, cut, copy, or paste them to other macros (or the current macro).

To use this feature CTRL-Click on any Macro line of code and the entire line will be selected. Additional CTRL-Clicks will select additional individual lines of code, while a Shift_Click will select all lines between the first and last Click.

Once your Selection is made, Right-Click the mouse anywhere in the Macro and a context menu will appear. Choose the "Selected" menu item and the desired action.

If you Cut/Copy, you can Paste it in this or another Macro. After you select a target row, you can then Paste and the clipboard content will be Inserted at that location. It inserts, not overwrites, so following lines will be moved down to make room.

New regular expression capability (available in functions ph_regex2, ph_regexdiff2, and ph_regexsnap2). This regular expression syntax is the same as VB and offers many more options than the regex functionality in Scintilla. Reference this website for very detailed documentation concerning this syntax: http://www.regular-expressions.info/vb.html

Webserver and Socket Server rewritten to eliminate contention errors.

Webserver has additional security options (cookie) and now supports SSL.

SMTP email functions have all been rewritten to use Catalyst SMTP control vs a raw socket. Improved stability and performance. New ph_sendsmtpemailasync function allows you send email asynchronously rather than holding up PowerHome execution waiting for the email function to return.

Numerous bugfixes, critical error fixes, and tweaks throughout. Too many to list. Since alot of the base code is completely new, please re-report any bugs or critical errors as they occur.

New Plugins:
Virtual Serial Port, Roku, Directory Monitor, Windows Lock Monitor, AVTech DVR control, Windows Monitor, Growl Control, ODBC Database Control, Windows Power Monitor, URL Scraper

New Functions:
d2h, h2d, h2s, ph_base64decode1, ph_convertir, ph_ctlrcontrol, ph_decrypt, ph_deletetimedevent, ph_encrypt, ph_fill, ph_formulabtnparm, ph_funcdef, ph_funclist, ph_getdevicestat, ph_getdeviceval, ph_getlasterrorstring, ph_getmd5hash, ph_getmd5hash1, ph_getmtret, ph_getothercounter, ph_getsyspwrstat, ph_gettstat, ph_gettstat_s, ph_geturl1, ph_geturlviaproxy1, ph_getvarsub, ph_htmlescape1, ph_insteonprodlistimport, ph_insteonrawext, ph_insteonwithret1, ph_insteonwithretext, ph_insteonwithretext1, ph_isssrunning, ph_iswslocked, ph_latlongdist, ph_locatehandle1, ph_lockworkstation, ph_minutestostring, ph_not, ph_number, ph_pad, ph_ping1, ph_postexequeue, ph_posturl1, ph_posturlviaproxy1, ph_random, ph_regex2, ph_regexdiff2, ph_regexsnap2, ph_retrievevars, ph_runasuser1, ph_runsync1, ph_saveurl1, ph_saveurlviaproxy1, ph_sendsmtpemailasync, ph_sendsmtpemailfileasync, ph_setdeviceval, ph_setothercounter, ph_settemps, ph_settstat, ph_shutdown, ph_snapxml, ph_split, ph_storevars, ph_sumnum, ph_timedeventsinfo, ph_trim, ph_urlescape, ph_varsub, ph_x10other, s2h

Changed Functions:
ph_devicebtn, ph_getdigitalstat, ph_getinsteonctrl, ph_getinteonstat, ph_getvar_d, ph_getvar_dt, ph_getvar_n, ph_getvar_s, ph_getvar_t, ph_insteonctrl, ph_modifytimedevent, ph_rtne, ph_runasuser, ph_sendsocketdata1, ph_setanalogout, ph_webaddblob, ph_webds


Changelog for PowerHome 2.1.5a

FAQ: PH Home Screen - Concepts & Facilities
Knowledge Notes

The PowerHome Home Screen is the focal point of almost all PH activities.

Understanding well its various features, icons, and capabilities will make using PH a lot easier to use, and your efforts more productive.

This tutorial will examine the many features of this Home Screen. There is no "standard" Home Screen configuration, as what appears there is totally customizable to suit the User's choices. The example shown below is a common configuration, as it shows many of the critical actions occuring in real-time.

PH Home Screen

NOTE: When you start PowerHome, or Initialize it, the PH window opens as a blank "clean slate". To cause the window to be populated with your favorite sub-windows (as above, for example), you can insert the following sample Macro Code in your Initialize Macro, that is triggered by a PH Start or Init...

Window Initialization Macro

The code in line 20 forces Windows to bring the PowerHome window to the foreground and give it focus, while the code in line 30 opens (respectively) the PowerHome Explorer, Insteon Explorer, Device Status windows.

The list of PH windows that can be opened includes...

  • 1 - Control Center
  • 2 - Device Status
  • 3 - Web Center
  • 4 - PowerHome Explorer
  • 5 - Insteon Explorer
  • 6 - PowerHome Status
  • 7 - Palm Pad
  • 8 - Eventlog
  • 9 - Multi-Editor
The above Macro Code will cause the designated windows to be open in the same position & size as they were when PH was last shutdown.

TOOL BAR ICONS

First, let's look at each of the Tool Bar icons, to understand what they do.

Each number labeled Toolbar icon will be examined, in the following dialog. ToolBar icons

  1. The "Initialize" icon [ [image]] causes PH to be re-initialized. This is essentially a re-start, except that the PH "Triggers" treat a Restart differently from an Initialize. If you want to take the same, or different, actions upon either event then you need to define two Trigger events in the "Trigger ID" field.
    Init Triggers

  2. The "Connect" icon [ [image]] causes PH to connect to the PLC/PLM controller. NOTE: When a connection is "Active" the icon is highlighted.

  3. The "PH Explorer" icon [ [image]] opens the window that allows you to select what detailed area of PH you wish to explore.
    PH Explorer Window

    To open a different database (for instance to look at one of the sample db's included with PH, or to look back at one of your earlier db's to see what how an older configuration was set up, click on the PH Explorer (3) icon. This will add the db Tools below the Top Toolbar.
    db Access

  4. Icon 4 is the Multi-Edit icon ( [image]) that opens up the Editor Window for all of the editable items associated with PH. The red boxed list shows the various target editors available. Pick the appropriate editor to properly configure the editor's functions to fit the target application...
    Multi Edit `

  5. Icon number 5 icon ( [image]) opens the Insteon Explorer window, which dynamically shows ongoing operations..
    Insteon Explorer

  6. The 6th icon ( [image]) Opens the "Wizard" that helps you set up many basic functions. This is a powerful tool to help you get started, if you are a new user. Other than initial setup configurations, this icon will seldom be used.

    WIzard

  7. Icon 7 ( [image]), opens the Control Center, which is a specialized area of PH that allows you to create your own custom control access to virtually all of the PH features and devices.
    Control Center

    See this Tutorial, for an introduction to designing your own custom Control Center page... Control Center Tutorial

  8. Icon number 8 ( Home Control), opens the Device status window. This window shows the real-time status of all "Displayed" devices and allows real-time control of those devices so they can be turned on/off or set to desired light levels.
    Device Status

    If you do not want to display a particular device in the Status window, then in the Insteon Explorer>Devices tab, check the "Do Not Display" parameter.
    DvcStatus Display

    Typically, one would not want to display Remote Switches linked to a Master (such as at both ends of a hallway), or the PLM or IRLink devices. Checking "Dont Display" will prevent the Device from appearing in the Device Status window.

    If you have devices appearing in the Device Status Window, but that can't be controlled, (such as a door open/closed state) then check the "No Control" parameter in the Insteon Explorer>Types tab. This will make the Device Status window eliminate the option to turn the device on/off/etc (red box). Only the Status of the device will be shown.
    Device Status Control Device No Control

  9. The 9th icon opens the ( Palm Pad) Palm Pad window. This screen appears similar to a standard X-10 palm pad and is useful for quickly testing your X-10 control with a minimal of setup.

    You can select the controller from which you want to send as well as the house code.
    Palm Pad Window

  10. Icon 10 opens the ( PH Stat) PowerHome Status window. This presents a real-time view into what is going on with PH, and is very handy to have shown. This window displays three sub-frames, as follows. . .
    PowerHome Status

    The Top Frame "System Status" displays the PowerHome and Windows OS continuous running time ("Up Times" ) since last restart/reset.

    This Frame also displays what the next Timed Event will be. Handy if you are wondering when an event will happen so you can see actions occurring in the Event Log (bottom Frame).

    NOTE: When you toggle OFF the Timed Events (icon 12) there will be nothing shown under the "Upcoming Timed Events:" label in the System Status frame. When this icon is enabled there will be an upcoming event listed (unless there are absolutely no timed events that are defined).

    The bottom Frame is a real-time snapshot of the last few Event Log entries. It gives you some idea of what is happening, but to get full details, you need to open the actual Event Log (icon 13).

  11. Icon 11 launch's the ( Web Center) Web Center page, which is any ANY web page (it doesn't have to be from the PH webserver) and can be set to a users other server, a PSP page, ASP, etc.

    The location of this web page is determined by the Web Center parameter in the "pwrhome.ini" file. That parameter is defaulted to http://127.0.0.1 but can be set to any valid IP address.
    [Web Center]
    home=http://127.0.0.1/

  12. Timed Events ( Timed Events) can be enabled/disabled with icon 12. This is very useful when debugging in PH, as it stops "clutter" in the Insteon Raw Log and the Event Log Windows so you can more readily find the Insteon traffic you are trying to trace. The icon is a toggle that has a highlighted background when Timed Events are turned on. Sometimes the icon is slow to change its appearance in real time, but you can readly tell if Events are enabled, or not, by looking at the System Status frame in the PowerHome Status window. If Timed Events are turned OFF, the there will be no entry below the Upcoming Timed Events: label. It will be blank as shown below...
    Timed Events window

  13. The Event Log ( Event Log) button is icon 13. Clicking on this icon will open up the Event history window showing chronological actions taken over whatever length of time the Log Size is set at.
    Event Log

    Since so much information is logged, the Event Log and the database can grow to enormous proportions if the log is not periodically trimmed. You have full control when the Event Log is trimmed and how many days worth of information you want to maintain. The Event Log is trimmed using the macro command "Trim Event Log" or the formula function ph_trimeventlog. This command allows you to empty the log except for the last X days.

    You can set X to any value you want, but would probably be satisfied with 2. You

    To trim automatically, create a Timed Event (saw at 2:00am) that executes "ph_trimeventlog(2)" That will trim the Log to two days of entries. A "7" would trim to a week, etc.

  14. Icons 14-18 ( Auto Arrange) provide Auto Arrangements of all windows you have open and showing in the PowerHome window. These icons arrange the windows as Tiled side-by-side, Tiled Vertically, Tiled in Layers, and The last icon allows you to arrange the windows as you choose.

    If you like PH to start-up with certain windows showing, you can create a Trigger action to automatically open your preferred windows on re-initialization or startup. The following triggers call an Initialization macro on both re-init and startup (but different macros could be called if desired)...
    Init Triggers

    As described at the beginning of this document, you can run an Initialization Macro, using code similar to the following to bring PH to the foreground for control, then open your windows. In this example the PowerHome Explorer, PowerHome Status, and Device Status windows are opened. They will be opened with the same size/position settings they had when last visible.
    Open Windows Code

    The parameter in the ph_openphwin() function is an integer from 1 to 9 that designates the type of PowerHome window to open.

    1 - Control Center, 2 - Device Status, 3 - Web Center, 4 - PowerHome Explorer, 5 - Insteon Explorer, 6 - PowerHome Status, 7 - Palmpad, 8 - Eventlog, 9 - Multi-Editor

  15. The "Question Mark" ( Help) icon Opens up the PowerHome Help window.

  16. The rightmost icon ( Exit) is "Exit" which is the same as clicking on the red "X" on the top right of the PH window, and causes PH to terminate and close down.


DateTime data

FAQ: DateTime data
Knowledge Notes
Date/Time variables are stored internally as a string.

See also the Date / Time Functions section for detailed information concerning date / time input-output formats.

The ph_getvar_XX functions will take these strings and perform the proper data conversion (if possible). This is generally safer and goes a long way into insuring you don't get syntax errors from data types that dont match. The [LOCALXX] form of a variable is a "search and replace" type of mechanism. If you're certain that the var contains the datatype that you're interested in, you can use this form.

Some examples to help make things clear...
if [LOCAL1] contains 5 then...
[LOCAL1] + 8 >> Returns a number type that equals 13
[LOCAL1] + " is a number." >> Returns a syntax error because the formula actually passed to the evaluator will look like: 5 + " is a number."
"[LOCAL1]" + " is a number." >> Returns a string that looks like: 5 is a number.
"[LOCAL1] is a number." >> Also works and is the equivalent of the formula just above.

Using this background, if the [LOCAL3] var contains a saved datetime value in the form of 12/15/2010 10:49:00 it will fail in this formula: ph_minutesafter([LOCAL3],today())

But...it will suceed if the saved datetime value in [LOCAL3] looks like: 2010-12-15 10:49:00, or the formula was changed to ph_minutesafter(ph_getvar_dt(1,3),today())

To create a negative time value (before an event) use this form . . . "ph_relativetime ( 00:00:00,[SUNRISE]-15*60)" which would be 15 minutes before SUNRISE.

You can specify a literal date, time, or datetime by using the format of "yyyy-mm-dd hh:mm:ss.ttt" That is with dashes, not slashes between date items and no comma between the date and time.

[NOTE: the date is year-month-day ordered.]

For example the formula...

ph_relativedatetime(2013-12-01 13:38:15.306,90)

Will give you back a datetime that is 90 minutes later than the entered datetime... almost. The milliseconds portion will always be 0, as the ph_relativedatetime function truncates time to seconds. If you want millisecond precision, you must use the ph_relativedtprecise function.

If you are wondering why the function today() returns its output in mm/dd/yyyy hh:mm:ss format rather than the literal datetime input, it is due to Windows formatting of datetime values which are controlled by regional settings. So input is always yyyy-mm-dd hh:mm:ss.fff and output can vary (usually mm/dd/yyyy hh:mm:ss in the United States) based upon Windows regional settings.

To better understand how to create formulas with Date/Time & System values the following chart demonstrates how various functions resolve their output values...

Formula | Result
ph_secondsafter(06:30:00, 06:32:00) | 120
[SUNRISE] | 22869
ph_relativetime(00:00:00,[SUNRISE]) | 06:25:26
ph_relativetime(00:00:00,[SUNRISE]-60) | 06:24:26
ph_relativetime(00:01:00,[SUNRISE]) | 06:26:26
ph_relativetime(02:00:00,90) | 02:01:30
Now() | 14:57:22:463
ph_relativetime(now(),30) | 14:57:52
Today() | 12/01/2013 14:57:22
ph_relativedatetime(today(),30) | 12/01/2013 14:57:52
ph_relativedatetime(datetime("09/23/13 12:00:00"),30) | 09/23/2013 12:30:00
ph_relativedatetime(2013-09-23 12:00:00,30) | 09/23/2013 12:30:00
datetime("09-23-13 08:15:00") | 09/23/2013 08:15:00
time("06:30:00") | 06:30:00
Now()>07:00:00 | True if after 7AM
datetime(today(),08:00:00) | 12/01/2013 08:00:00


Timed Events and Formulas

FAQ: Timed Events & Formulas
Knowledge Notes
One of the most useful functions of PH is its ability to schedule Timed Events in the future on a one-shot, or repeating basis.

The Timed Event control window is accessed via PH Explorer, and offers a wide range of control choices.

Timed Event Window

To set up a Timed Event right-click on any row and select "Insert" from the pop-up menu. This will create a new row, where you clicked, so you can enter a new event. The rows are sorted by the ID column. If you wish to update the window and have it sorted after you have made entry(s), press F5 on your keyboard.

Start by entering a descriptive name for your event in the ID column.

NOTE: The Disabled column lets you enable or disable a timed event. If Disabled the Event Scheduling will be ignored by PH.

The Start Time column cells are grayed out because they are not user accecssible, but are the sytem calculated datetime value representing the actual scheduled event time based on the user entered Reference Time/Offset/Offset Amount data values.

Select a fixed or dynamic Timing property depending on whether the event is to be scheduled to occur at a specific time or at a varying time related to day/night cycles. NOTE: if the later, in order for sunrise/sunset calculations to be correct, your geographic location MUST be setup in the PH Explorer>Setup>Sun window.

Timing

Next set the Frequency the event should occur. The frequency can be directly specified in (integer) Minutes (eg, 10) or in a variety of predefined time periods such as Hourly, Daily, Weekly, etc.

The Frequency pull-down menu can be used to select one of an extensive number of these predefined periods, including special days like "4th of July".

The last part of this FAQ document describes how to create your own custom special periods, such as "Every Other Tuesday" using Timed Event Formulas.

Event Frequency

The specified Frequency can have an Offset associated with it to create a "lived in" appearance for lighting ( the Random attributes to keep perps at bay) or Absolute offsets (eg, to schedule something for 20 minutes after sunrise). Most often the default "None" choice will be used.

Offset

If an Offset (other than None) is selected, then a value in (integer) minutes must also be specified in the Offset Amnt column.

If you select "Exact" in the Timing column then you must enter a datetime in the Reference Time column. You can enter a datetime value directly in the Reference Time cell or you can double-click the cell which will open up a dialog window where you can pick a calendar date and edit the time values.

You can skip this step if your Timing column entry is one of the dynamic time choices, since the Reference Time will be automatically determined, and will vary every day.

Reference Time

After setting up the datetime parameters, you now specify how you want to take action(s) at the scheduled time. You can choose from four different Types of action as exampled below.

Event Type

Finally NOTE that the Boolean field (as in many other PH configuration Windows) can be used to selectively enable/disable the Timed Event. The example Boolean entry here only allows the Timed Even to occur if the Global value of HOME is true. If HOME is not true, then the Timed Event will be skipped.

TE Boolean

Timed Event Formulas

The following dialog explains how to creatre your own Timed Event Formulas, that will allow you to design your own custom event schedules, such as scheduling an alert every other Tuesday.

The Timed Event Formulas can be tricky, but aren't too bad once you get used to it. It helps to know how it works internally though.

A Timed Event formula MUST evaluate to a datetime type. This is a MUST. Other than that, it's just a formula and the functions under the Date/Time section of the Help file are extremely useful.

Timed Event Formulas have two special variables that come into play.

The first one is [REFTIME]. [REFTIME] is substituted for the datetime value in the "Reference Time" column of a timed event. When you are creating a brand new Timed Event, the "Reference Time" field defaults to the current date and time. If it's an existing Timed Event that has just fired and the Timed Event formula is being evaluated to determine the next reference time, it is the date and time in the reference field which is the datetime that the Timed Event was just executed at.

In a normal Timed Event with a "Daily" frequency, the reference time will be increased by 10080 which will be a full day forward. When that Timed Event is fired, all things being normal, the reference time will be current date and time. The frequency will then be "added" to the reference time to determine the new reference time. If the Frequency is a Timed Event Formula, the formula will be evaluated to determine the new reference time.

Which brings us to our second special variable.

The [INCREMENT] variable. [INCREMENT] initially starts as a value of 0 and the Timed Event formula is evaluated. If the datetime returned is less than the current datetime, 1 is added to [INCREMENT] and the Timed Event formula is evaluated again. This continues until the returned datetime is greater than the current datetime and this value becomes the new "Reference Time". So the [INCREMENT] is just a number that can be used anywhere within the Timed Event formula and increases by 1 until the formula returns a datetime in the future. You can use this [INCREMENT] value to increment the year, the day, an hour, etc.

So, if we were to create a custom Timed Event Formula to schedule an "Every Other Tuesday at 6:30AM" occurance, it would go like this:

datetime(relativedate([REFTIME],[INCREMENT] * 14 + 3 - daynumber([REFTIME]) - if(daynumber([REFTIME]) > 3,0,7)),time([REFTIME]))

[REFTIME] is substituted for whatever value is currently in the Reference Time. If this a brand new Timed Event, it will be the current date and time.

If the Timed Event has already been working, it should be the Date and Time that the Timed Event has fired which should be Tuesday.

Since [REFTIME] is the "Reference Time" value which is actually a date AND a time, we should extract out the invidual date and time components using the date() and time() functions respectively.

The relativedate function accepts a date and an offset amount in days to determine a new date.

The daynumber function accepts a date and tells you what number of the day in the week that date falls on. Sunday is 1, Monday is 2, and so on to Saturday, which is 7.

Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7

If you are creating the Timed Event for the first time, the reference time will the current date and time which may be either before Tuesday of the current week or after Tuesday of the current week. Since it makes no sense to create a Timed Event in the past, the formula is designed to set the Reference Time to whatever the next Tuesday is.

So, lets walk our way through it for the case where the example formula is assumed to be created on Sunday 01/18/2015.

Tuesdays are the 3rd day of the week (thus the "3" occuring in the Timed Event Formula example above).

We're creating the Timed Event for the first time, so [INCREMENT] will start out as 0.

Substituting 0 for [INCREMENT], we have 0 * 14 + 3 --> 3

Substituting 1 for daynumber(2015-01-18) (where 2015-01-18 is the formula creation time [REFTIME]) we have --> 1

The next part of the equation contains an if statement which looks like: if(daynumber(date([REFTIME])) > 3,7,0).

This is basically trying to determine if we're evaluating this formula on a day before or on Tuesday (Sun, Mon, Tue) or a day after Tuesday (Wed, Thurs, Fri, Sat).

If the daynumber of [REFTIME] (2015-01-18 in our case or 1) is greater than 4, then return 7 else return 0. Since 1 is less than 4, we have --> 0.

So our formula is now 3 - 1 - 0 which equals 2.

Thus our relativedate function will take the Sunday initial date (2015-01-18) and add 2 which will give us a date of 2015-01-20 (Tuesday).

We take that date as well as the time component of the [REFTIME] and create a datetime value for 2015-01-20.

Now, lets say the Timed Event is running as normal, it's Tuesday and the Timed Event has just executed.

We now need to evaluate the formula to determine the new Reference Time for when the Timed Event will run again.

Lets say the date is 2015-01-20 (Tuesday). Lets also say the [REFTIME] time component was 13:00:00. [INCREMENT] of course starts at 0.

So we have 0 * 14 + 3 - 3 (for this part of the formula: [INCREMENT] * 14 + 4 - daynumber(date([REFTIME]))). This equates to 0.

The if statement also equates to 0 since the daynumber of the current reftime is 3 and 3 is not greater than 4.

So our offset amount for the relativedate function is 0 and the date portion is today.

So the relativedate function will return 2015-01-20 and the time component of reftime is 13:00:00.

Thus the total datetime value returned is 2015-01-20 13:00:00.

This is compared to the current date/time. Since all Timed Events are actually executed 1 second after their scheduled time (this is by design), this returned time will automatically be less than the current time (the soonest of which would be 2015-01-20 13:00:01).

Now 1 is added to the [INCREMENT] variable, resulting in a value of 1 and we repeat the formula.

[INCREMENT] * 14 + 3 - daynumber(date([REFTIME]))

which substitutes out to: 1 * 14 + 3 - 3 which equals 14. The if statement still evaluates to 0. The result of the relativedate function will therefore be 14 days in the future (2 weeks) from the current date which will be Tuesday, 2015-02-03.

This is combined with the time component of reftime which is 13:00:00 yielding a new datetime of 2015-02-03 13:00:00. This is compared with the current date/time and since it's in the future, evaluation stops and the new reference time is set.


KPL Care & Feeding / Linking / Button & Ctrl Groups

FAQ: KPL Care & Feeding / Linking / Button & Ctrl Groups
Knowledge Notes

KPL Keypads come in 6 and 8 button configurations.

By changing the faceplate on the KPL, the button config can be modified as desired, and the PH Insteon Explorer>KPL Config Tab can be used to modify the KPL's Properties to match. Newer models of the KPLs are now ordered and configured for specific usage.

The button numbering on a KPL is easily confusing, but the following diagram should clear things up...
KPL Button Labeling

All keypads have 8 switches numbered from 1-8. The 6-button keypad just has wide buttons on the top/bottom rows that simultaneously activate the 1-2 (top) and 7-8 (bottom) switches when pressed.

NOTE: a 6-button keypad uses the top and bottom button pairs to create an On/Off switch function. ALL of these 4 combined buttons (1,2,7,8) are referred to collectively as button "1" and are associated directly with the KPL device ID just as a normal Insteon wall switch's top/bottom switch presses are linked to the "0" button to control the device.

Controlling KPL Associated Device
Insteon "on/off" commands for the KPL's attached device are just sent to either the 6 or 8 button KPL, as a normal wall switch would be treated, eg, ph_insteon("MID CHANDELIER",ifaston,0). By defining the 6-button keypad, this way it allows control to always be the same for both types of KPLs. Associated device control is always to "1" and the remaining buttons control their respective linked devices.

Via PowerHome, or Insteon manual controller/responder direct linking the non-button1 keys can be used to control other devices, or the individual key lights can be used merely to show "status" of other devices (eg, garage door open).

Controlling KPL Button Lights
Buttons on a KPL are controlled with Insteon Group, or Group Cleanup commands. (eg, ph_insteongroup; ph_insteongroupcu).

First Define a PLM Group to assign an ID to the PLM Controller link which can be used in Macro commands. Define a Macro which turns the KPL button ON or OFF. As illustrated below, eight buttons have been assigned individual Group Numbers. These may be used with any KPL, as the PH control functions specify both the Device ID as well as a button number.

PLC/PLM Groups

To control a KPL button, links must be created in the Insteon Explorer>Links tab just as any controller/responder link would be set up between any two linked Insteon devices.

For example, using the above Group ID's to light button 4 on a KPL keypad in the bedroom to indicate the garage door was open,the following would do it...

ph_insteongroupcu("KPL-B4","BEDROOM_KPL",ifaston)

If there were multiple KPLs, all with the Garage Door Open status indicated on button-4 then instead of the specific KPL control offered by ph_insteongroupcu(), the broader ph_insteongroup() function could be used. This will light button-4 on all KPLs that have their button four assigned to "KPL-B4" (in point-of-fact such specific usage would be better done with a specific group name like "GDR_STATUS" assigned to its own unique Group Number such as "204". This also offers the advantage that the Status light could then be on any KPL button that was linked to that Group ID. {See more on linking below})

For example...

ph_insteongroup("GDR_STATUS","ifaston",0)

Creating Controller/Responder Links
In the example below, links have been created in the "MID PORCH KPL" with the PLM as the Controller and various other switches and KPLs as Responders. In the Controllers frame, the Group 104 entry allows button-4 on the porch KPL to be controlled by PH functions (eg, ph_insteongroupcu("KPL-B4","MID PORCH KPL ",ifaston) while the link for Group 4 (which is button-4 on this KPL) controls the OUT YARD light.

Understanding KPL Groups
When linking KPLs to each other the Group and Button meanings are as follows: For Controllers the "Group" number will be the button number on the sending KPL and the "Button" number will be the affected button on the receiving KPL.

For Responders the "Group" # will be the button# on this selected KPL and the "Button"' # will be the button on the responding Device(0) or KPL(#). In most cases the Button# will just be "0" for all controllers and responders except KPLs..

KPL Groups

With the release of PH version 2.1.5, the management of KPL setups has been moved to the Insteon Explorer>Devices tab.

To open the KPL configuration window, click on the Options button next to the KPL Device. This will open the Insteon Options Window. Here you can configure the KPL to be a 6 or 8 button device; set the On Level and Ramp Rate for the Button 1 (master KPL device); and also allow you to set KPL Buttons in Toggle/On-Off mode; and control the button back-lighting actions. ...
KPL Config

To set a KPL Button to be a Toggle/On/Off button with every press, use the Explorer>PLC/PLM Groups>Control window to turn the desired KPL buttons on/off.
KPL Button Control

Set the buttons you wish to set as non-toggle ON to be "On" and the buttons you wish to set as non-toggle OFF to be "Off." Save changes.

Then using the Explorer>Devices>Options button, (per 2nd image above) set the appropriate buttons from toggle to either non-toggle on or non-toggle off. It doesn't matter (other than the button is not set to be toggle) as the button will be set as non-toggle on or non-toggle off based upon the current status of the button's lights. Press Save/Refresh.

Then in order for the KPL to "see" the changes, it must be power cycled to set the changes into ROM. To do this, pull the KPL Air Gap tab out for 10 seconds, then push it back onto the ON position, or turn the circuit breaker/fuse off/on for the circuit.

What the LED On and LED Off checkboxes control is the status of the other KPL buttons when the button in which the checkboxes reside is controlled.

For instance, take "Button 1" . If you placed a check in LED On for 3 and a check in LED Off for 5, then when you manually control button 1, button 3 will be lit and button 5 will be off. It usually used to make mutually exclusive buttons for a scene. Say button 3 is scene full on, button 4 is scene 75% on, button 5 is scene 50%, and button 6 is scene 25%. In this case, if you press button 4 (scene 75%), you would want the other 3 buttons (3,5,6) to turn off.


Local/Temp/Global Variables

FAQ: LOCAL/TEMP/GLOBAL VARS
Knowledge Notes
There are a total of 120 special system variables. 10 of these only have scope within the macro, PSP, or formula from which they were called.

These system variables are [LOCAL1] through [LOCAL10]. These system variables can be used as temporary variables to store characters or numbers. This will save you from using global variables as temporary storage and incurring the database read and write.

Another 10 special system variables are [TEMP1] through [TEMP10].

These variables serve two purposes...

The first is that they can be referenced and set from within macros, PSP, or formulas. When a macro or formula calls another macro or formula, any values within these system variables are passed continuously down through subsequent calls. These are not global in the sense that the values are the same for all macros, PSP, and formulas. For example, if a timed event launches a macro called TEST1, this macro may set the [TEMP1] through [TEMP10] variables to certain values. If this TEST1 macro calls another macro called TEST2, then the TEST2 macro will be able to reference the values that the TEST1 macro placed in the [TEMP1] through [TEMP10] system variables. TEST2 can in turn call a Send Keys formula that can also reference the values in the variables. When the original macro TEST1 completes, the values in the [TEMP1] through [TEMP10] variables are lost.

The second use of these variables is to pass parameters from triggers and voice commands. When certain triggers and / or voice commands are processed, some of the [TEMP1] through [TEMP10] system variables will be prepopulated with relevant information that the resulting macro or Send Keys formula can reference. These pre-populated values will be detailed in their relevant sections.

The last 100 special variables are [GLOBAL1] through [GLOBAL100]. These variables are truly global and can be seen from within any formula or macro. They are not stored in the database however and will be lost when PowerHome is shut down.


Macros Quick Start Guide

FAQ: Macros Quick Start Guide
Knowledge Notes

Unlike many other "Home Automation" software offerings, PowerHome is unique in the breadth and richness of the control that can be achieved by program means. The level of automation you achieve is virtually limitied only by your imagination and willingness to design and create "macros" to perform your task.

A "macro," which is just a sequence of steps to be processed to achieve a goal, is just another name for a "program."

While encountering PowerHome Macros for the first time may seen daunting, they are actually easier to use than most programming languages. If you are familar with Visual Basic, Java, C, etc then you will have little problem in creating PowerHome macros, as the same concepts of arithmetic/logic/branching/testing are used.

Macros are constructed in the PH Explorer > Macros window.

PH Explorer is launched via the "Magnifying Glass" icon (red circled) in the Tool Bar or via Menue>Maintenance>PowerHome Explorer.

When you click on the radio button to the left of the "Macros" item (red oval circled group), it will open up a window showing a table of your entire macro collection.

Whether that collection is empty or full, you add a new macro by right-clicking on a macro table button, or line and selecting "Insert"

This will create a new line where you can name and describe the macro function.

Let's create a macro that will turn off the lights in the room and turn on your bed electric blanket if it is winter. We will call the macro "ROOM OFF"

This macro will be called by a Trigger event that senses when you do a double-tap of the Off room ceiling light. (This, and Timed Events, is a common method of causing macros to run when appropriate)

Our macro will look like this. An explaination follows ...

ROOM OFF Macro

Seq #10/20 send Insteon commands to the sofa and chandlier to turn Off.
Seq #30 is a Jump that tests for the month on this date and either executes the next line to turn on the electric blanket (if the month is 11,12,1,2,3) or go down two lines and exit.

In place of the Jump at Seq #30, a "GoTo Label" could have been used instead. The Jump is an easy approach, but if the jump is more than a few lines, it is easy to have subsequent code problems if you change the jumped over code and forget to change the Jump values. The "GoTo Label" allows you to define Labels in your macro and jump to them by name. NOTE: that if a GoTo "Label" is undefined, then the goto just goes to the next line of code. This is actually a handly shortcut, as it allows you to make a Branch command construction like ...

"if({HOME},"nextLINE","AWAY")"

This will just go to the next line of code (assuming there is no "nextLINE" label defined (or any string you choose to use here)) if you are HOME , and branch to the label "AWAY" otherwise.

The Trigger to sense this event would look like this ...

The ID field is just a friendly name for you to remember what this is for. While the Trigger can create many possible actions from direct Insteon Device control to formulas to calling macros, the Macro action is one of the most common Action Types as it offers extreme flexibility. The Action field, for Action Type "Macro", is the name of the macro. Double tapping the Living Room Ceiling light switch will cause an Insteon Group Out command to be sent advising everything that a Fast Off has just been done. This "out" transmission from the switch is an "in" message to PowerHome, and thus we use the "Insteon Group in" Trigger Type. See also "FAQs-Triggering from Device Changes"

NOTE: The Boolean field in the Triggers table defaults to "1" but you can instead create formulas to return a "0" or "1" into the Boolean field. For instance, an "IF" statement here can filter trigger actions. That is, we could only trigger the ROOM OFF action, if it was later than 8:00 PM in the evening by putting the following in the Boolean field.

This will "filter" the trigger so that if, and only if, the time is between 8:00PM and midnight, that it will "fire."


Setting up Insteon Thermostats

FAQ: New Thermostat Setup Procedure
Knowledge Notes

With the release of PowerHome 2.1.5, an entirely new support system for Insteon Thermostats has been implemented.

While this is a substantial benefit, it unfortunately means that old (pre 2.1.5) PowerHome configurations will no longer work.

This tutorial documents the process for migrating, or creating new, thermostat configurations.

If you are creating a NEW thermostat installation, then the first thing to do is to Find your STAT device in the Insteon Explorer "Types" Tab and Modify the Ctlr Groups entry for all Insteon stats you will be using. The default value is usually "1". Change this to "254"

Stat Type Setup

Now Open the Devices Tab. If you are upgrading from an earlier version of PH then you may skip this step, as your devices are already entered in the database. Configure all of your STAT devices as exampled below.

Stat Devices Setup

Enter an ID and Description (Usually the same. The ID is used in Formulas to identify the device, and the Description is what appears in the Device Status window. (Most users find it most usefull to just make the two fields the same.)

Enter the STAT Insteon Address, the Location, and the "Device Type." Because you are setting up the thermostat as an Analog device, you will also want to check the Don't Display attribute to prevent having this Insteon device appear as a duplicate in the Analog Device entries in the Device Status window. If you are not sure what the Device Type is, then select the * Auto Discovery * parameter in the Device Type cell and then click on the "Save/Refresh" button. Once the auto discovery process completes successfully, click on the Save/Refresh button again to refresh the window. The correct Device Type should then be displayed.

After clicking on the Save/Refrresh button, look at the Pending and Completed Operations windows in Insteon Explorer. If the Save/Refresh operation does not complete succecssfully you will see something as shown below where the "CREATE I2CS INITIAL:" operation keeps trying and trying without success. You will see red entries in the Insteon Raw Log window (red arrows) indicating NAK responses from the device, because a connection cannot be made. This occurs because some I2CS Insteon devices contain firewalls to protect against program modification.

If your Save/Refresh operation went successfully, then you should see in the Completed Operations window a single CREATE I2CS INITIAL entrty with several CREATE CTLR LINK entries above it (one for each Controller Group you defined.

If you encounter blocked access to your I2CS device, then the following proceedure must be used to get around the I2CS device firewall protection.

Go to the Devices Tab and change the IEngine entry for the I2CS device from I2CS to I2. Do a Save/Refresh. This should allow the CREATE CTLR LINK operations to successfully run. Once they do, change the IEngine type back to I2CS and do another Save/Refresh.

Now open the PH Explorer Links tab and set up the Links between each STAT and and your Insteon Controller.

PowerHome now has support that causes Thermostat devices to update within PowerHome as items change so you don't have to rely solely on polling. (See setting up Triggers, below.) With the thermostat as the current device, you'll want to create responder links with the STAT as the controller and the PLM as responder. The first link created should be from group 239. Next create the group 1 followed by group 2 followed by group 3.

You can control the order of group creation (and thus Trigger handling priority) by using the CTRL Sort field Place a 1 in the 239 group, a 2 in the 1 group, etc and place a 9 in all other groups as the order doesnt really matter after that).

You now have the Device configuration parameters all set up, and you are ready to use it.

From PowerHome Explorer open the Analog I/O window...

and Add the five Insteon Stat attributes that can be sensed (Cool Set Point, Heat Set Point, Humidity, Stat Mode, and Temp) for each of your thermostat devices.

Create ID Names to use with Macros, Triggers, etc. and enter a description for each item. This Description will be used in the Device Status window to describe the item. Select the I/O, and Controller parameters from the pull-down lists. Enter the IP Address for the STAT (this will change to the Device ID string in later releases of PH) and a poll interval (in seconds) to repeatedly check the status of each item. Enter a string in the Message field that you want to appear in the Device Status window, after the parameter value. The Poll Intvl field allows you to specify how often PowerHome should manually "poll" for the values from the thermostat. This column is in seconds. From the examples below, a Poll Interval of 300 is used which equates to 5 minutes.

Device Status Window showing "Message" strings appended to parameter values...

This completes the setup of the Thermostats.

Reinit/Restart PowerHome to assure all changes are locked in and saved.

You can now read/write STAT values using the following PH Functions...

ph_getanalog("ID")
ph_setanalogout("ID","TYPE/VALUE")

where:
ID is the ID you assigned the thermostat in the THERMOSTATS screen.
VALUE is a string containing the value you wish to set.
TYPE is a string describing predefined one of the attributes you have previously defined in the "Analog Input/Output Detail" Table. (See Detail Table figure above.)

If you query a Stat with a Stat Mode command, it will return one of these string values ...
Off
Heat
Cool
Auto
Fan
Program Auto
Program Heat
Program Cool

The information returned by the ph_getanalog function will be a string value. In the case of values such as temperature and cool setpoint, this string value will be a numeric (eg. 37, 72, 78, etc). You will need to use a function such as integer() to convert the string to a numeric for further processing. Executing ph_getanalog for the thermostat mode will return values such as "Off", "Cool", "Heat", etc. Unlike previous PowerHome Insteon Thermostat routines, the data values for setpoint and termperature are now direct reading and do not have to be divided by two to obtain the correct value.

For instance the following reads all of the "TS1" thermostat parameters, and writes each to a Global Variable (which you have already defined in the Global Variables window...

NOTE: The ph_getanalog function ONLY returns text values. In the case of setpoint and temps, the text value returned will be numeric but it is still a text value in terms of a formula. For example...

if(ph_getanalog("TS1CSP") < 78,1,0)

The above formula will fail because you're comparing text to a numeric. You would need to use this instead...

if(integer(ph_getanalog("TS1CSP")) < 78,1,0)

This function is now proper because a number is now compared to another number.

The following writes a new Heat Setpoint value to the "TS2" thermostat.

ph_setanalogout("TS2HSP","72")

Its important to note that the second value is a string instead of a numeric value. This is because the ph_setanalogout function is looking for the calculated value which can be anything. In the case of the thermostat device types, the calculated value and the raw value are essentially the same.

NOTE: In order to set a heat/cool temperature setting, the Stat must be in the appropriate State. Thus the above TS2HSP would fail unless the Stat is in "Heat" mode.

The proper sequence would be...

ph_setanalogout("TS2MODE","Heat")
ph_setanalogout("TS2HSP","72")

In order to have the changing thermostat values updated into your Global variables, or in your Control Center or web page, appropriate Triggers must be defined in the Triggers window.

NOTE: When the Trigger is activated, TEMP4 will contain the appropriate RAW value read from the STAT for use in setting Global Variables, or in formula actions you may wish to take. The best way to fetch the TEMP4 value is to use the ph_getvar(2,4) function. The TEMP5 variable will contain the calculated value read from the STAT. In the case of temps and setpoints, the raw and calculated values are the same. In the case of the thermostat mode, TEMP4 will contain the raw value 2 while TEMP5 will contain the calculated value "Cool". The best way to fetch the TEMP5 value is to use ph_getvar(2,5).

A typical setup might look like this...

Note the "Action Type", "Trigger Type", and "Trigger ID" are all pull-down selections. Everything else in the blue background areas, you will enter yourself. The grayed area values are automatically inserted by your pull-down choices.

A typical Action would be this...

ph_setglobal_s("STAT-DWN-COOLSP",ph_getvar_s(2,4))+
ph_setglobal_s("STAT-DWN-SET",ph_getglobal_s("STAT-DWN-COOLSP"))

which reads the contents of TEMP4 and writes it to the Global "STAT-DWN-COOLSP" and also updates the STAT-DWN-SET variable which is used as a single convenient setpoint variable that holds either the Heat or the Cool setpoint, as appropriate for the current STAT Mode.

At this point, you should have a working Insteon Thermostat setup in PowerHome. From this base, you are now ready to read and control your thermostats as dictated by your needs and imagination.


Setting up PLM Responder Links

FAQ: Setting up PLM as Responder Links to Assure Best PowerHome Performance
Knowledge Notes

You almost always want the PLM as a responder link for every Insteon device.

This is not necessary for responder only devices such as LampLincs though (if Responder groups does not equal 0 in the types table, you can create Responder links).

Thus none needed for the red boxed device, but suggested for the green boxed devices.

Responder Link OK?

If there are multiple Responder Links, then it is good practice to make this link the first link, so that the PLM will have the greatest chance of being updated.

When you control an Insteon device manually (at the switch), it will send an Insteon Group Broadcast command (unacknowledged without retries) to any device listening.

If the receiving device hears it (the PLM) then we're good. If it isn't heard, then we must rely on a Group Cleanup message.

This message is sent to every device in the Group (in the order that the links appear) up to/until another Insteon message is placed on the power line.

If you have two Insteon switches right next to each other, and first switch one and then immediately the other, you'll get a group broadcast from the first one but the group broadcast from the second one will cut off any (or if you're lucky, the first group cleanup may already be sent) group cleanups being sent and you'll only get them from the second switch (up until another Insteon message is placed on the line).

The second reason its good to have a Responder link to the PLM is that the message is sent directly to the PLM and acknowledged. Due to the way Insteon works, if a Switch controls another Insteon device (but not the PLC/PLM) it will send the group broadcast (which the PLM may hear) and if you're lucky the Group Cleanup message directly to the controlled device (which the PLM may also hear). If the PLM is far away and the switch and its controlled device are close to one another, the PLM may never get a chance to hear the Group Cleanup as the message will stop being repeated as soon as the remote device acknowledges it. (Insteon relies upon a simulcast repeating message network to try and get its messages through to every device).

You typically only need a controller link to a device with the PLM as the controller if you plan on controlling multiple devices through the PLM groups. A special situation would be where a LampLinc (eg, SmartHome Model 2456D2, which can't have a Responder link) is I2CS.

Then you MUST have the PLM address somewhere in its database so a controller link is the most logical answer.


Strings: Tips & Hints

FAQ: String Tips and Hints
Knowledge Notes
An important note about PowerHome (PH) string search functions is that they often use "greedy" regular expression searchs, depending on the "special characters" used in the parameter values. When using the * and + special characters this function will not stop at the first match but will instead go to the last match. The Escape character (~255) does not exhibit this characteristic and is thus a better choice versus the (.+) or (*) when looking for the first match. NOTE: You should NEVER replace crlf's if you can help it as it slows the searches down and can produce unexpected results due to greediness.

The ".+" and "~255" are totally different. The ".+" is part of the regular expression syntax but the "~255" is a unique PH feature. What the ~255 does is separate individual regular expression searches and is typically used when you're NOT replacing carriage return/line feeds (this is slow to do) but allows you the ability to "kind of" search across multiple lines. Since a single regular expression will only search up to a carriage return line feed (it will "reset" itself and then search the next line up to a CR/LF and then repeat), we either have to replace the Carriage Return/Line Feed characters(the CR/LF "2" flag does this) with other characters or we use the ~255 to perform multiple searches with the last search being whats actually used to pattern to match.

The PH search functions will not perform a regular expression search that spans multiple lines. If the data to search contains carraige returns or line feeds, the entire matching search data for the regular expression must exist within a single line. If the regular search expression must span across a line, then add 2 to the flags to have CR's and LF's temporarily converted. CR will be converted to ASCII 128 and LF will be converted to ASCII 129. If you convert CF/LF then you can include them in your search with PowerHome escape characters ~128 and ~129 respectively.

Within each search pattern you may perform multiple searches by separating your search pattern using the PowerHome escape character ~255. This is most useful when CF/LF IS NOT replaced and trying to match a particular piece of data. If you do multiple searches, the last search is used as the starting position and ending position of the returned text.

NOTE: Where search pattern srings might contain a quote (') character then you must use the single quote (') character to delineate your string variables.

The PowerHome regular expression engine (at least the Scintilla one that the string functions use) can only search a single line at a time. If there are multiple lines, it will search them all, sequentially, until a match is found. By adding a 2 to the flags parm in functions like ph_regexdiff(), PH first replaces all CR/LF's with different characters and then submits, what is now been converted into a single line, to the regex string parsing engine.

For example, given the following string (contained in LOCAL1) to be searched ...

ROMId,Name, Value,Avg,
"3F000001CD92C728","Refrig",39.20,37.46,
"3F0000017C8BD128","Outside",23.90,19.81,
"3F000001CDB2BA28","House",70.65,70.13,
"3F000001CD9E6D28","Freezer",1.96,1.11,'

The expression (ph_regexdiff1 ("3F~2551", "8", "[LOCAL1]", 1, 4,0,3,0 ) will work the same to find CD92C72 whether the flags parameter has a 0 or a 2.

The ~255 is a separator for two separate searches.

Stepping through the logic for each instance. Lets start with the flags parm = 0 (CR/LF is not replaced).

1. PH passes the first search to the regex engine. In this case, "3F". The regex engine knows nothing about ~255 or the 1 following it at this point.
2. The first line is searched for 3F. It is not found.
3. The second line is searched for 3F and it is found. The resulting location is returned to PowerHome.
4. PH now takes the second search (from the first search string) that was separated by ~255 and submits a new version of the data to the regex engine starting with the characters immediately following the 3F that was found in step 3. The data that is submitted to the search engine will look like this:

000001CD92C728","Refrig",39.20,37.46,
"3F0000018C8BD128","Outside",23.90,19.81,
"3F000001CDB2BA28","House",70.65,70.13,
"3F000001CD9E6D28","Freezer",1.96,1.11,

The regex search expression that will be performed against this data is a "1" which followed the ~255 escape character in the search strring.

5. The search is performed, and it successful on the first line. This location is returned back to PH

6. PowerHome then submits a new version of the data starting with the char immediately after where the "1" is found. The data looks like this: CD92C728","Refrig",39.20,37.46, "3F0000018C8BD128","Outside",23.90,19.81, "3F000001CDB2BA28","House",70.65,70.13, "3F000001CD9E6D28","Freezer",1.96,1.11, PH will now submit the regex expression for the ending search "8" to be searched against this data.

7. The search is performed and the 8 is found on the first line. This is returned back to PH and is deemed the 1st occurrence. Since we want the 4th occurrence, we're not done yet.

8. PH creates a new version of the data starting with the char after the first occurrence. It will look like this: ","Refrig",39.20,37.46, "3F0000018C8BD128","Outside",23.90,19.81, "3F000001CDB2BA28","House",70.65,70.13, "3F000001CD9E6D28","Freezer",1.96,1.11,

9. The whole process is repeated. PH starts with 3F and submits this to the regex engine. 3F is not found on the first line.

10. The regex engine then searches for 3F on the second line. It's found, the data is returned to PH, and the process repeats starting at step 4. When all is done, this is the second occurrence. We repeat until we find and finally return the 4th occurrence.

With the flags parm set to 2 (or 2 is added to the flags parm because a value of 3 will perform the same as 2 but with case not having to match), the CR/LFs are replaced with ~128 and ~129 respectively. Keep in mind that ~128 and ~129 are SINGLE characters with ASCII values of 128 and 129. The ~128 is just PowerHome (PowerBuilder actually) nomenclature that evaluates to the single ascii characters. Since the space character is decimal 32, you could make a space by using ~032 and it will internally be a single space character.

====

Now going through the process with flags = 2:

0. PH first replaces all CR/LF's with ~128 and ~129. The data that is passed to the regex engine will look like: ROMId,Name, Value,Avg,,~128~129"3F000001CD92C728", "Refrig",39.20,37.46,~128~129"3F0000018C8BD128","Outside",23.90,19.81,~128~129"3F000001CDB2BA28","House",70.65,70.13,~128~129"3F000001CD9E6D28","Freezer",1.96,1.11,

Note there are no line breaks in the above and it is a single long continuous line.

1. PH passes the first search to the regex engine. In this case, "3F". The regex engine knows nothing about ~255 or the 1 following it at this point.

2. The long continuous line is searched for 3F. Its found after the ~128~129. This is passed back to PH.

3. PH now takes the second search (from the first search string) that was separated by ~255 and submits a new version of the data to the regex engine starting with the characters immediately following the 3F that was found in step 3. The data that is submitted to the search engine will look like this:

000001CD92C728","Refrig",39.20,37.46,~128~129"3F0000018C8BD128","Outside",23.90,19.81,~128~129"3F000001CDB2BA28","House",70.65,70.13,~128~129"3F000001CD9E6D28","Freezer",1.96,1.11,

It is still a single continuous line. The regex search expression that will be performed against this data is "1".

4. The search is performed and its found. This location is returned back to PH

6. PowerHome then submits a new version of the data starting with the char immediately after where the "1" is found. The data looks like this:
CD92C728","Refrig",39.20,37.46,~128~129"3F0000018C8BD128","Outside",23.90,19.81,~128~129"3F000001CDB2BA28","House",70.65,70.13,~128~129"3F000001CD9E6D28","Freezer",1.96,1.11,

It is still a single continuous line.

PH will now submit the regex expression for the ending search "8" to be searched against this data.

7. The search is performed and the 8 is found as the 8th character of the continous line. This is returned back to PH and is deemed the 1st occurrence. Since we want the 4th occurrence, we're not done yet so this process is continued until 4 matches are found (or not) and the Result returned.


String Extraction

FAQ: String Match/Locate/Extract Examples
Knowledge Notes

The various string Match/Locate/Extract functions can be very complex and thus confusing.

The following example pulls various data points from a weather site, demonstrates the use of a number of functions, and provides tips for "best use" of System/Global variables in the procecss.

An explaination of the macro follows the macro image ...

This weather info was fetched from the "weatherforyou.com" web site and saved in LOCAL1.

Next a check is made to verify that a valid result was returned. If not an error message is posted in the User Log by the code at the "ERROR" label section of the macro. Note that the label of "nextLINE" is a bogus label. It could be anything (ie, "foofoo") you want as long as it is not a valid label. If PH can't find a label with the named designation, then it just goes to the next line of code.

Thus the (bogus) "nextLINE" label is discriptive for code-flow understanding.

Assuming we have a good page returned, it turns out that this web page is rather huge, so to keep subsequent string operations from bogging down, the text in LOCAL1 is trimmed to just 5000 characters around the area where the needed data is located. An easy way to determine this "sweet area" is to use the ph_saveurl() which will save your weather site page contents to a file.

Then open the file in Windows Word (or similar program) and use the word/character count feature to locate your "sweet spot." Using that data, use the "mid" function to extract an area around your interest area, allowing for reasonable variations in subsequent web page designs.

Next we look for the "Wind" data.

It is located in an html area that looks like this ...

<span class="Label">Wind </span><span class="Value">SW 18 MPH </span>

Seq #80 then checks to see if the returned date was "Calm" rather than a wind speed in mph. Since the speed is used elsewhere and needs to be a number, it is converted from "Calm" to the number 0.

NOTE: The formula in Seq #80 was (as well as other formulas before and after) was ...
if(match (ph_getvar_s(1,2), "Calm"),"0","[LOCAL2]"),
and NOT ...
if(match ("[LOCAL2]", "Calm"),"0","[LOCAL2]")

The ph_getvar_s() is the ONLY way that you can be assured of a good string being returned, since it is possible that a complex target string may contain BOTH single (') and double (") prime characters. It is a "best practice" to always use the ph_getvar_s() function when you want to get a perfect string returned.

Seq #90 snaps the numeric value of "18" out of the string returned into LOCAL2, which was "SW 18 MPH"

Finally (Seq #100) an error check is done to assure that a numeric value is returned. If the value extracted is not a number then a default value of "3" is placed in LOCAL2.

Next the Humidity data value (Seq 3120) is extracted from the web page environment of ...

<span class="Label">Humidity </span><span class="Value">54%</span>

In Seq #130, we error check and if the Humidity value id blank, then substitute "65" as a generic value.

In Seq #140 we extract the wind chill, or "Feels Like" temp from a web page environment of ...

<span class="SmallTemp">Feels Like &deg; 10 F</span>

After that it is just some house keeping to round the numers to integer values.

This example gives a number if various ways to trim, find, and fetch data from complex data strings.


Triggering from Insteon Device Changes

FAQ: TRIGGERING FROM INSTEON DEVICE CHANGES
Knowledge Notes

When an Insteon Device changes its state by means of its associated switch, or when commanded to change by a linked Controlling Device, Insteon commands are broadcast so that Linked Responders can be kept aware of what is happening. The actual trigger type In/Out is whether PH sends it (Out) or another device sends it (In)

Insteon communications traffic is monitored by PH, and recorded in the Event Log. It can be used to Trigger actions by setting up trigger events in the PowerHome Explorer>Triggers tab.

The triggers pretty much match the available Insteon command types. Insteon has group broadcast commands, direct commands, group cleanups (a type of Direct command), and standard broadcast commands. The In and Out refers to the whether the command is coming (In) or going (Out) as "seen" by the PLC/PLM controller on the computer running PowerHome.

command modes

The image below shows some sample Event Log entries ...

1) Four different actions from an Insteon wall switch (DWN SOFA) that sent an on, an off, brighten for a few seconds, then dim for a few seconds.
2) An Insteon command sent from PowerHome to turn the DWN SOFA light On.
3) A Trigger Check action sensed by a Triggers entry, monitoring "Insteon Device Change" and Any trigger type but filtered by the Boolean field to only pass Direct Command or Group Broadcast messages sent from the DWN SOFA switch. See TEMP variables trigger contents discussion below.
trigger types

Insteon devices typically only send group broadcast commands usually followed by the group cleanup command unless another Insteon transmission interrupts the process. Thus as seen below, the Group Broadcast On is followed moments later by a Group Cleanup command.
command types

When an Insteon device is switched on/off/brightened/dimmed, it sends a group broadcast.

When PowerHome "see" this, it is considered an "Insteon Group In" (it's incoming to PH).

If PH sends a group broadcast command, that is an "Insteon Group Out" (it's outgoing from PH).

If the remote device sends the group cleanup command, then that will be an "Insteon Direct In" trigger (with a "Grp Cleanup-From Any" selection used for the Trigger ID Number).

If PH sends a group cleanup, then that is an Insteon Direct Out with a "Grp Cleanup-To Any" selection used for the Trigger ID Number). Only a PLM will send Direct (non cleanup) commands. If PowerHome sends it, it's an Insteon "Direct Out" with "Direct-To Any" in the Trigger ID Number field. If another PLM sends a direct command and PH hears it, it's a "Direct In" with "Direct-From Any" in the Trigger ID Number.

Take for example a group cleanup command being sent from a remote device to the PLM itself. This will always be an Insteon Direct In trigger since PowerHome didn't send it. Typically, you will probably choose for a trigger ID, the device that is actually sending the group cleanup. If you do this, then the Trigger Number should be Grp Cleanup - To Any. This means that PH will trigger on all group cleanup commands for the device chosen as the Trigger ID. So if the cleanup is sent to the PLM (or any other device), a Trigger will occur.

Now if instead the Trigger ID is set to be the PLM, you need to set the Trigger Number to Grp Cleanup - From Any. The trigger type will stay the same as Insteon Direct In. In this version of the trigger, PowerHome will fire on a group cleanup from ANY device sending a group cleanup direct to the PLM.

A Broadcast type command is not commonly seen, as not many devices send it, although some EZIO devices use this command type to notify when a zone is changing.

When a device is controlled by other sources (ie, via linking and groups or PH controlling it via the PLC/PLM) then rather than attempt to trigger off specific senders or trigger types, it is often easiest to use the "Insteon Device Change" Trigger Type, which will watch all activities affecting a targeted device.

The "Insteon Device Change Trigger" can be "triggered" by any of the Insteon command types as long as it results in a status change for the device (even if the status is the same as it currently is. That action is still updating the status.

If the goal is to monitor and trigger off of a device status changing, the Insteon Device Chg trigger is probably the most logical option. If however, you're trying to trigger off of a specific command (take for instance a handheld remote link that isnt actually linked to anything other than the PLM and you're using it to execute a macro or some other function), then one of the others may make more sense.

There is a large range of events that can be used to fire a Trigger. Here are a number of examples ...

trigger examples

Following is a brief summary of many of the significant items in the table above.

  1. Note the Trigger IDs are a sorted list. When a Trigger Event occurs, the Triggers list is searched for a match. Thus any time critical items should be located at the beginning of the list by using a leading underscore (_) or numeric character to put them at the start of the list.
  2. There are different Action Types that can be used to respond to the trigger. These include macro calls, simulated key strokes, raw formulas, and direct Insteon device control. The "Action" field is used as appropriate for the Action "Type".
  3. There are an extraordinary range of Trigger Types than can be used. The example belows shows many of the commonly used types. NOTE: If a device (eg, light) is a responder to other controllers, then the "Insteon Device Change" Trigger Type will normally be used as that monitors the device state itself independant of what is sending the change command.

    Further NOTE that the Boolean filed can be used as a filter to control the trigger "firing" dependant on what the device change was (ie, was it turned on or off or dimmed, etc?)

    The next paragraph explains how different device state information is passed thru the Trigger to subsequent Actions that might be taken.
The Insteon Device Chg trigger includes addtional supporting info in the TEMP variables that may assist you in your efforts (most triggers include addl info in the TEMP vars).

Below is the data that is contained in the TEMP vars for the Insteon Device Chg trigger:

TEMP1 ID of Trigger [eg, "HALL ON-SR"]
TEMP2 0
TEMP3 Insteon CMD2
TEMP4 Type of trigger
1 = Direct Command from PH PLC
2 = Group Cleanup from PH PLC
3 = Group Broadcast from PH PLC
4 = Direct Command from device
5 = Group Broadcast from device
6 = Group Cleanup from device
TEMP5 The address of the Trigger Sending device [eg, "1E.16.B2"]
TEMP6 Command Type
20 = Direct type command
21 = Broadcast type command
TEMP7 The address of the receiving device [eg, "08.3C.12"]
TEMP8 The Group number for group type commands, 1 otherwise
TEMP9 Insteon CMD1 [eg, "19"]
TEMP10 ID of Trigger Sending device [eg, "MID-SOFA"]

You can effectively get a “Level Change” trigger by using the “Insteon Device Chg” trigger with [Any] group and [Any] command and then placing this formula in the “Boolean” field:
case([TEMP9] when 21,22,24 then 1 else 0)
This will only allow the trigger to fire when a dim, bright, or stop manual change command affects the desired device. You could then create multiple “Insteon Device Chg” triggers with appropriate formulas in the “Boolean” field all executing different macros to pick up some granularity.


Undo/Redo

FAQ: UNDO/REDO
Knowledge Notes

A CTRL-Z will UNDO changes as most Windows programs do. Within the PowerHome Explorer, an F10 will UNDO everything done on the current detail window. Once you leave a detail window (or refresh/save with F5), the changes are permanent and F10 will have no effect. A CTRL-Y will REDO actions, as with most Windows programs.

When you delete a macro line, two things happen...

  • First, the line is deleted, then
  • the rest of the lines are renumbered.
So the first CTRL-Z undoes the renumbering and the second CTRL-Z undoes the delete.

F10 will "Undo All" (up to the last save).

There is also a CTRL-Y for redo.

Thus if you're working on a screen and have made multiple changes, a single F10 will revert you back to where you were when you first entered the screen.

You can also ctrl-z your way back to this point. But if you hit F5 (Save/Refresh) or navigate to a different Explorer detail screen, your changes are saved to the database and are permanent.

These 3 options are also available and shown on the PH Explorer toolbar (last 3 buttons) and the "Edit" menu.


FAQ: Charting From PH
Knowledge Notes

While PowerHome does not incorporate "native" charting capability, it is possible to chart just about any data that PH can access, using the following Google Charts extraordinarily capable API.

Introductory documentation is available here...
https://google-developers.appspot.com/chart/interactive/docs /index

and a wonderful Help Forum with quick responses and terrific mentors here...
https://groups.google.com/forum/#!forum/google-visualization -api

Using the Google API, coupled with a very moderate amount of javaScrip it is possible to display graphs of any numeric values that PH can access.

As an aside, what is documented below is for Line Charting, but the Google Chart API is astoundingly capable, allowing for the creation of line, pie, donut, column, area, scatter, and more charts. You can even create these Gauges ...
gauges

The example documentation here is broadly general, and shows a web page displaying 3 different charts, but this dialog will only cover a single chart, the DAY chart. The others are similar, but have different axis parameters and Timed Event firing schedules..

The Line chart shown below (the DAY chart) is one chart of the trio.
chart

This chart is created from the following web page...

chartTemps.html: The web page that presents the charts using the Google Charts API. This page is almost entirely javaScript, but it is heavily commented to help it be as understandable as possible. This web page is constructed to create the three charts using a single function, drawChart(), and passing parameters to it in the call, that define the axis ranges, various labels, input csv file, etc.

Chart html Page

The chart was produced from data contained in a CSV file that looks like this...

Time,Dwn,Dwn,Mid,Mid,Out,Out,Frzr,Frzr,Frig,Frig
0,71.1,,71,,28.7,,4.6,,26.5,
0.17,70.6,,71,,28.7,,4.6,,26.5,
0.33,70.3,,71,,27.9,,2.6,,25.6,
0.5,70.2,,71,,27.9,,1.1,,25.6,
0.67,70.1,,71,,28.2,,-0.4,,25.6,
0.83,70.1,,71,,29,,-0.9,,29.2,
1,70.1,,71,,29,,-1.9,,32.1,
1.17,69.6,,71,,28.7,,-2.4,,34.8,
1.33,69.3,,71,,28.7,,-2.4,,35.7,
1.5,69.2,,71,,28.7,,-2.9,,36.6,
. . . . .
. . . . .
22.5,72.1,,,71,,29.6,,0.6,,46.3
22.67,72.1,,,71,,29.6,,1.1,,46.5
22.83,72.6,,,71,,29.9,,1.6,,40.4
23,72.3,,,71,,29.1,,2.1,,33.7
23.17,72.2,,,71,,29.1,,2.6,,31.1
23.33,71.6,,,71,,28.8,,3.1,,30.1
23.5,71.3,,,71,,28.2,,3.6,,28.7
23.67,71.1,,,71,,28.7,,3.6,,28.3
23.83,71.1,,,71,,28.7,,4.1,,27.4

This CSV Day file contains specific DAY CHART data and timing information. There will be similar csv files for the WEEK and MONTH charts.

The PH "SQL UPDATE_DAY_TBL" macro produces the data for this CSV file. Whenever the chart viewing web page "chartTemps.html" is opened, it calls the Google charting API functions to chart the data from this CSV file. This Macro is called from a Timed Event that runs every 10 minutes, thus populating 6 time bins per hour, over a 24 hour day. The macro looks like this...

Update Day Tbl

All of the collected data is stored in the PowrHome "userData2" database Table, and all of the database management is done using PowerHome standard SQL functions See this PH Forum link for information on that table (search for "userdata2" to find the info in this large Thread). It is on page 1..

http://www.power-home.com/forum/forum_posts.asp?TID= 2723&KW= userdata2

This example chart uses the following columns in the PH userData2 db Table ...

NOTE: The Charts show a sensor's data line as solid (for current) and dashed (for historic) data. That way you can see what was happening, at the current time in the period before, to identify any deviations from expected norms. This is handled in the Google Chart API by using SQL to move the paired (new/old) data from the left pair-column to the right column at the beginning of a new charting period (ie, midnight for the DAY chart). The Google Chart visualization (on the chartTemps.html page) charts left column data as "solid" and right column data as "dashed". The following image only shows "left" column (new) data points.

userData2 Tbl

The contents of these columns is as follows...

  • uid - Sequentially numbered as a unique index key
  • type - In the example "1" is used to mark this as a "Day" table, since there could be a "Week" and "Month" and maybe even "Year" charts from the same general Table( Type=2,3,4).
  • idstring: Not used
  • idnum: Not used
  • iddate - not used
  • valstring1: Time expressed as a number. Required to make Google Charts use a continuous,, rather than discreet X-Axis so that data is displayed in the correct time position even if there are missing data points. The UPDATE Macro converts true time into discrete numeric bins so that everything is standardized. See above comment about my 10 minute (1/6th hour) time increments.
  • valstring2: Holds the current (new) data, since 00:00 hours up to the current viewing time.
  • valstring3: This column holds the historic data. This Day view is a 24 hour cyclic buffer. So if the current snapshot was at 2PM all of the day from 00:00 - 14:00 hours would be in the valstring1 column (and displayed as a solid line) while the data from 2PM to midnight would all appear in the valstring2 column, since that is historic (yesterday's data).}
  • No other columns are used for Charting data but valnum1 and valnum2 are used as a ring buffer to compute long term average temps for the Frig and Frzr. This need will disappear with the release of PH 2.1.5c which will have averaging built into the Analog I/O Devices support.

In addition to these these files, an additional Macro is also useful. It is the "SQL CREATE_DAY_TABLE" which makes sure the userData2 db is cleared out before use, and then creates a set of standard data capture time bins, for use by the "SQL CREATE_DAY_TABLE" routine.

NOTE: The very first formula in this macro (normally disabled) can be enabled to assure an empty database Table. Normally it is disabled to allow just the DAY entries to be reset, in the event the db is used for multiple charts. This table covers 24 hours and has 6-bins (10 min slots) within each hour. The DAY data is all keyed as Type-1

CREATE Dat Tbl
**********************************************

OK. All the background stuff is defined, how do you use this?

1. Create Timed Events to capture your Chart data over the desired period (Day/Week/Month/etc)

Timed Event

2. Create a web link from your Web Center page to chartTemps.html ! This will create the actual chart(s) when you click on the web page.