### Install pyhaystack from source Source: https://pyhaystack.readthedocs.io/en/latest/index.html Clone the develop branch and install pyhaystack using the setup.py script. This method is an alternative to pip installation. ```bash python setup.py install ``` -------------------------------- ### Install pyhaystack using pip Source: https://pyhaystack.readthedocs.io/en/latest/index.html Use this command to install the pyhaystack library via pip. Ensure you have pip installed. ```bash pip install pyhaystack ``` -------------------------------- ### Install pyhaystack dependencies in a virtual environment Source: https://pyhaystack.readthedocs.io/en/latest/index.html After activating a virtual environment, install necessary libraries including requests, hszinc, and pyhaystack. Avoid using sudo for pip installs within a virtual environment. ```bash pip install requests pip install hszinc pip install pyhaystack ``` -------------------------------- ### Asynchronous Exception Handling Example Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.util.html Demonstrates how to capture exceptions in an asynchronous function and pass them to a callback for later handling. ```python def _some_async_function(…, callback_fn): try: do some async op that may fail result = ... except: # Capture all exceptions result = AsynchronousException() callback_fn(result) ``` -------------------------------- ### get() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Retrieves data using the HTTP client. This is a method of the HTTPClient class. ```APIDOC ## get() ### Description Retrieves data using the HTTP client. ### Method (Method of pyhaystack.client.http.base.HTTPClient) ``` -------------------------------- ### Site entity data structure Source: https://pyhaystack.readthedocs.io/en/latest/site.html A site entity is represented as a dictionary containing its attributes and values. This example shows the typical structure for a site. ```python {'S.site': <@S.site: {area=BasicQuantity(0.0, 'ft²'), axSlotPath='slot:/site', axType='nhaystack:HSite', dis='site', geoAddr='2017', geoCity='thisTown', geoCountry='myCountry', geoLat=0.0, geoLon=0.0, geoPostalCode='', geoState='myState', geoStreet='myStreet', navName='site', site, tz='New_York'>} ``` -------------------------------- ### GetGridOperation Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.ops.html Performs a GET operation to retrieve a ZINC grid from a specified URI. ```APIDOC ## GetGridOperation ### Description A state machine that performs a GET operation then reads back a ZINC grid. It initializes a GET request for the grid with the given URI and arguments. ### Parameters * **session** (object) - Haystack HTTP session object. * **uri** (string) - Possibly partial URI relative to the server base address to perform a query. No arguments shall be given here. * **args** (dict) - Dictionary of key-value pairs to be given as arguments. * **multi_grid** (bool) - Boolean indicating if we are to expect multiple grids or not. If true, then the operation will always return a list, otherwise, it will always return a single grid. Defaults to False. * **kwargs** - Additional keyword arguments passed to the base class. ``` -------------------------------- ### HTTPClient.get Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.http.html Convenience function to perform an HTTP GET operation. ```APIDOC ## def get(uri, callback, **kwargs) ### Description Convenience function: perform a HTTP GET operation. Arguments are the same as for request. ### Parameters * **uri** (string) - URL for this request. * **callback** (function) - A callback function that will be presented with the result of this request. * **kwargs** - Additional keyword arguments passed to the `request` method. ``` -------------------------------- ### BaseGridOperation Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.ops.html A base class for GET and POST operations involving grids, inheriting from BaseAuthOperation. ```APIDOC ## BaseGridOperation ### Description A base class for GET and POST operations involving grids. It initializes a request for the grid with the given URI and arguments, and handles various aspects like expected format, multi-grid responses, and raw response handling. ### Parameters * **session** (object) - Haystack HTTP session object. * **uri** (string) - Possibly partial URI relative to the server base address to perform a query. No arguments shall be given here. * **args** (dict) - Dictionary of key-value pairs to be given as arguments. * **expect_format** (string) - Request that the grid be sent in the given format. Defaults to 'text/zinc'. * **multi_grid** (bool) - Boolean indicating if we are to expect multiple grids or not. If True, then the operation will always return a list, otherwise, it will always return a single grid. Defaults to False. * **raw_response** (bool) - Boolean indicating if we should try to parse the result. If True, then we should just pass back the raw HTTPResponse object. Defaults to False. * **retries** (int) - Number of retries permitted in case of failure. Defaults to 2. * **cache** (bool) - Whether or not to cache this result. If True, the result is cached by the session object. Defaults to False. * **cache_key** (string) - Name of the key to use when the object is cached. * **accept_status** (list) - What status codes to accept, in addition to the usual ones? * **headers** (dict) - Dictionary of custom headers to send with the request. * **exclude_cookies** (bool or list) - If True, exclude all default cookies and use only the cookies given. Otherwise, this is an iterable of cookie names to be excluded. ``` -------------------------------- ### Retrieve Entity and Get Local Timezone Source: https://pyhaystack.readthedocs.io/en/latest/his.html Retrieves a site entity and uses its local timezone to get the current and a specific time. Ensure the entity has a 'tz' tag. ```python import datetime # Retrieve a single entity, by ID op = session.get_entity('S.SERVISYS', single=True) op.wait() site = op.result # is the entity S.SERVISYS # The current time at S.SERVISYS (to the microsecond) now = datetime.datetime.now(tz=site.tz) # A specific time, at S.SERVISYS sometime = site.tz.localize(datetime.datetime(2017, 5, 7, 18, 11)) ``` -------------------------------- ### Get Certifi CA Bundle Path Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Retrieve the file path to the certifi CA certificate bundle. This path can be used to append custom trusted certificates. ```python import certifi certifi.where() ``` -------------------------------- ### Describe Pandas Series Source: https://pyhaystack.readthedocs.io/en/latest/his.html Uses the describe() method on a Pandas Series to get statistical information. ```python room_temp_serie.describe() ``` -------------------------------- ### HaystackOperation State Machine Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.util.html A base class for implementing state machines in pyhaystack. It provides methods for managing the lifecycle of an operation, including starting, checking completion, and retrieving results. ```APIDOC ## Class: HaystackOperation ### Description Base class for implementing state machines for operations. ### Initialization Subclasses should override `__init__` to accept and validate inputs, storing them as private variables. ### Methods #### go() Starts the asynchronous operation processing. #### is_done Returns `True` if the operation is complete, `False` otherwise. #### is_failed Returns `True` if the operation resulted in an exception, `False` otherwise. #### result Returns the result of the operation or raises its exception. Raises `NotReadyError` if the operation is not yet complete. #### state Returns the current state of the state machine. #### wait(timeout=None) Waits for the operation to finish. Should not be called in the same thread executing the operation to avoid deadlocks. ``` -------------------------------- ### Set up a virtual environment Source: https://pyhaystack.readthedocs.io/en/latest/index.html Commands to create and activate a Python virtual environment. This is recommended for managing dependencies and avoiding conflicts. ```bash sudo pip install virtualenv ``` ```bash mkdir your project folder cd project virtualenv venv source venv/bin/activate ``` -------------------------------- ### Initialize HaystackSession with Default HTTP Client Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Demonstrates initializing a HaystackSession using the default synchronous HTTP client. No specific http_client or http_args are needed if defaults are acceptable. ```python from pyhaystack.client.session import HaystackSession session = HaystackSession(uri="http://localhost:8080/api") ``` -------------------------------- ### Initialize HTTP Client Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Instantiate the HTTP client with a URI and optional arguments. The `debug` and `log` parameters are handled specifically, while others are passed to the underlying HTTP client class. Useful arguments include `timeout`, `proxies`, and `tls_verify`. ```python if bool(http_args.pop('debug',None)) and ('log' not in http_args): http_args['log'] = log.getChild('http_client') self._client = http_client(uri=uri, **http_args) ``` -------------------------------- ### HTTPClient Initialization Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.http.html Instantiate an HTTP client instance with default parameters. These parameters can be modified as needed. ```APIDOC ## class pyhaystack.client.http.base.HTTPClient ### Description The base HTTP client interface. This class defines methods for making HTTP requests in a unified manner. The interface presented is an asynchronous one, even for synchronous implementations. ### Parameters * **uri** (string) - Base URI for all requests. If given, this string will be pre-pended to all requests passed through this client. * **params** (dict) - A dictionary of key-value pairs to be passed as URI query parameters. * **headers** (dict) - A dictionary of key-value pairs to be passed as HTTP headers. * **cookies** (dict) - A dictionary of key-value pairs to be passed as cookies. * **auth** (HttpAuth) - An instance of a HttpAuth object. * **timeout** (int or float) - An integer or float giving the default maximum time duration for requests before timing out. * **proxies** (dict) - A dictionary mapping the hostname and protocol to a proxy server URI. * **tls_verify** (bool or string) - For TLS servers, this determines whether the server is validated or not. It should be the path to the CA certificate file for this server, or alternatively can be set to ‘True’ to verify against CAs known to the client. (e.g. OS certificate store) * **tls_cert** (string) - For TLS servers, this specifies the certificate used by the client to authenticate itself with the server. * **log** (logging object) - If not None, then it’s a logging object that will be used for debugging HTTP operations. * **insecure_requests_warning** (bool) - Controls the display of insecure requests warnings. Defaults to True. * **requests_session** (bool) - Flag to enable or disable the use of requests sessions. Defaults to True. ``` -------------------------------- ### Initialize HaystackSession with Custom HTTP Client and Args Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Shows how to initialize a HaystackSession with a custom HTTP client and pass specific arguments to its constructor. This is useful for testing or using alternative HTTP implementations. ```python from pyhaystack.client.session import HaystackSession from pyhaystack.client.http.dummy import DummyHttpClient session = HaystackSession( uri="http://localhost:8080/api", http_client=DummyHttpClient, http_args={"timeout": 5} ) ``` -------------------------------- ### GetGridOperation Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Represents an operation to get a grid. This is a class within the pyhaystack.client.ops.grid module. ```APIDOC ## GetGridOperation ### Description Represents an operation to get a grid. ### Class (class in pyhaystack.client.ops.grid) ``` -------------------------------- ### Navigate server structure with session.nav() Source: https://pyhaystack.readthedocs.io/en/latest/site.html The `session.nav()` method allows you to explore the Project Haystack server's data structure. You can navigate to specific paths by providing a `nav_id`. ```python op = session.nav() op.wait() nav = op.result print(nav) ``` ```python op = session.nav(nav_id='his:/') op.wait() nav = op.result print(nav) ``` -------------------------------- ### GetEntityOperation Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Represents an operation to get an entity. This is a class within the pyhaystack.client.ops.entity module. ```APIDOC ## GetEntityOperation ### Description Represents an operation to get an entity. ### Class (class in pyhaystack.client.ops.entity) ``` -------------------------------- ### Skyspark: Using connect() Function Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Connect to Skyspark using the `pyhaystack.connect()` function by specifying 'skyspark' as the implementation. Provide project details along with credentials. ```python import pyhaystack session = pyhaystack.connect(implementation='skyspark', uri='http://ip:port', username='user', password='my_password', project='my_project' pint=True) ``` -------------------------------- ### pyhaystack.client.loader.get_instance Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Instantiates a Project Haystack client, accepting implementation details and additional arguments. ```APIDOC ## get_instance ### Description Get an instance of a Project Haystack client. ### Signature `pyhaystack.client.loader.get_instance(_implementation_ , _*args_ , _**kwargs_)` ``` -------------------------------- ### Skyspark: Direct Session Instantiation Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Instantiate a Skyspark Haystack session directly. This requires the URI, username, password, and the project name. ```python from pyhaystack.client.skyspark import SkysparkHaystackSession session = SkysparkHaystackSession(uri='http://ip:port', username='user', password='my_password', project='my_project' pint=True) ``` -------------------------------- ### Find Equipment Synchronously Source: https://pyhaystack.readthedocs.io/en/latest/synchronous.html Locate equipment within a site using dictionary-like access with the equipment's ID, dis, or navName. The first match found will be returned. Access the list of all equipments using `site.equipments`. ```python my_equip = site['myEquip'] Reading equipments for this site... ``` ```python site.equipments # Returns a list of EquipSiteRefEntity ``` -------------------------------- ### Load Haystack Server Configuration from JSON Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Instantiate a Haystack session by loading connection details from a JSON file. Ensure the JSON file contains all necessary parameters like implementation, URI, username, and password. ```json { "implementation": "skyspark", "uri": "http://ip:port", "username": "user", "password": "password", "project": "my_project", "pint": true } ``` ```python import json import pyhaystack session = pyhaystack.connect( **json.load( open("my-haystack-server.json","r") ) ) ``` -------------------------------- ### get_instance Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Obtains an instance of a Project Haystack client, accepting implementation details and additional arguments. ```APIDOC ## get_instance ### Description Get an instance of a Project Haystack client. ### Parameters * **implementation** (string) - The name of the implementation class. * **args** - Positional arguments for the client instance. * **kwargs** - Keyword arguments for the client instance. ``` -------------------------------- ### Get Entity Operation Logic Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.ops.html This operation retrieves entity instances by ID. It prioritizes cached entities and then performs a low-level read for any missing or to-be-refreshed entities. ```python If refresh_all is False: # State: init For each entity_id in entity_ids: If entity_id exists in cache: Retrieve and store entity from cache. Add entity_id to list got_ids. For each entity_id in got_ids: Discard entity_id from entity_ids. If entity_ids is not empty: # State: read Perform a low-level read of the IDs. For each row returned in grid: If entity is not in cache: Create new Entity instances for each row returned. Else: Update existing Entity instance with new row data. Add the new entity instances to cache and store. Return the stored entities. # State: done ``` -------------------------------- ### Access Specific Tag Value Source: https://pyhaystack.readthedocs.io/en/latest/tags.html Get the value of a specific tag for an entity by accessing the `.tags` property like a dictionary, using the tag name as the key. ```python val = my_office.tags['curVal'] ``` -------------------------------- ### Accessing the first site via session property Source: https://pyhaystack.readthedocs.io/en/latest/site.html A shortcut to access the first site attached to the session. This returns a `SiteTzEntity` object. ```python # Target the first site (returns a SiteTzEntity) session.site ``` -------------------------------- ### NiagaraAXAuthenticateOperation Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.ops.vendor.html Implements the log-in procedure for Niagara AX servers. It involves an initial request to set session cookies, followed by a specific GET request to authenticate and retrieve the session cookie. ```APIDOC ## NiagaraAXAuthenticateOperation ### Description An implementation of the log-in procedure for Niagara AX. The procedure involves an initial request to set session cookies, followed by a specific GET request for authentication. ### Parameters - **session** (Haystack HTTP session object) - The session object. - **retries** (int) - Number of retries permitted in case of failure. Defaults to 0. ### Method `go()` ### Purpose Attempt to log in to the Niagara AX server. ``` -------------------------------- ### Create and Convert Pint Quantity Source: https://pyhaystack.readthedocs.io/en/latest/quantity.html Instantiate a quantity with a value and unit, then convert it to a different unit. Requires Pint to be configured. ```python from pyhaystack import Q_ temp = Q_(13,'degC') temp.to('degF') ``` -------------------------------- ### nav Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Navigates the project structure for discovery, exposing the database in a human-friendly tree or graph format. ```APIDOC ## nav ### Description Navigates the project for learning and discovery. This operation allows servers to expose the database in a human-friendly tree (or graph) that can be explored. ### Parameters * **nav_id**: Optional navigation ID to start from. * **callback**: Optional callback function. ### Parameters * **nav_id** (str) - Optional - The starting navigation ID. * **callback** (function) - Optional - Callback function. ``` -------------------------------- ### Retrieve History for a Specific Point Source: https://pyhaystack.readthedocs.io/en/latest/synchronous.html Chains the .his() function to a specific point retrieved using square bracket notation to get its history. By default, this returns a Pandas Series with today's history. ```python pcv6 = site['PCV~2d11~2d012_BVV~2d06'] zone_temp = pcv6['ZN~2dT'] zone_temp.his() # Return a Pandas Series with today's history by default. ``` -------------------------------- ### get_equip() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Retrieves equipment information. This is a method of the EquipRefMixin class. ```APIDOC ## get_equip() ### Description Retrieves equipment information. ### Method (pyhaystack.client.entity.mixins.equip.EquipRefMixin method) ``` -------------------------------- ### Configure Pint Quantity Session Source: https://pyhaystack.readthedocs.io/en/latest/quantity.html Initialize a NiagaraHaystackSession with Pint quantity support enabled. ```python session = NiagaraHaystackSession(uri='http://server', username='user', password='myComplicatedPassword', pint=True) ``` -------------------------------- ### Configure HTTP Client Arguments in HaystackSession Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Illustrates how `http_args` are handled when initializing a HaystackSession. If `http_args` is None, it defaults to an empty dictionary before being passed to the HTTP client constructor. ```python if http_args is None: http_args = {} # … etc … ``` -------------------------------- ### Niagara4: Direct Session Instantiation Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Use this approach to directly instantiate a Niagara4 Haystack session. Ensure you provide the correct URI, username, and password. ```python from pyhaystack.client.niagara import Niagara4HaystackSession session = Niagara4HaystackSession(uri='http://ip:port', username='user', password='myPassword', pint=True) ``` -------------------------------- ### get_instance() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Retrieves an instance. This function is available in multiple modules. ```APIDOC ## get_instance() ### Description Retrieves an instance. ### Method (in module pyhaystack.client) (in module pyhaystack.client.loader) ``` -------------------------------- ### Make an 'about' request to the server Source: https://pyhaystack.readthedocs.io/en/latest/site.html Use the `session.about()` method to query basic information about the Haystack server. The result is a `hszinc.Grid` instance containing server details. ```python op = session.about() op.wait() ``` -------------------------------- ### Import hszinc and SkysparkHaystackSession Source: https://pyhaystack.readthedocs.io/en/latest/index.html Demonstrates how to import the hszinc library and the SkysparkHaystackSession class from pyhaystack. These are essential for interacting with Haystack data. ```python import hszinc hszinc.MODE_ZINC from pyhaystack.client.skyspark import SkysparkHaystackSession ``` -------------------------------- ### VRT Widesky: Direct Session Instantiation Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Directly create a session for VRT Widesky. This method requires a specific URI format and OAuth2 credentials, along with optional impersonation. ```python from pyhaystack.client.widesky import WideskyHaystackSession session = WideskyHaystackSession( uri='https://yourtenant.on.widesky.cloud/reference', username='user', password='my_password', client_id='my_id', client_secret='my_secret' pint=True, impersonate='user_id') ``` -------------------------------- ### HaystackSession Initialization Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Initializes a base Project Haystack session handler with various configuration options. ```APIDOC ## HaystackSession ### Description The Haystack Session handler is responsible for presenting an API for querying and controlling a Project Haystack server. ### Parameters * **uri** (string) - Base URI for the Haystack installation. * **api_dir** (string) - Subdirectory relative to URI where API calls are made. * **grid_format** (string) - What format to use for grids in GET/POST requests? Defaults to 'text/zinc'. * **http_client** (class) - HTTP client class to use. Defaults to SyncHttpClient. * **http_args** (dict) - Optional HTTP client arguments to configure. * **tagging_model** (class) - Entity Tagging model in use. Defaults to HaystackTaggingModel. * **log** (object) - Logging object for reporting messages. * **pint** (bool) - Configure hszinc to use basic quantity or Pint Quantity. Defaults to False. * **cache_expiry** (float) - Number of seconds before cached data expires. Defaults to 3600.0. ``` -------------------------------- ### Retrieving all sites from session Source: https://pyhaystack.readthedocs.io/en/latest/site.html Access all sites attached to the session. This returns a dictionary containing all site entities. ```python # Get a dict with all sites session.sites ``` -------------------------------- ### Niagara AX: Direct Session Instantiation Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Instantiate a Niagara AX Haystack session directly. This requires the URI, username, and password for authentication. ```python from pyhaystack.client.niagara import NiagaraHaystackSession session = NiagaraHaystackSession(uri='http://ip:port', username='user', password='myPassword', pint=True) ``` -------------------------------- ### Session.nav() Source: https://pyhaystack.readthedocs.io/en/latest/site.html Navigates the structure of the Project Haystack server. It can be called with an optional `nav_id` to explore specific parts of the server's hierarchy. ```APIDOC ## Session.nav() ### Description Navigates the structure of the Project Haystack server. ### Method This is a client-side method call, not an HTTP method. ### Endpoint N/A (Client-side method) ### Parameters - **nav_id** (Str) - Optional. The identifier for the navigation level to explore. ### Request Example ```python # To get the top-level navigation op = session.nav() op.wait() nav = op.result print(nav) # To navigate to a specific path, e.g., 'his:/' op = session.nav(nav_id='his:/') op.wait() nav = op.result print(nav) ``` ### Response #### Success Response Returns a `hszinc.Grid` instance representing the navigation structure. - **dis** (Str) - Display name of the navigation item. - **navId** (Str) - The identifier for the navigation item. - **stationName** (Str) - Name of the station (if applicable). #### Response Example ``` Columns: dis navId Row 0: dis='ComponentSpace', navId='slot:/' Row 1: dis='HistorySpace', navId='his:/' Row 2: dis='Site', navId='sep:/' ``` ``` Columns: dis stationName navId Row 0: dis='mySite', stationName='mySite', navId='his:/mySite' ``` ``` -------------------------------- ### Session.about() Source: https://pyhaystack.readthedocs.io/en/latest/site.html Queries basic information about the Haystack server. It returns a single row grid with details about the server's Haystack version, timezone, name, time, and product information. ```APIDOC ## Session.about() ### Description Queries basic information about the server. ### Method This is a client-side method call, not an HTTP method. ### Endpoint N/A (Client-side method) ### Parameters None ### Request Example ```python op = session.about() op.wait() ``` ### Response #### Success Response Returns a `hszinc.Grid` instance containing server information. - **haystackVersion** (Str) - Version of REST implementation, must be “2.0” - **tz** (Str) - Server’s default timezone - **serverName** (Str) - Name of the server or project database - **serverTime** (DateTime) - Current DateTime of server’s clock - **serverBootTime** (DateTime) - DateTime when server was booted up - **productName** (Str) - Name of the server software product - **productUri** (Uri) - Uri of the product’s web site - **productVersion** (Str) - Version of the server software product - **moduleName** (Str) - Module which implements Haystack server protocol if it's a plug-in to the product - **moduleVersion** (Str) - Version of moduleName #### Response Example ``` Columns: productName moduleName productVersion serverTime tz moduleUri serverName productUri serverBootTime haystackVersion moduleVersion Row 0: productName='Niagara AX', moduleName='nhaystack', productVersion='3.8.41.2', serverTime=datetime.datetime(2016, 4, 28, 21, 31, 33, 882000, tzinfo=), tz='Montreal', moduleUri=Uri('https://bitbucket.org/jasondbriggs/nhaystack'), serverName='Servisys', productUri=Uri('http://www.tridium.com/'), serverBootTime=datetime.datetime(2016, 4, 5, 15, 9, 8, 119000, tzinfo=), haystackVersion='2.0', moduleVersion='1.2.5.18.1' ``` ``` -------------------------------- ### pyhaystack.client.loader.get_implementation Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Retrieves a Project Haystack session manager implementation based on the provided class name. ```APIDOC ## get_implementation ### Description Get an implementation of Project Haystack session manager based on the class name. ### Signature `pyhaystack.client.loader.get_implementation(_implementation_)` ``` -------------------------------- ### get_implementation Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Retrieves an implementation of a Project Haystack session manager based on the provided class name. ```APIDOC ## get_implementation ### Description Get an implementation of Project Haystack session manager based on the class name. ### Parameters * **implementation** (string) - The name of the implementation class. ``` -------------------------------- ### Dynamically Configure Pint Quantity Source: https://pyhaystack.readthedocs.io/en/latest/quantity.html Modify the Pint quantity setting for an existing session. Use False to disable or True to enable. ```python session.config_pint(False) # or True ``` -------------------------------- ### go() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Executes an operation. This method is part of several operation classes. ```APIDOC ## go() ### Description Executes an operation. ### Method (pyhaystack.client.entity.ops.crud.EntityTagUpdateOperation method) (pyhaystack.client.ops.entity.FindEntityOperation method) (pyhaystack.client.ops.entity.GetEntityOperation method) (pyhaystack.client.ops.grid.BaseAuthOperation method) (pyhaystack.client.ops.his.HisReadFrameOperation method) (pyhaystack.client.ops.his.HisReadSeriesOperation method) (pyhaystack.client.ops.his.HisWriteFrameOperation method) (pyhaystack.client.ops.his.HisWriteSeriesOperation method) (pyhaystack.client.ops.vendor.niagara.NiagaraAXAuthenticateOperation method) (pyhaystack.client.ops.vendor.skyspark.SkysparkAuthenticateOperation method) (pyhaystack.client.ops.vendor.widesky.CreateEntityOperation method) (pyhaystack.client.ops.vendor.widesky.WideSkyPasswordChangeOperation method) (pyhaystack.client.ops.vendor.widesky.WideskyAuthenticateOperation method) (pyhaystack.util.state.HaystackOperation method) ``` -------------------------------- ### about Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Retrieve the version information of this Project Haystack server. ```APIDOC ## about ### Description Retrieve the version information of this Project Haystack server. ### Parameters * **cache** (bool) - Whether to use cached data. Defaults to True. * **callback** (callable) - Asynchronous result callback. ``` -------------------------------- ### config_pint() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Configures pint units for the Haystack session. ```APIDOC ## config_pint() ### Description Configures pint units for the Haystack session. ### Method (Not specified, likely a method call on a HaystackSession object) ### Endpoint (Not applicable for SDK methods) ### Parameters (No parameters specified) ### Request Example ```python session.config_pint() ``` ### Response (Response details not specified in the source) ``` -------------------------------- ### sites Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Helper to retrieve all sites found on the server. ```APIDOC ## sites ### Description This helper will return all sites found on the server. ### Method GET ### Endpoint /api/nav/?navId=sites ### Response #### Success Response (200) Returns a list of all site entities found. ``` -------------------------------- ### Niagara4: Using connect() Function Source: https://pyhaystack.readthedocs.io/en/latest/connect.html This method uses the `pyhaystack.connect()` function to establish a connection to Niagara4. Specify 'n4' as the implementation. ```python import pyhaystack session = pyhaystack.connect(implementation='n4', uri='http://ip:port', username='user', password='myPassword', pint=True) ``` -------------------------------- ### Access Site Tags Synchronously Source: https://pyhaystack.readthedocs.io/en/latest/synchronous.html Retrieve specific tags from a site object using dictionary-like access. Ensure the session is created and the site object is defined. ```python site ['area'] # Returns BasicQuantity(0.0, 'ft²') ``` -------------------------------- ### Niagara AX: Using connect() Function Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Connect to Niagara AX using the `pyhaystack.connect()` function by specifying 'ax' as the implementation. Provide necessary authentication details. ```python import pyhaystack session = pyhaystack.connect(implementation='ax', uri='http://ip:port', username='user', password='myPassword', pint=True) ``` -------------------------------- ### site Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Helper to retrieve the first site found on the server, typically representing the single site on a server. ```APIDOC ## site ### Description This helper will return the first site found on the server. This case is typical: having one site per server. ### Method GET ### Endpoint /api/nav/?navId=site ### Response #### Success Response (200) Returns the first site entity found. ``` -------------------------------- ### Find Points Under Equipment Synchronously Source: https://pyhaystack.readthedocs.io/en/latest/synchronous.html Access points associated with an equipment using dictionary-like syntax. This populates a list under `equip.points` for rapid iteration without needing to poll the server. ```python zone_temp = my_equip['ZN~2dT'] Reading points for this equipment... ``` ```python equip.points ``` -------------------------------- ### get_implementation() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Retrieves the implementation details. This function is available in multiple modules. ```APIDOC ## get_implementation() ### Description Retrieves the implementation details. ### Method (in module pyhaystack.client) (in module pyhaystack.client.loader) ``` -------------------------------- ### about() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Retrieves information about the Haystack session. ```APIDOC ## about() ### Description Retrieves information about the Haystack session. ### Method (Not specified, likely a method call on a HaystackSession object) ### Endpoint (Not applicable for SDK methods) ### Parameters (No parameters specified) ### Request Example ```python session.about() ``` ### Response (Response details not specified in the source) ``` -------------------------------- ### create() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Creates a new entity using CRUD operations. ```APIDOC ## create() ### Description Creates a new entity using CRUD operations. ### Method (Not specified, likely a method call on a CRUDOpsMixin object) ### Endpoint (Not applicable for SDK methods) ### Parameters (No parameters specified) ### Request Example ```python crud_mixin.create(...) ``` ### Response (Response details not specified in the source) ``` -------------------------------- ### Filter Builder Usage for Finding Points Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.util.html Shows how to use the filter builder to construct queries for finding points, including historical points and points with specific timezones. ```python from pyhaystack.util import filterbuilder as fb # Get all historical points: session.find_points(fb.Field('his')) ``` ```python # All historical points in Brisbane timezone. session.find_points(fb.Field('his') & ( fb.Field('tz') == fb.Scalar('Brisbane') )) ``` -------------------------------- ### Access Units Metadata from History Series Source: https://pyhaystack.readthedocs.io/en/latest/synchronous.html Demonstrates how to access the metadata, specifically the units, associated with a historical data Series. This is helpful for understanding the physical quantities represented in the data. ```python room_temp_serie.meta['units'] ``` -------------------------------- ### authenticate Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Authenticate with the Project Haystack server. ```APIDOC ## authenticate ### Description Authenticate with the Project Haystack server. If an authentication attempt is in progress, we return it, otherwise we instantiate a new one. ### Parameters * **callback** (callable) - Asynchronous result callback. ``` -------------------------------- ### Add a New Tag Source: https://pyhaystack.readthedocs.io/en/latest/tags.html Demonstrates how to add a new tag with a quantity and unit. This change is held in memory until committed. ```python znt.tags['space'] = hszinc.Quantity(4, 'm²') ``` -------------------------------- ### config_pint Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Configure the use of Pint Quantity. ```APIDOC ## config_pint ### Description Configure hszinc to use basic quantity or Pint Quantity. ### Parameters * **value** (bool) - Whether to use Pint Quantity. Defaults to False. ``` -------------------------------- ### SiteMixin Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.entity.mixins.html A mix-in for entities carrying the 'site' marker tag, providing methods to retrieve associated equipment and refresh local lists. ```APIDOC ## SiteMixin ### Description A mix-in used for entities that carry the ‘site’ marker tag. ### Methods #### `equipments` (property) site.equipments returns the list of equipments under a site. First read will force a request and create local list. #### `find_entity(filter_expr=None, single=False, limit=None, callback=None)` Retrieve the entities that are linked to this site. This is a convenience around the session find_entity method. #### `refresh()` Re-create local list of equipments. ``` -------------------------------- ### formats Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Retrieve the grid formats supported by this Project Haystack server. ```APIDOC ## formats ### Description Retrieve the grid formats supported by this Project Haystack server. ### Parameters * **cache** (bool) - Whether to use cached data. Defaults to True. * **callback** (callable) - Asynchronous result callback. ``` -------------------------------- ### VRT Widesky: Using connect() Function Source: https://pyhaystack.readthedocs.io/en/latest/connect.html Use the `pyhaystack.connect()` function with 'widesky' implementation for VRT Widesky connections. This includes OAuth2 details and optional impersonation. ```python import pyhaystack session = pyhaystack.connect(implementation='widesky', uri='https://yourtenant.on.widesky.cloud/reference', username='user', password='my_password', client_id='my_id', client_secret='my_secret', pint=True, impersonate='user_id') ``` -------------------------------- ### HTTPClient.request Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.http.html Perform a generic HTTP request with customizable parameters. ```APIDOC ## def request(method, uri, callback, body=None, params=None, headers=None, cookies=None, auth=None, timeout=None, proxies=None, tls_verify=None, tls_cert=None, exclude_params=None, exclude_headers=None, exclude_cookies=None, exclude_proxies=None, accept_status=None) ### Description Perform a request with this client. Most parameters here exist to either add to or override the defaults given by the client attributes. The parameters exclude_… serve to allow selective removal of defaults. ### Parameters * **method** (string) - The HTTP method to request. * **uri** (string) - URL for this request. If this is a relative URL, it will be relative to the URL given by the ‘uri’ attribute. * **callback** (function) - A callback function that will be presented with the result of this request. * **body** (any) - An optional body for the request. * **params** (dict) - A dictionary of key-value pairs to be passed as URI query parameters. * **headers** (dict) - A dictionary of key-value pairs to be passed as HTTP headers. * **cookies** (dict) - A dictionary of key-value pairs to be passed as cookies. * **auth** (HttpAuth) - An instance of a HttpAuth object. * **timeout** (int or float) - An integer or float giving the default maximum time duration for requests before timing out. * **proxies** (dict) - A dictionary mapping the hostname and protocol to a proxy server URI. * **tls_verify** (bool or string) - For TLS servers, this determines whether the server is validated or not. It should be the path to the CA certificate file for this server, or alternatively can be set to ‘True’ to verify against CAs known to the client. (e.g. OS certificate store) * **tls_cert** (string) - For TLS servers, this specifies the certificate used by the client to authenticate itself with the server. * **exclude_params** (list) - A list of parameter keys to exclude from the request. * **exclude_headers** (list) - A list of header keys to exclude from the request. * **exclude_cookies** (list) - A list of cookie keys to exclude from the request. * **exclude_proxies** (list) - A list of proxy keys to exclude from the request. * **accept_status** (list) - A list of HTTP status codes that are considered successful. ``` -------------------------------- ### formats() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Retrieves available data formats from the Haystack session. ```APIDOC ## formats() ### Description Retrieves available data formats from the Haystack session. ### Method (Not specified, likely a method call on a HaystackSession object) ### Endpoint (Not applicable for SDK methods) ### Parameters (No parameters specified) ### Request Example ```python session.formats() ``` ### Response (Response details not specified in the source) ``` -------------------------------- ### create_entity() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Creates an entity with tags. ```APIDOC ## create_entity() ### Description Creates an entity with tags. ### Method (Not specified, likely a method call on a TaggingModel or CRUDOpsMixin object) ### Endpoint (Not applicable for SDK methods) ### Parameters (No parameters specified) ### Request Example ```python model.create_entity(...) crud_mixin.create_entity(...) ``` ### Response (Response details not specified in the source) ``` -------------------------------- ### EquipRefMixin Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.entity.mixins.html A mix-in for entities with an 'equipRef' reference tag, providing a method to retrieve the associated equipment instance. ```APIDOC ## EquipRefMixin ### Description A mix-in used for entities that carry an ‘equipRef’ reference tag. ### Methods #### `get_equip(callback=None)` Retrieve an instance of the equip this entity is linked to. ``` -------------------------------- ### get_site() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Retrieves site information. This is a method of the SiteRefMixin class. ```APIDOC ## get_site() ### Description Retrieves site information. ### Method (pyhaystack.client.entity.mixins.site.SiteRefMixin method) ``` -------------------------------- ### PostGridOperation Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.ops.html Performs a POST operation with a ZINC grid to a specified URI, potentially reading back a ZINC grid. ```APIDOC ## PostGridOperation ### Description A state machine that performs a POST operation with a ZINC grid then may read back a ZINC grid. It initializes a POST request for the grid with the given grid, URI and arguments. ### Parameters * **session** (object) - Haystack HTTP session object. * **uri** (string) - Possibly partial URI relative to the server base address to perform a query. No arguments shall be given here. * **grid** (object) - Grid (or grids) to be posted to the server. * **args** (dict) - Dictionary of key-value pairs to be given as arguments. * **post_format** (string) - What format to post grids in? Defaults to 'text/zinc'. * **kwargs** - Additional keyword arguments passed to the base class. ``` -------------------------------- ### Retrieve Room Temperature Sensors History as DataFrame Source: https://pyhaystack.readthedocs.io/en/latest/synchronous.html Fetches all room temperature sensors and their historical data for 'today' into a Pandas DataFrame. Use this to analyze time-series data for multiple sensors simultaneously. ```python room_temp_sensors = session.find_entity(filter_expr='sensor and zone and temp').result room_temp_sensors_df = session.his_read_frame(room_temp_sensors, rng= 'today').result room_temp_sensors_df.tail() ``` -------------------------------- ### watch_sub Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Creates a new watch subscription for a list of points. ```APIDOC ## watch_sub ### Description Creates a new watch with a debug string, identifier, and lease time. Points can be specified as strings, Entity objects, or hszinc.Ref objects. ### Parameters * **points**: A list of points (strings, Entity objects, or hszinc.Ref objects) to subscribe to. * **watch_id**: Optional string identifier for the watch. * **watch_dis**: Optional debug string for the watch. * **lease**: Optional integer lease time in seconds. * **callback**: Optional callback function. ### Parameters * **points** (list) - Required - List of points to subscribe to. * **watch_id** (str) - Optional - Identifier for the watch. * **watch_dis** (str) - Optional - Debug string for the watch. * **lease** (int) - Optional - Lease time in seconds. * **callback** (function) - Optional - Callback function. ``` -------------------------------- ### SkysparkHaystackSession Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Initializes a Skyspark Project Haystack session handler. Supports authentication and basic session management. ```APIDOC ## SkysparkHaystackSession ### Description Initialise a Skyspark Project Haystack session handler. ### Parameters * **uri** (string) - Base URI for the Haystack installation. * **username** (string) - Authentication user name. * **password** (string) - Authentication password. * **project** (string) - Skyspark project name ### Methods #### is_logged_in() Return true if the user is logged in. ``` -------------------------------- ### get_entity Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.html Retrieve instances of entities, possibly refreshing them. ```APIDOC ## get_entity ### Description Retrieve instances of entities, possibly refreshing them. ### Parameters * **ids** (string or list) - A single entity ID, or a list of entity IDs. * **refresh** (bool) - Do we refresh the tags on those entities? Defaults to False. * **single** (bool) - Are we expecting a single entity? Defaults to True if ids is not a list. * **callback** (callable) - Asynchronous result callback. ``` -------------------------------- ### authenticate() Source: https://pyhaystack.readthedocs.io/en/latest/genindex.html Authenticates the Haystack session. ```APIDOC ## authenticate() ### Description Authenticates the Haystack session. ### Method (Not specified, likely a method call on a HaystackSession object) ### Endpoint (Not applicable for SDK methods) ### Parameters (No parameters specified) ### Request Example ```python session.authenticate() ``` ### Response (Response details not specified in the source) ``` -------------------------------- ### SkysparkAuthenticateOperation Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.ops.vendor.html Implements the log-in procedure for SkySpark servers. This involves retrieving a login URL, calculating a MAC and digest using provided credentials, and POSTing to the login URL to establish a session. ```APIDOC ## SkysparkAuthenticateOperation ### Description An implementation of the log-in procedure for Skyspark. This involves retrieving a login URL, calculating authentication credentials (MAC and digest), and POSTing them to the login URL. ### Parameters - **session** (Haystack HTTP session object) - The session object. - **retries** (int) - Number of retries permitted in case of failure. Defaults to 2. ### Method `go()` ### Purpose Attempt to log in to the Skyspark server. ``` -------------------------------- ### EquipMixin Source: https://pyhaystack.readthedocs.io/en/latest/pyhaystack.client.entity.mixins.html A mix-in for entities carrying the 'equip' marker tag, providing methods to find related entities and manage local lists of points and equipment. ```APIDOC ## EquipMixin ### Description A mix-in used for entities that carry the ‘equip’ marker tag. ### Methods #### `find_entity(filter_expr=None, limit=None, single=False, callback=None)` Retrieve the entities that are linked to this equipment. This is a convenience around the session find_entity method. #### `points` (property) First call will force reading of points and create local list. #### `refresh()` Re-create local list of equipments. ``` -------------------------------- ### Find Entities Using Filter Synchronously Source: https://pyhaystack.readthedocs.io/en/latest/synchronous.html Use the bracket syntax to find entities beyond tags, equipment, or points by leveraging `find_entity`. The search context is sensitive, operating under the current site or equipment. ```python air_sensors = my_equip['sensor and air'] # Returns all the points corresponding to this search. ```