Metadata-Version: 2.1
Name: exoedge
Version: 18.11.17
Summary: The ExoSense Client is the Python library for interacting with Exosite's ExoSense Industrial IoT Solution.
Home-page: https://github.com/exosite/lib_exoedge_python
Author: Exosite LLC
Author-email: support@exosite.com
License: Apache 2.0
Keywords: murano exosite iot iiot gateway edge exoedge exosense
Platform: UNKNOWN
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Operating System :: POSIX :: Linux
Classifier: Topic :: System :: Operating System Kernels :: Linux
Classifier: Topic :: Software Development :: Embedded Systems
Classifier: License :: OSI Approved :: Apache Software License
Requires-Python: >= 2.7.9, <4
Requires-Dist: docopt (>=0.6.2)
Requires-Dist: pureyaml
Requires-Dist: murano-client (>=18.11.15)

ExoEdge (Python)
========================

.. image:: https://travis-ci.com/exosite/lib_exoedge_python.svg?token=tgjcyH1MG5sXqcVsD1kG&branch=master
    :target: https://travis-ci.com/exosite/lib_exoedge_python

ExoEdge is the client to `ExoSense <exosense.readme.io>`_. ExoSense provides configuration objects that conform to data schemas. ExoEdge interprets these schema-driven objects and configures industrial IoT gateways to give their data to ExoSense according to schema. In other words, ExoEdge is a schema based IIoT gateway that runs on most platforms.

ExoEdge provides functionality to interpret ExoSense data schemas and self-configure gateways. It is expected that the user will write a gateway application to leverage this library, but many use cases can be covered in very few lines of application code.

Requirements
---------------

* Python 2.7.9+, 3.4, 3.5, 3.6, 3.7

**NOTE:** In most cases, having a linux gateway is enough as long as the Python requirements are met. ExoEdge is pure-python, which means there is no need for ``gcc`` or ``python-dev`` in order to install and run it.

Getting started in 15m
-----------------------

Install ExoEdge
~~~~~~~~~~~~~~~~~

Make sure the gateway is connected to the internet before installing ExoEdge.

  .. code-block :: bash

    pip install exoedge

Start Reporting
~~~~~~~~~~~~~~~~~~

Once ExoEdge is installed, it must be started with some variant of the following ``edged`` command (pronounced edge-dee, as in 'edge daemon').

ExoEdge INI file:

.. code-block:: bash

    # edged.ini
    [device]
    murano_host = <MURANO_PRODUCT_HOST>
    murano_id = <GATEWAY_SERIAL_#>

.. code-block :: bash

    edged -i edged.ini go

The ``edged`` command has many options (run ``edged --help`` for more information), but must be running in order for data to be reported to ExoSense.

Once ``edged`` is running, set the ``config_io`` resource to the object below in the Murano Product UI:

.. code-block :: json

    {
      "channels": {
        "one": {
          "display_name": "Temperature",
          "description": "It's the temperature",
          "properties": {
            "max": 1000,
            "data_unit": "DEG_CELSIUS",
            "precision": 4,
            "data_type": "TEMPERATURE",
            "min": 0
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": false,
            "report_rate": 1000,
            "sample_rate": 1000,
            "down_sample": "ACT",
            "app_specific_config": {
              "function": "sin_wave",
              "module": "exo_simulator",
              "parameters": {
                "period": 120,
                "amplitude": 10,
                "offset": 100,
                "precision": 0
              },
              "positionals": []
            }
          }
        }
      }
    }


Verify that the device started reporting a sin wave with those characteristics.

For more information on the configuration options available in ExoEdge and ExoSense, please visit the `ExoSense documentation <exosense.readme.io>`_.

Argument Support
-----------------

The ``edged`` command supports supplying arguments via CLI flags, environment variables, and INI files.

Naming conventions differ slightly between these methods—for a generic argument
``some_argument`` they are named as follows:

* CLI: ``--some-argument``
* Environment: ``EDGED_SOME_ARGUMENT``
* INI: ``some_argument``

Argument Precedence
----------------------

In handling conflicting arguments from different sources, ``edged`` evaluates arguments in the following order:

1. CLI (overrides Environment and INI)
2. Environent (overriden by CLI, overrides INI)
3. INI (overriden by CLI and Environment)


Examples
~~~~~~~~~~

With command line arguments and a local config_io:

.. code-block :: bash

    $ edged --host=https://abcdef123456.m2.exosite.io/ -s device01.ini -c my_config.json -i device01.ini go

    ...^C

    $ cat device01.ini
    [device]
    murano_host = https://abcdef123456.m2.exosite.io/
    murano_id = device01
    murano_token = cz0wIrytgohIxa9YVxFWzsyXyeDaEexOdnYyd9mT
    watchlist = config_io,data_out,config_applications
    murano_port = 443

    [edged]
    config_io_file = my_config.json
    config_applications_file = config_applications.json


With INI file:

.. code-block :: bash

    $ cat device01.ini
    [device]
    murano_host = https://abcdef123456.m2.exosite.io/
    murano_id = device01
    debug = INFO

    $ edged -i device01.ini -c my_config.json go

**NOTE:** The ``murano_token`` option is not present in the .ini file prior to activation. If ``murano_token`` is present, the client will attempt to use
that token, even if it's blank, to communicate with Murano. The example, above, omits ``murano_token``, because it will be saved there after ``edged`` provisions with Murano.

Local or Remote Configs
------------------------

ExoEdge will always look for a local ``config_io`` file first, then check to see if there's one in ExoSense. For more information on how ``edged`` manages configs (e.g. ``config_io``, ``config_applications``, etc.), see ``edged -h``.

Creating an ExoEdge Source
----------------------------

There are two types of sources for data in ExoEdge: ones that are implemented and supported by Exosite (e.g. Modbus_TCP, Modbus_RTU, ExoSimulator, etc.), and ones that are provided by installed Python packages and modules.

Creating a "source" is as simple as writing Python package or module.

Simple Case
~~~~~~~~~~~~

The "source", above, illustrates that ExoEdge imports the ``my_source`` module and calls the function ``minutes_from_now`` with parameter ``30`` every second. This module needs to be installed like any other Python module or package (i.e. ``python setup.py install``, ``pip install my_source``, etc.).

.. code-block :: python

    # in my_source/__init__.py
    import time

    def minutes_to_seconds(min):
      return min * 60

    def minutes_from_now(minutes=0):
      # Returns the timestamp `minutes` after the current time.
      return time.time() + minutes_to_seconds(minutes)

.. code-block ::

    {
      "channels": {
        "001": {
          "display_name": "30 Minutes from Now",
          ...,
          "protocol_config": {
            "application": "Custom Application",
            "report_on_change": false,
            "report_rate": 1000,
            "sample_rate": 1000,
            "down_sample": "ACT",
            "app_specific_config": {
              "module": "my_source",
              "function": "minutes_from_now",
              "parameters": {
                "minutes": 30
              },
              "positionals": []
            }
            ...
          }
        }
      }
    }

Complex Case
~~~~~~~~~~~~~

The example, below, utilizes the ``ExoEdgeSource`` class provided by ExoEdge.

**NOTE:** Though it is not required, when using the ``ExoEdgeSource`` class you can set ``protocol_config.application`` to ``ExoSimulator``. Doing so will prevent an unecessary thread of execution from being started for the associated channel. By setting ``protocol_config.application`` to ``Custom Application`` or some other unique identifier, ExoEdge will import ``protocol_config.app_specific_config.module`` and call ``protocol_config.app_specific_config.function`` with ``protocol_config.app_specific_config.positionals`` and ``protocol_config.app_specific_config.parameters`` every ``protocol_config.sample_rate``.

.. code-block:: python

    # example_source.py

    # -*- coding: utf-8 -*-
    # pylint: disable=W1202
    import sys
    import time
    import datetime
    from exoedge.sources import ExoEdgeSource
    from exoedge import logger

    LOG = logger.getLogger(__name__)

    def sixteen():
        return 16

    class ExampleSource(ExoEdgeSource):

        def minutes_from_now(self, minutes=0.0):
            return datetime.datetime.fromtimestamp(float(minutes)*60 + time.time()).strftime('%c')

        def run(self):

            exoedge_source_channels = self.get_channels_by_application('ExoEdgeSource')
            example_source_channels = self.get_channels_by_module(__name__)

            # filter by only the channels in this example
            my_channels = list(set(exoedge_source_channels).intersection(example_source_channels))

            LOG.critical("Starting with channels: {}".format(my_channels))

            while True:

                for channel in my_channels:
                    if channel.is_sample_time():
                        func = channel.protocol_config.app_specific_config['function']
                        if hasattr(sys.modules.get(__name__), func):
                            function = getattr(sys.modules[__name__], func)
                            par = channel.protocol_config.app_specific_config['parameters']
                            pos = channel.protocol_config.app_specific_config['positionals']
                            LOG.warning("calling '{}' with: **({})"
                                        .format(function, par))
                            try:
                                channel.put_sample(function(*pos, **par))
                            except Exception as exc: # pylint: disable=W0703
                                LOG.warning("Exception".format(format_exc=exc))
                                channel.put_channel_error(exc)
                        elif hasattr(self, func):
                            function = getattr(self, func)
                            par = channel.protocol_config.app_specific_config['parameters']
                            pos = channel.protocol_config.app_specific_config['positionals']
                            LOG.warning("calling '{}' with: **({})"
                                        .format(function, par))
                            try:
                                channel.put_sample(function(*pos, **par))
                            except Exception as exc: # pylint: disable=W0703
                                LOG.warning("Exception".format(format_exc=exc))
                                channel.put_channel_error(exc)
                        else:
                            channel.put_channel_error(
                                'MySource has no function: {}'.format(func))

                time.sleep(0.01) # throttle a bit to lay off the processor

.. code-block:: json

    {
      "channels": {
        "sixteen": {
          "display_name": "The number 16, according to the example_source.",
          "protocol_config": {
            "report_on_change": false,
            "report_rate": 5000,
            "application": "ExoEdgeSource",
            "app_specific_config": {
              "function": "sixteen",
              "module": "example_source",
              "parameters": {},
              "positionals": []
            },
            "sample_rate": 5000,
            "down_sample": "ACT"
          }
        },
        "thirty_minutes_from_now": {
          "display_name": "The time, thirty minutes from now, according to the gateway.",
          "protocol_config": {
            "report_on_change": false,
            "report_rate": 5000,
            "application": "ExoEdgeSource",
            "app_specific_config": {
              "function": "minutes_from_now",
              "module": "example_source",
              "parameters": {
                "minutes": 30
              },
              "positionals": []
            },
            "sample_rate": 5000,
            "down_sample": "ACT"
          }
        }
      }
    }

For more in-depth information on creating Python modules and packages, see the docs_.

.. _docs: https://docs.python.org/2/tutorial/modules.html#packages

Passing Parameters
~~~~~~~~~~~~~~~~~~
Some application functions take keyword arguments which are passed in the parameters section of the ``app_specific_config`` object in ``config_io``. For instance, a function ``random_integer(lower=0, upper=10)`` which returns—you guessed it—a random integer between it's ``lower`` and ``upper`` keyword arguments might have a parameters section like this:

.. code-block:: json

    "parameters": {
      "lower": 100,
      "upper": 200
    }

Other application functions accept positional arguments. In this case, supply them in ``protocol_config.app_specific_config.positionals``

.. code-block:: json

    "positionals": ["arg1", "foo", 15]


Upgrades
----------

To upgrade ExoEdge, the following command should be used:

.. code-block::

    pip install exoedge --upgrade


Log Rotation
---------------

ExoEdge can be configured to save and rotate its own logs, as opposed to dumping logging to 'stdout'.

.. code-block:: bash

    # example
    $ export EDGED_LOG_FILENAME=${PWD}/edged.log
    $ edged -i f5330e5s8cho0000.ini go

Other supported environment variables for logging configuration are:

* ``EDGED_LOG_DEBUG`` (default:CRITICAL)
* ``EDGED_LOG_MAX_BYTES`` (default:1024000)
* ``EDGED_LOG_MAX_BACKUPS`` (default:3)

You might wish to save and rotate the underlying ``murano_client`` logging as well. For help on this see `murano-client <https://pypi.org/project/murano-client/#logging>`_.

A typical logging configuration for a production gateway looks like the following:

.. code-block::

    export EDGED_LOG_FILENAME=/var/log/edged.log
    export MURANO_CLIENT_LOGFILE=/var/log/murano_client.log

A typical logging configuration for a development gateway might look like:

.. code-block::

    export EDGED_LOG_FILENAME=${PWD}/edged.log
    export MURANO_CLIENT_LOGFILE=${PWD}/murano_client.log

**TIP:** If you don't care about the ``murano_client`` logging, you can use the standard redirect since ``murano_client`` defaults to logging on 'stderr':

.. code-block::

    edged -i f5330e5s8cho0000.ini go 2>/dev/null

ExoSimulator
--------------

ExoEdge has a built-in simulator with some useful features:

* Maintenance/Telemetrics
* Simulated Data

To use the simulator, simply set up ``config_io`` along these lines:

.. code-block:: json

    {
      "channels": {
        "sin_wave": {
          "display_name": "Sinusoid",
          "description": "Sinusoidal data from ExoEdge ExoSimulator.",
          "properties": {
            "max": null,
            "precision": null,
            "data_type": "NUMBER",
            "min": null
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": false,
            "report_rate": 1000,
            "sample_rate": 1000,
            "down_sample": "ACT",
            "app_specific_config": {
              "function": "sin_wave",
              "parameters": {
                "period": 60,
                "amplitude": 1,
                "offset": 0,
                "precision": 2
              },
              "positionals": []
            }
          }
        }
      }
    }

Another example using the function ``do_wave`` which supports ASDR envelope definitions:

.. code-block:: json

    {
      "channels": {
        "asdr": {
          "display_name": "ASDR",
          "description": "An ASDR simulation.",
          "properties": {
            "max": null,
            "precision": null,
            "data_type": "NUMBER",
            "min": null
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": false,
            "report_rate": 1000,
            "sample_rate": 1000,
            "down_sample": "ACT",
            "app_specific_config": {
              "function": "do_wave",
              "parameters": {
                "period": 60,
                "amplifier": {
                  "type": "lineargain",
                  "gain": -3.0,
                  "offset": 4.0
                },
                "envelope": {
                  "attack": 2,
                  "decay": 0.5,
                  "sustaint": 2.5,
                  "sustainl": 6.9,
                  "release": 7.4,
                  "gap": 5
                },
                "precision": 1
              },
              "positionals": []
            }
          }
        }
      }
    }

Another useful function is the ``ip_address`` function of the simulator:

.. code-block:: json

    {
      "channels": {
        "ip_address": {
          "display_name": "IP Address",
          "description": "The IP Address of the gateway.",
          "properties": {
            "data_type": "STRING"
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": true,
            "app_specific_config": {
              "function": "ip_address",
              "module": "exo_simulator",
              "parameters": {},
              "positionals": ["eth0"]
            }
          }
        }
      }
    }

If the ``psutil`` module is installed, there are other gateway stats that can be collected as well.

* architecture
* cpu_times_percent
* disk_stats
* machine_type
* net_io
* system_platform
* whoami

.. code-block:: JSON

   {
      "channels": {
        "architecture": {
          "display_name": "Processor Architecture",
          "description": "The Processor Architecture of the gateway.",
          "properties": {
            "data_type": "STRING"
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": true,
            "app_specific_config": {
              "function": "architecture",
              "module": "exo_simulator",
              "parameters": {},
              "positionals": []
            }
          }
        },
        "machine_type": {
          "display_name": "Machine Type",
          "description": "The Machine Type of the gateway.",
          "properties": {
            "data_type": "STRING"
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": true,
            "app_specific_config": {
              "function": "machine_type",
              "module": "exo_simulator",
              "parameters": {},
              "positionals": []
            }
          }
        },
        "system_platform": {
          "display_name": "System Platform",
          "description": "The System Platform of the gateway.",
          "properties": {
            "data_type": "STRING"
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": true,
            "app_specific_config": {
              "function": "system_platform",
              "module": "exo_simulator",
              "parameters": {},
              "positionals": []
            }
          }
        },
        "python_version": {
          "display_name": "Python Version",
          "description": "The Python Version of the gateway.",
          "properties": {
            "data_type": "STRING"
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": true,
            "app_specific_config": {
              "function": "python_version",
              "module": "exo_simulator",
              "parameters": {},
              "positionals": []
            }
          }
        },
        "whoami": {
          "display_name": "Current User",
          "description": "The Current User of the edged process.",
          "properties": {
            "data_type": "STRING"
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": true,
            "app_specific_config": {
              "function": "whoami",
              "module": "exo_simulator",
              "parameters": {},
              "positionals": []
            }
          }
        },
        "net_io": {
          "display_name": "NetIO",
          "description": "Network statistics of the gateway.",
          "properties": {
            "data_type": "JSON"
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": false,
            "sample_rate": 30000,
            "report_rate": 30000,
            "app_specific_config": {
              "function": "net_io",
              "module": "exo_simulator",
              "parameters": {},
              "positionals": []
            }
          }
        },
        "disk_stats": {
          "display_name": "Disk Stats",
          "description": "Disk usage statistics of the gateway.",
          "properties": {
            "data_type": "JSON"
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": false,
            "sample_rate": 30000,
            "report_rate": 30000,
            "app_specific_config": {
              "function": "disk_stats",
              "module": "exo_simulator",
              "parameters": {},
              "positionals": []
            }
          }
        },
        "cpu_times_percent": {
          "display_name": "CPU Stats",
          "description": "CPU usage statistics of the gateway.",
          "properties": {
            "data_type": "JSON"
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": false,
            "sample_rate": 30000,
            "report_rate": 30000,
            "app_specific_config": {
              "function": "cpu_times_percent",
              "module": "exo_simulator",
              "parameters": {
                "interval": 1
              },
              "positionals": []
            }
          }
        },
        "exoedge_version": {
          "display_name": "ExoEdge Version",
          "description": "The ExoEdge Version running on the gateway.",
          "properties": {
            "data_type": "STRING"
          },
          "protocol_config": {
            "application": "ExoSimulator",
            "report_on_change": true,
            "app_specific_config": {
              "function": "exoedge_version",
              "module": "exo_simulator",
              "parameters": {},
              "positionals": []
            }
          }
        }
      }
    }


