Polyglot Methods and Classes

Module

These are the classes and methods from the Polyglot module.

Config Manager

The configuration management module for Polyglot

class polyglot.config_manager.ConfigManager(config_dir)[source]

Configuration Manager class

Parameters:config_dir – The configuration directory to use
decode(encoded)[source]

Decode passwords and return decoded

encode()[source]

Encode passwords and return an encoded copy

make_path(*args)[source]

make a path to a file in the config directory

nodeserver_sandbox(url_base)[source]

make and return a sandbox directory for a node server.

read()[source]

Reads configuration file

update(*args, **kwargs)[source]

Update the configuration with values in dictionary

write()[source]

Writes configuration file

Core

The primary functionality for the Polyglot application

class polyglot.core.Polyglot(config_dir)[source]

Core class

Parameters:config_dir – Directory where configuration is stored
Variables:config – Dictionary of current config
get_log()[source]

Read and return the log file contents.

run()[source]

Run the Polyglot server

setup()[source]

Setup Polyglot to resume the last known state

stop(*args)[source]

Stops the Polyglot server

update_config()[source]

Signal Polyglot to fetch updated configuration.

Nodeserver API

This library consists of four classes and one function to assist with node server development. The classes polyglot.nodeserver_api.NodeServer and polyglot.nodeserver_api.SimpleNodeServer and basic structures for creating a node server. The class polyglot.nodeserver_api.Node is used as an abstract class to crate custom nodes for node servers. The class polyglot.nodeserver_api.PolyglotConnector is a bottom level implementation of the API used to communicate between Polyglot and your node server. Finally, included in this library is a method decorator, polyglot.nodeserver_api.auto_request_report(), that wraps functions and methods to automatically handle report requests from the ISY.

class polyglot.nodeserver_api.Node(parent, address, name, primary=True, manifest=None)[source]

Abstract class for representing a node in a node server.

Parameters:
  • parent (polyglot.nodeserver_api.NodeServer) – The node server that controls the node
  • address (str) – The address of the node in the ISY without the node server ID prefix
  • name (str) – The name of the node
  • primary (polyglot.nodeserver_api.Node or True if this node is the primary.) – The primary node for the device this node belongs to, or True if it’s the primary.
  • manifest (dict or None) – The node manifest saved by the node server
_drivers = {}

The drivers controlled by this node. This is a dictionary of lists. The key’s are the driver names as defined by the ISY documentation. Each list contains at least three values: the initial value, the UOM identifier, and a function that will properly format the value before assignment. The fourth value is optional – if provided, and set to “False”, the driver’s value will not be recorded in the manifest (this is useful to reduce I/O when there is no benefit to restoring the driver’s value on restart).

Insteon Dimmer Example:

_drivers = {
    'ST': [0, 51, int],
    'OL': [100, 51, int],
    'RR': [0, 32, int]
}

Pulse Time Example:

_drivers = {
    'ST': [0, 56, int, False],
}
_commands = {}

A dictionary of the commands that the node can perform. The keys of this dictionary are the names of the command. The values are functions that must be defined in the node object that perform the necessary actions and return a boolean indicating the success or failure of the command.

add_node()[source]

Adds node to the ISY

Returns boolean:
 Indicates success or failure of node addition
get_driver(driver=None)[source]

Gets a driver’s value

Parameters:driver (str or None) – The driver to return the value for
Returns:The current value of the driver
manifest

The node’s manifest entry. Indicates the current value of each of the drivers. This is called by the node server to create the full manifest.

Type:dict
node_def_id = ''

The node’s definition ID defined in the node server’s profile

query()[source]

Abstractly queries the node. This method should generally be overwritten in development.

Returns boolean:
 Indicates success or failure of node query
report_driver(driver=None)[source]

Reports a driver’s current value to ISY

Parameters:driver (str or None) – The name of the driver to report. If None, all drivers are reported.
Returns boolean:
 Indicates success or failure to report driver value
report_isycmd(isycommand, value=None, uom=None, timeout=None, **kwargs)[source]

Sends a single command from the node server to the ISY, optionally passing in a value.

No formatting, and little validation, of the isy cmd, value, or uom is done by this simple low-level API. It is up to the caller to ensure correctness.

Parameters:
  • isycommand (str) – Name of the ISY command to send (e.g. ‘DON’)
  • value (string, float, int, or None) – (optional) The value to be sent for the command
  • uom (int or None) – (optional) - The value’s unit of measurement. If provided, overrides the uom defined for this command
  • timeout (int or None) – (optional) - the number of seconds before this command expires and is discarded
Returns boolean:
 

Indicates success or failure to queue for sending (Note: does NOT indicate if actually delivered)

run_cmd(command, **kwargs)[source]

Runs one of the node’s commands.

Parameters:
  • command (str) – The name of the command
  • kwargs (dict) – The parameters specified by the ISY in the incoming request. See the ISY Node Server documentation for more information.
Returns boolean:
 

Indicates success or failure of command

set_driver(driver, value, uom=None, report=True)[source]

Updates the value of one of the node’s drivers. This will pass the given value through the driver’s formatter before assignment.

Parameters:
  • driver (str) – The name of the driver
  • value – The new value for the driver
  • uom (int or None) – The given values unit of measurement. This should correspond to the UOM IDs used by the ISY. Refer to the ISY documentation for more information.
  • report (boolean) – Indicates if the value change should be reported to the ISY. If False, the value is changed silently.
Returns boolean:
 

Indicates success or failure to set new value

smsg(strng)[source]

Logs/sends a diagnostic/debug, informative, or error message. Individual node servers can override this method if they desire to redirect or filter these messages.

class polyglot.nodeserver_api.NodeServer(poly, shortpoll=1, longpoll=30)[source]

It is generally desireable to not be required to bind to each event. For this reason, the NodeServer abstract class is available. This class should be abstracted. It binds appropriate handlers to the API events and contains a suitable run loop. It should serve as a basic structure for any node server.

Parameters:
  • poly (polyglot.nodeserver_api.PolyglotConnector) – The connected Polyglot connection
  • optional shortpoll (int) – The seconds between poll events
  • optional longpoll (int) – The second between longpoll events
add_node(node_address, node_def_id, node_primary_addr, node_name, callback=None, timeout=None, **kwargs)[source]

Add this node to the polyglot

Returns bool:True on success
long_poll()[source]

Called every longpoll seconds for less important polling.

on_add_all(request_id=None)[source]

Received add all command from ISY

Parameters:optional request_id (str) – Status request id
Returns bool:True on success
on_added(node_address, node_def_id, primary_node_address, name)[source]

Received node added report from ISY

Parameters:
  • node_address (str) – The address of the node to act on
  • node_def_id (str) – The node definition id
  • primary_node_address (str) – The node server’s primary node address
  • name (str) – The node’s friendly name
  • optional request_id (str) – Status request id
Returns bool:

True on success

on_cmd(node_address, command, value=None, uom=None, request_id=None, **kwargs)[source]

Received run command from ISY

Parameters:
  • node_address (str) – The address of the node to act on
  • command (str) – The command to run
  • value (optional) – The value of the command’s unnamed parameter
  • uom (optional) – The units of measurement for the unnamed parameter
  • optional request_id (str) – Status request id
  • <pN>.<uomN> (optional) – The value of parameter pN with units uomN
Returns bool:

True on success

on_config(**data)[source]

Received configuration data from Polyglot

Parameters:data (dict) – Configuration data
Returns bool:True on success
on_disabled(node_address)[source]

Received node disabled report from ISY

Parameters:node_address (str) – The address of the node to act on
Returns bool:True on success
on_enabled(node_address)[source]

Received node enabled report from ISY

Parameters:node_address (str) – The address of the node to act on
Returns bool:True on success
on_exit(*args, **kwargs)[source]

Polyglot has triggered a clean shutdown. Generally, this method does not need to be orwritten.

Returns bool:True on success
on_install(profile_number)[source]

Received install command from ISY

Parameters:profile_number (int) – Noder Server’s profile number
Returns bool:True on success
on_query(node_address, request_id=None)[source]

Received query command from ISY

Parameters:
  • node_address (str) – The address of the node to act on
  • optional request_id (str) – Status request id
Returns bool:

True on success

on_removed(node_address)[source]

Received node removed report from ISY

Parameters:node_address (str) – The address of the node to act on
Returns bool:True on success
on_renamed(node_address, name)[source]

Received node renamed report from ISY

Parameters:
  • node_address (str) – The address of the node to act on
  • name (str) – The node’s friendly name
Returns bool:

True on success

on_result(seq, status_code, elapsed, text, retries, **kwargs)[source]

Handles a result message, which contains the result from a REST API call to the ISY. The result message is uniquely identified by the seq id, and will always contain at least the numeric status.

on_statistics(**kwargs)[source]

Handles a statistics message, which contains various statistics on the operation of the Polyglot server and the network communications.

on_status(node_address, request_id=None)[source]

Received status command from ISY

Parameters:
  • node_address (str) – The address of the node to act on
  • optional request_id (str) – Status request id
Returns bool:

True on success

poll()[source]

Called every shortpoll seconds to allow for updating nodes.

poly = None

The Polyglot Connection

Type:polyglot.nodeserver_api.PolyglotConnector
register_result_cb(func, **kwargs)[source]

Registers a callback function to handle a result. Returns the unique sequence ID to be passed to the function whose result is to be handled by the registered callback.

report_status(node_address, driver_control, value, uom, callback=None, timeout=None, **kwargs)[source]

Report a node status to the ISY

Returns bool:True on success
restcall(api, callback=None, timeout=None, **kwargs)[source]

Sends an asynchronous REST API call to the ISY. Returns the unique seq id (that can be used to match up the result later on after the REST call completes).

run()[source]

Run the Node Server. Exit when triggered. Generally, this method should not be overwritten.

setup()[source]

Setup the node server. All node servers must override this method and call it thru super. Currently it only sets up the reference for the logger.

smsg(strng)[source]

Logs/sends a diagnostic/debug, informative, or error message. Individual node servers can override this method if they desire to redirect or filter these messages.

tock()[source]

Called every few seconds for internal housekeeping.

class polyglot.nodeserver_api.PolyglotConnector[source]

Polyglot API implementation. Connects to Polyglot and handles node server IO.

Raises:RuntimeError
add_node(node_address, node_def_id, primary, name, timeout=None, seq=None)[source]

Adds a node to the ISY. To make this node the primary, set primary to the same value as node_address.

Parameters:
  • node_address (str) – The full address of the node (e.g. ‘dimmer_1’)
  • node_def_id (str) – The id of the node definition to use for this node
  • primary (str) – The primary node for the device this node belongs to
  • name (str) – The name of the node
  • timeout (str, float, or int) – (optional) timeout (seconds) for REST call to ISY
  • seq (str or int) – (optional) set to unique id if result callback desired
change_node(node_address, node_def_id, timeout=None, seq=None)[source]

Changes the node definition to use for an existing node. An example of this is may be to change a thermostat node from Fahrenheit to Celsius.

Parameters:
  • node_address (str) – The full address of the node (e.g. ‘dimmer_1’)
  • node_def_id (str) – The id of the node definition to use for this node
  • timeout (str, float, or int) – (optional) timeout (seconds) for REST call to ISY
  • seq (str or int) – (optional) set to unique id if result callback desired
commands = ['config', 'install', 'query', 'status', 'add_all', 'added', 'removed', 'renamed', 'enabled', 'disabled', 'cmd', 'ping', 'exit', 'params', 'result', 'statistics']

Commands that may be invoked by Polyglot

connect()[source]

Connects to Polyglot if not currently connected

connected

Indicates if the object is connected to Polyglot. Can be set to control connection with Polyglot.

Type:boolean
disconnect()[source]

Disconnects from Polyglot. Blocks the thread until IO stream is clear

exit(*args, **kwargs)[source]

Tells Polyglot that this Node Server is done.

get_params(**kwargs)[source]

Get the params from nodeserver and makes them available to the nodeserver api

install(*args, **kwargs)[source]

Abstract method to install the node server in the ISY. This has not been implemented yet and running it will raise an error.

Raises:NotImplementedError
listen(event, handler)[source]

Register an event handler. Returns True on success. Event names are defined in commands. Handlers must be callable.

Parameters:
  • event (str) – Then event name to listen for.
  • handler (callable) – The callable event handler.
logger = None

logger is initialized after the node server wait_for_config completes by the setup_log method and the log file is located in the node servers sandbox. Once wait_for_config is complete, you can call poly.logger.info(‘This variable is set to %s’, variable)

pong(*args, **kwargs)[source]

Sends pong reply to Polyglot’s ping request. This verifies that the communication between the Node Server and Polyglot is functioning.

remove_node(node_address, timeout=None, seq=None)[source]

Removes a node from the ISY. A node cannot be removed if it is the primary node for at least one other node.

Parameters:
  • node_address (str) – The full address of the node (e.g. ‘dimmer_1’)
  • timeout (str, float, or int) – (optional) timeout (seconds) for REST call to ISY
  • seq (str or int) – (optional) set to unique id if result callback desired
report_command(node_address, command, value=None, uom=None, timeout=None, seq=None, **kwargs)[source]

Sends a command to the ISY that may be used in programs and/or scenes. A common use of this is a physical switch that somebody turns on or off. Each time the switch is used, a command should be reported to the ISY. These are used for scenes and control conditions in ISY programs.

Parameters:
  • node_address (str) – The full address of the node (e.g. ‘switch_1)
  • command (str) – The command to perform (e.g. ‘DON’, ‘CLISPH’, etc.)
  • value (str, int, or float) – Optional unnamed value the command used
  • uom (int or str) – Optional units of measurement of value
  • timeout (str, float, or int) – (optional) timeout (seconds) for REST call to ISY
  • seq (str or int) – (optional) set to unique id if result callback desired
  • <pN>.<uomN> (optional) – Nth Parameter name (e.g. ‘level’) . Unit of measure of the Nth parameter (e.g. ‘seconds’, ‘uom58’)
report_request_status(request_id, success, timeout=None, seq=None)[source]

When the ISY sends a request to the node server, the request may contain a ‘requestId’ field. This indicates to the node server that when the request is completed, it must send a fail or success report for that request. This allows the ISY to in effect, have the node server synchronously perform tasks. This message must be sent after all other messages related to the task have been sent.

For example, if the ISY sends a request to query a node, all the results of the query must be sent to the ISY before a fail/success report is sent.

Parameters:
  • request_id (str) – The request ID the ISY supplied on a request to the node server.
  • success (bool) – Indicates if the request was sucessful
  • timeout (str, float, or int) – (optional) timeout (seconds) for REST call to ISY
  • seq (str or int) – (optional) set to unique id if result callback desired
report_status(node_address, driver_control, value, uom, timeout=None, seq=None)[source]

Updates the ISY with the current value of a driver control (e.g. the current temperature, light level, etc.)

Parameters:
  • node_address (str) – The full address of the node (e.g. ‘dimmer_1’)
  • driver_control (str) – The name of the status value (e.g. ‘ST’, ‘CLIHUM’, etc.)
  • value (str, float, or int) – The numeric status value (e.g. ‘80.5’)
  • uom (int or str) – Unit of measure of the status value
  • timeout (str, float, or int) – (optional) timeout (seconds) for REST call to ISY
  • seq (str or int) – (optional) set to unique id if result callback desired
request_stats(*args, **kwargs)[source]

Sends a command to Polyglot to request a statistics message.

restcall(api, timeout=None, seq=None)[source]

Calls a RESTful api on the ISY. The api is the portion of the url after the “https://isy/rest/” prefix.

Parameters:
  • api (str) – The url for the api to call
  • timeout (str, float, or int) – (optional) timeout (seconds) for REST call to ISY
  • seq (str or int) – (optional) set to unique id if result callback desired
send_config(config_data)[source]

Update the configuration in Polyglot.

Parameters:config_data (dict) – Dictionary of updated configuration
Raises:ValueError
send_error(err_str)[source]

Enqueue an error to be sent back to Polyglot.

Parameters:err_str (str) – Error text to be sent to Polyglot log
smsg(str)[source]

Logs/sends a diagnostic/debug, informative, or error message. Individual node servers can override this method if they desire to redirect or filter these messages.

uptime

The number of sections the connection with Polyglot has been alive

Type:float
wait_for_config()[source]

Blocks the thread until the configuration is received

write_nodeserver_config(default_flow_style=False, indent=4)[source]

Writes any changes to the nodeserver custom configuration file. self.nodeserver_config should be a dictionary. Refrain from calling this in a poll of any kind. Typically you won’t even have to write this unless you are storing custom data you want retrieved on the next run. Saved automatically during normal Polyglot shutdown. Returns True for success, False for failure.

Parameters:
  • default_flow_style (boolean) – YAML’s default flow style formatting. Default False
  • indent (int) – Override the default indent spaces for YAML. Default 4
class polyglot.nodeserver_api.SimpleNodeServer(poly, shortpoll=1, longpoll=30)[source]

Simple Node Server with basic functionality built-in. This class inherits from polyglot.nodeserver_api.NodeServer and is the best starting point when developing a new node server. This class implements the idea of manifests which are dictionaries that contain the relevant information about all of the nodes. The manifest gets sent to Polyglot to be saved as part of the configuration. This allows the node server to automatically recall its last known values when it is restarted.

add_node(*args, **kwargs)[source]

Add node to the Polyglot and the nodes dictionary.

Parameters:node (polyglot.nodeserver_api.Node) – The node to add
Returns boolean:
 Indicates success or failure of node addition
exist_node(address)[source]

Check if a node exists by its address.

Parameters:address (str) – The node address
Returns bool:True if the node exists
get_node(address)[source]

Get a node by its address.

Parameters:address (str) – The node address
Returns polyglot.nodeserver_api.Node:
 If found, otherwise False
nodes = OrderedDict()

Nodes registered with this node server. All nodes are automatically added by the add_node method. The keys are the node IDs while the values are instances of polyglot.nodeserver_api.Node. Classes inheriting can access this directly, but the prefered method is by using get_node or exist_node methods.

on_add_all(*args, **kwargs)[source]

Adds all nodes to the ISY. Also sends requests reponses when necessary.

Parameters:optional request_id (str) – Status request id
Returns bool:True on success
on_added(node_address, node_def_id, primary_node_address, name)[source]

Internally indicates that the specified node has been added to the ISY.

Parameters:
  • node_address (str) – The address of the node to act on
  • node_def_id (str) – The node definition id
  • primary_node_address (str) – The node server’s primary node address
  • name (str) – The node’s friendly name
  • optional request_id (str) – Status request id
Returns bool:

True on success

on_cmd(*args, **kwargs)[source]

Runs the specified command on the specified node. Also sends requests reponses when necessary.

Parameters:
  • node_address (str) – The address of the node to act on
  • command (str) – The command to run
  • value (optional) – The value of the command’s unnamed parameter
  • uom (optional) – The units of measurement for the unnamed parameter
  • optional request_id (str) – Status request id
  • <pN>.<uomN> (optional) – The value of parameter pN with units uomN
Returns bool:

True on success

on_disabled(node_address)[source]

Received node disabled report from ISY

Parameters:node_address (str) – The address of the node to act on
Returns bool:True on success
on_enabled(node_address)[source]

Received node enabled report from ISY

Parameters:node_address (str) – The address of the node to act on
Returns bool:True on success
on_exit(*args, **kwargs)[source]

Triggers a clean shut down of the node server by saving the manifest, clearing the IO, and stopping.

Returns bool:True on success
on_query(*args, **kwargs)[source]

Queries each node and reports all control values to the ISY. Also responds to report requests if necessary.

Parameters:
  • node_address (str) – The address of the node to act on
  • optional request_id (str) – Status request id
Returns bool:

True on success

on_removed(node_address)[source]

Internally indicates that a node has been removed from the ISY.

Parameters:node_address (str) – The address of the node to act on
Returns bool:True on success
on_renamed(node_address, name)[source]

Changes the node name internally to match the ISY.

Parameters:
  • node_address (str) – The address of the node to act on
  • name (str) – The node’s friendly name
Returns bool:

True on success

on_status(*args, **kwargs)[source]

Reports the requested node’s control values to the ISY without forcing a query. Also sends requests reponses when necessary.

Parameters:
  • node_address (str) – The address of the node to act on
  • optional request_id (str) – Status request id
Returns bool:

True on success

update_config(replace_manifest=False)[source]

Updates the configuration with new node manifests and sends the configuration to Polyglot to be saved.

Parameters:replace_manifest (boolean) – replace or merge existing manifest
polyglot.nodeserver_api.auto_request_report(fun)[source]

Python decorator to automate request reporting. Decorated functions must return a boolean value indicating their success or failure. It the argument request_id is passed to the decorated function, a response will be sent to the ISY. This decorator is implemented in the SimpleNodeServer.

Nodeserver Helpers

Helper functions for managing Node Servers.

polyglot.nodeserver_helpers.available_servers()[source]

list all available elements

polyglot.nodeserver_helpers.dirs_in(path, include_path=True)[source]

Returns a list of directories in a path.

Parameters:path – The path to search.
polyglot.nodeserver_helpers.get_path(platform)[source]

Find Node Server Platform path

polyglot.nodeserver_helpers.ignore_dir(path, dir_name)[source]

Deterermine if a directory should be ignored.

Nodeserver Manager

The element management module for Polyglot

class polyglot.nodeserver_manager.NodeServer(pglot, ns_platform, profile_number, nstype, nsexe, nsname, config, sandbox, configfile=None, interface=None, mqtt_server=None, mqtt_port=None)[source]

Node Server Class

alive

Indicates if the Node Server is running.

definition

Return the server defintion from server.json

kill()[source]

Kill the node server process.

profile

Return the profile.zip data.

responding

Indicates if the Node Server is responding.

restart()[source]

restart the nodeserver

send_addall(request_id=None)[source]

Send add all request to Node Server.

send_added(node_address, node_def_id, primary_node_address, name)[source]

Send node added confirmation to Node Server.

send_cmd(node_address, command, value=None, uom=None, request_id=None, **kwargs)[source]

Send run command signal to Node Server.

send_config()[source]

Send configuration to Node Server.

send_disabled(node_address)[source]

Send node disabled confirmation to Node Server.

send_enabled(node_address)[source]

Send node enabled confirmation to Node Server.

send_exit()[source]

Send exit command to the Node Server.

send_install(profile_number=None)[source]

Send install command to Node Server.

send_params()[source]

Send parameters to Node Server.

send_ping()[source]

Send Ping request to the Node Server.

send_query(node_address, request_id=None)[source]

Send query command to Node Server.

send_removed(node_address)[source]

Send node removed confirmation to Node Server.

send_renamed(node_address, name)[source]

Send node renamed confirmation to Node Server.

send_status(node_address, request_id=None)[source]

Send status request to Node Server.

start()[source]

start the node server

class polyglot.nodeserver_manager.NodeServerManager(pglot)[source]

Node Server Manager

Parameters:

pglot – The parent Polyglot object

Variables:
  • pglot – The parent Polyglot object
  • servers – Dictionary of active Node Servers
config

Node Server configuration block.

delete(base_url)[source]

Remove a server from Polyglot.

load()[source]

Initial load of the active Node Servers

start_server(ns_platform, profile_number, nsname=None, base=None, config=None)[source]

starts a node server

unload()[source]

Unload all node servers

class polyglot.nodeserver_manager.mqttSubsystem(parent)[source]

mqttSubsystem class instantiated if interface is mqtt in server.json

Parameters:parent (polyglot.nodeserver_manager.NodeServer) – The NodeServer object that called this function
start()[source]

The client start method. Starts the thread for the MQTT Client and publishes the connected message.

stop()[source]

The client stop method. If the client is currently connected stop the thread and disconnect. Publish the disconnected message if clean shutdown.

polyglot.nodeserver_manager.random_string(length)[source]

Generate a random string of uppercase, lowercase, and digits

Utils

Generic utilities used by Polyglot.

class polyglot.utils.AsyncFileReader(fd, handler)[source]

Helper class to implement asynchronous reading of a file in a separate thread. Pushes read lines on a queue to be consumed in another thread.

Source: http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading

run()[source]

The body of the thread: read lines and put them on the queue.

class polyglot.utils.LockQueue(*args, **kwargs)[source]

Python queue with a locking utility

put(*args, **kwargs)[source]

Put item into queue

put_nowait(*args, **kwargs)[source]

Put item into queue without waiting