Metadata-Version: 2.4
Name: thingsboard-endpoint
Version: 1.0.0
Summary: ThingsBoard endpoint package
Home-page: https://gitlab.com/things-board
Author: HES-SO Valais, School of Engineering, Sion
Author-email: thomas.sterren@hes-so.ch
License-Expression: MIT
Project-URL: Bug Tracker, https://gitlab.com/things-board/thingsboard-endpoint/-/issues
Project-URL: Source Code, https://gitlab.com/things-board/thingsboard-endpoint
Project-URL: Documentation, https://gitlab.com/things-board/thingsboard-endpoint#thingsboard-endpoint
Keywords: ThingsBoard endpoint library
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Information Technology
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Requires-Python: >=3.13
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: thingsboard-common~=1.0.0
Requires-Dist: tb-mqtt-client~=1.13.14
Requires-Dist: tb-paho-mqtt-client~=2.1.2
Requires-Dist: configobj~=5.0.9
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: home-page
Dynamic: keywords
Dynamic: license-file
Dynamic: project-url
Dynamic: requires-dist
Dynamic: summary

# ThingsBoard Endpoint

> Note: 
> 
> This is not an official project of the [ThingsBoard](https://thingsboard.io/) authors! Please refer to 
> [ThingsBoard - Open-source IoT Platform](https://github.com/thingsboard) for official ThingsBoard projects!

The ThingsBoard Endpoint package adds a data Meta-Model to the ThingsBoard devices sending data over MQTT. This 
allows to provide a common data model for each device type.

The devices providing telemetry and attributes information to ThingsBoard are named **Endpoint**s to remove confusion 
added when using names like _clients_ or _devices_. 

## Endpoint Data Meta-Model
The object meta-structure is given as follows: 
 - An EndPoint can have Nodes
 - Nodes can have Objects
 - Objects can have Objects and/or Attributes

The [Attribute](https://gitlab.com/things-board/thingsboard-endpoint/-/blob/main/src/thingsboard/endpoint/attribute/attribute.py) objects represent the leafs in the data structure. 

An `Attribute` is responsible to synchronise a variable or an attribute to the cloud. Depending on the write policy the
attribute may be changed from the cloud in which case the attribute gets updated on the endpoint.

To set up your endpoint data model you should first think about how you would like to show up your IoT device in the 
cloud, keeping in mind the _EndPoint->Node->Object->Attribute_ meta-structure implied.

We encourage you to provide the data model using an [XML](https://en.wikipedia.org/wiki/XML) or 
[JSON](https://en.wikipedia.org/wiki/JSON) based file. The file needs then to be parsed and the Endpoint's object 
structure set up accordingly. There are [Factory](https://gitlab.com/things-board/thingsboard-endpoint/-/tree/main/src/thingsboard/endpoint/factory)
classes provided to simplify this process (XML only for the moment). The `Factory` class reads a data model file and 
creates the Endpoint object.

## Quick start
Install the package (Python 3.13 or later): `pip install thingsboard-endpoint`. Create the properties file
`~/.config/thingsboard/MyEndpoint.properties` (the name is the one you give to `Endpoint(...)`, also searched in
`/etc/thingsboard/`; see [tests/crazyfrog/config](tests/crazyfrog/config/thingsboard/CrazyFrogEndpoint-template.properties)
for a template with all the options). The mandatory entries are the broker and the access token of the ThingsBoard
device. The `port` is 8883 (TLS) unless you say otherwise, and the endpoint checks that the file named by
`thingsboard-server-tls-cert`, if you set it, exists. Without TLS:

```properties
host=thingsboard.example.com
port=1883
device-access-token="the access token of the device"
```

A publisher that sends a value every second and tells what happens to the connection:

```python
import logging
import time

from thingsboard.endpoint.endpoint import Endpoint
from thingsboard.endpoint.exception.endpoint_offline_error import EndpointOfflineError
from thingsboard.endpoint.interface import EndpointListener
from thingsboard.endpoint.runtime import RuntimeNode, RuntimeObject

logging.basicConfig(level=logging.INFO)


class MyListener(EndpointListener):
    """Told what happens to the connection and to the values. Called on the worker thread: do not block."""

    def on_connected(self):
        logging.info('Connected')

    def on_disconnected(self):
        logging.warning('Connection lost')

    def on_publish_failed(self, key, timestamp, value, reason, will_retry):
        logging.warning('%s=%r was not sent: %s (%s)', key, value, reason, 'will retry' if will_retry else 'gone')


# 1. The data model: Endpoint -> Node -> Object -> Attribute
node = RuntimeNode()
sensors = RuntimeObject()
node.add_object('sensors', sensors)
temperature = sensors.add_attribute('temperature', float, 'measure')    # Sent to the cloud when it is set

# 2. The endpoint: reads the properties file, does not connect yet
endpoint = Endpoint('MyEndpoint')
endpoint.add_node('MyNode', node)
endpoint.add_listener(MyListener())

# 3. Connect (raises the exception of the MQTT client, e.g. ConnectionRefusedError, if the broker is not reachable)
endpoint.start()
endpoint.wait_until_online(timeout=30)                  # Raises TimeoutError

# 4. Set values: the endpoint sends them in the background
try:
    while True:
        try:
            temperature.set_value(21.5)                 # Telemetry 'MyNode/sensors/temperature' and a client attribute
        except EndpointOfflineError:
            logging.warning('Offline: the value is not sent')   # Only with the persistence 'none', the default
        time.sleep(1)
except KeyboardInterrupt:
    pass
finally:
    endpoint.shutdown()                                 # 5. Stops the threads and the MQTT client
```

The `constraint` of an attribute says what it is: a `measure` or a `status` is set by the endpoint; a `parameter` (kept
by the endpoint) and a `setpoint` (may be reset at the next power cycle) can be changed from the cloud, and the
`AttributeListener`s registered with `attribute.add_listener()` are told; a `static` value does not change. The sections
below say what each step does in detail.
A complete, runnable example with every feature is in [tests/crazyfrog](#running-the-crazyfrog-example).

### What happens when something goes wrong
| What happens                                          | The library                                                                       |
|-------------------------------------------------------|-----------------------------------------------------------------------------------|
| The properties file or `host` is missing, a property is invalid | **raises** `EndpointConfigurationError` from `Endpoint(...)`            |
| The broker cannot be reached by `start()`             | **raises** the exception of the MQTT client; nothing is left running, call `start()` again |
| The endpoint is not online after `wait_until_online(timeout)` | **raises** `TimeoutError`                                                 |
| A value is set while offline, persistence `none`      | **raises** `EndpointOfflineError` from `set_value()` / `set_values()`             |
| A value is set while offline, persistence `memory` or `file` | **stores** it, sends it when the connection is back (oldest first)         |
| The connection is lost                                | **reconnects** by itself with a growing pause; the listener gets `on_disconnected`, then `on_connected` |
| A send fails while connected                          | **retries**, in order, with a pause that grows to 60 s; the listener gets `on_publish_failed(will_retry=True)` |
| A value is sent but not acknowledged when the connection is lost | **stores** it (persistence `memory`/`file`) or **drops** it and reports it with `will_retry=False` |
| The queue is full (`maxQueueSize`)                    | **drops** the oldest value, counts it in `dropped_count`, reports `will_retry=False` |
| A payload can never be sent (not valid JSON)          | **drops** it, logs it, reports `will_retry=False`                                 |
| The worker thread dies (it should not)                | `is_online()` is `False`, so `set_value()` raises (persistence `none`); a `ThreadMonitor` reports it |
| `shutdown()`                                          | stores what is queued (persistence) or **drops** it and reports it with `on_publish_failed` |

## Starting, reconnecting and stopping
`Endpoint(...)` only reads the configuration: it does not connect and starts no thread, so building the endpoint and
its model never waits for the broker. Add the nodes, then connect:

```python
endpoint = Endpoint('MyEndpoint')
endpoint.add_node('MyNode', node)
endpoint.add_listener(listener)
endpoint.start()                # connects, starts the worker and the reconnect supervisor
endpoint.wait_until_online()
```

 - **`start()`** announces the nodes added before it. If the broker cannot be reached it raises the exception of the 
   MQTT client (e.g. `ConnectionRefusedError`) and leaves nothing running: call it again to retry, no need to rebuild 
   the endpoint (a node can belong to one endpoint only).
 - **`reconnect()`** rebuilds the connection in place: nodes and attributes are kept. The connection is dropped first, so queued 
   values are treated as for any lost connection: kept in the persistence and sent afterwards if there is one, else 
   dropped (and reported).
 - **`shutdown()`** stops the supervisor, the worker and the MQTT client. Values still queued or not acknowledged are 
   stored in the persistence if there is one, else dropped; the listeners are told with `on_publish_failed`. It is safe 
   on an endpoint that was never started, whose worker died, and when called twice. `close()` is the same; `start()` 
   after it starts the endpoint again.

## Connection and worker resilience
An `Endpoint` runs two threads:
 - the **worker**, which sends the values to the cloud and processes what comes back. A failing send, or a bad 
   incoming message, ends one pass of its loop, not the thread: the failure is logged and the worker tries again after
   a pause that grows while the failures last (2 s at first, 60 s at most). The value whose send failed stays at the
   front of the queue, so the values reach the cloud in the order they were set, each with the timestamp it was set 
   with. A message that can never be sent (e.g. a payload that is not valid JSON) is logged and dropped.
   Setting a new value ends the pause, so a value is never held back by it: while sends keep failing, there is one 
   attempt per value set.
 - the **reconnect supervisor**, which keeps the MQTT connection up. It runs apart from the worker, so a stuck worker 
   does not prevent reconnection (paho does not reliably reconnect after a clean DISCONNECT from the broker).

While there is no connection, the values are stored in the persistence store, if there is one (see 
[Persistence](#persistence)); when the connection is back they are sent first, oldest first. Without persistence
(`none`, the default) they are not stored: see [Errors and limits](#errors-and-limits).

`Endpoint.is_online()` is `True` when a value set now will be sent: the client is connected, the endpoint is ready 
and the worker thread is alive.

Pass a `thingsboard.common.core.thread_monitor.ThreadMonitor` as `Endpoint(..., thread_monitor=monitor)` to register 
both threads (named `<uuid>` and `<uuid>-reconnect`); `monitor.check()` then reports a dead or stalled one.

### Reconnect properties
Optional entries of the endpoint `.properties` file, in seconds. The reconnect supervisor rebuilds the MQTT client
and gives the broker `connectGraceSeconds` to answer; if it does not, that attempt has failed. After a failed attempt
it pauses, then tries again. The pause starts at `reconnectMinDelay` and doubles after each failed attempt up to
`reconnectMaxDelay`; each pause is shortened by a random share of at most 25 %, so that many endpoints do not retry in
lockstep. The first attempt after a lost connection starts at once.

| Property                                   | Default | Meaning                                                                |
|--------------------------------------------|---------|------------------------------------------------------------------------|
| `thingsboard.endpoint.reconnectMinDelay`   | `5`     | The pause after the first failed attempt                               |
| `thingsboard.endpoint.reconnectMaxDelay`   | `120`   | The longest pause (not smaller than `reconnectMinDelay`)               |
| `thingsboard.endpoint.connectGraceSeconds` | `5`     | How long an attempt has to succeed before it counts as failed          |

Mind that an attempt that fails takes `connectGraceSeconds` before the pause starts, so two failed attempts start 
`connectGraceSeconds` plus the pause apart. All three must be greater than 0.

## Persistence
`thingsboard.endpoint.persistence` in the endpoint `.properties` file says what happens to a value set while the 
endpoint is not connected:

| Value             | What happens                                                                                    |
|-------------------|-------------------------------------------------------------------------------------------------|
| `none` (default)  | Nothing is kept: `Attribute.set_value()` raises `EndpointOfflineError`                          |
| `memory`          | The value is kept in memory and sent when the connection is back; lost if the process ends      |
| `file`            | The value is written to a file (directory: `thingsboard.endpoint.persistenceLocation`, default `~/mqtt-persistence`) and survives a restart |

## Errors and limits
An `Endpoint` raises instead of failing silently or ending the process:

 - **`EndpointOfflineError`**: `Attribute.set_value()` raises it when the endpoint is not online (see `is_online()`) and
   the persistence is `none`. The attribute holds the new value, but it is not sent. Catch it, or set a persistence.
   The connection can still be lost after the check: `on_publish_failed` tells about that case.
 - **`EndpointConfigurationError`**: `Endpoint(...)` raises it, with the message, when the properties file is not found, 
   `host` is missing or a property has an invalid value (the library never calls `exit()`). `InvalidPropertyException` 
   is a subclass of it.
 - **`TimeoutError`**: `endpoint.wait_until_online(timeout=30)` raises it if the endpoint is not online after `timeout`
   seconds.

The queue of values waiting to be sent is bounded, so it cannot grow for ever when the worker is dead or slower than 
the callers: `thingsboard.endpoint.maxQueueSize` (default `10000`, a whole number of at least 1). When it is full the 
oldest value is dropped, `endpoint.dropped_count` counts the drops since the endpoint was created, and the listeners get
`on_publish_failed(..., will_retry=False)` from the worker thread (if that is dead, `dropped_count` is the only trace). 
Values restored from the persistence when the connection is back count against the bound too.

## Listening to the endpoint
Derive from `thingsboard.endpoint.interface.EndpointListener` and register an instance with `endpoint.add_listener()`
(right after creating the endpoint, so the first connection is not missed; `endpoint.remove_listener()` unregisters
it). Every method does nothing by default:

```python
class MyListener(EndpointListener):
    def on_connected(self): ...
    def on_disconnected(self): ...
    def on_publish_failed(self, key, timestamp, value, reason, will_retry): ...
```

The methods are called on the worker thread, one at a time, so do not block in them. An exception in one is logged and
swallowed. Not to be confused with `AttributeListener`, which tells about the changes of an attribute.

`on_publish_failed` tells that a value was not sent: `key` is the key of the value in the data model, `timestamp` the 
time it was set (ms), `reason` says what went wrong. `will_retry` is `True` if the value will be sent again, `False` 
if it is gone. It is called once per failed attempt. The cases:

| What happened                                         | `will_retry`                                            |
|-------------------------------------------------------|---------------------------------------------------------|
| The send failed (failure code or exception) while connected, for telemetry or for attribute | `True`: the value stays at the front of the queue |
| The value was set while not connected                 | `True` if the persistence is `memory` or `file`, `False` with `none` (there `set_value()` raises `EndpointOfflineError` when it sees the endpoint offline: this is a connection lost just after) |
| The value was sent but not acknowledged when the connection was lost (paho keeps no queue across connections) | `True` if the persistence is `memory` or `file`, `False` with `none` |
| The message can never be sent (a payload that is not valid JSON) | `False`                                      |

A value that was in flight when the connection was lost may have reached the broker: with a persistence it is sent
again, which does no harm (same key, same timestamp).

`endpoint.connection_count` counts the connections made since the endpoint was created: one more per connect, never
less.

`Attribute.set_value()` raises if the value cannot be serialized (it no longer logs and returns).

## Telemetry only, and batches
**`write_as_attribute`.** A value of a Measure or Status attribute is sent as telemetry and, by default, also written 
as a ThingsBoard client attribute (the latest value, readable by the rules and the dashboards, on which the gateways
and the calculated values rely). That is two messages per value. Turn the attribute write off for a series nobody reads
as an attribute (a high-volume measure, a forecast): the value is then sent as telemetry only.

```python
obj.add_attribute('power_forecast', float, 'measure', write_as_attribute=False)
```

It is a property of the attribute (`attribute.write_as_attribute`, set before the value is sent). It cannot be turned 
off for the other constraints (Parameter, SetPoint, Static): there the attribute is the only way the value is sent, 
and `add_attribute()` raises `ValueError`.

**`endpoint.set_values()`.** One message per point does not scale: a 15-minute forecast is about 1,900 points. 
`set_values` sends a list of points in one telemetry call:

```python
endpoint.set_values([(forecast_attribute, timestamp_ms, value), ('some/telemetry/key', timestamp_ms, value), ...])
```

 - A point is `(attribute_or_key, timestamp, value)`: a Measure or Status `Attribute` of the endpoint, or the key of the
   telemetry as a string; the timestamp is in milliseconds. `0` or `None` is the time of the call, the same for every
   point that has none.
 - A point has its own timestamp: two points with the same key and the same timestamp raise `ValueError` (one of them
   would silently replace the other).
 - The value of an `Attribute` point is converted to the type of the attribute, as `set_value()` does: `ValueError`
   for a number that is not one, `TypeError` for a value that is not a string on a String attribute. The value of a
   string key must be JSON serializable (`TypeError` otherwise).
 - A batch over the limits of ThingsBoard (payload size, data points per message) is split by the MQTT client into
   as many messages as needed. It keeps each message within the limits, at times a point or so below them, so count
   on at least ceil(points / limit) messages.
 - The point with the latest timestamp of each `Attribute` that has `write_as_attribute` on is also written as a client
   attribute, whatever the order of the list. The value of the `Attribute` object itself is not changed: a batch is a
   series, not the current state. Turn the attribute write off for a series.
 - Results and failures go through the `EndpointListener` like single values: a failed batch calls `on_publish_failed`
   once **per point**. With a persistence a batch set while offline is stored whole, as one entry, and sent as a batch
   when the connection is back (`will_retry` is `True` for every point if it is stored, `False` for every point if it
   is not). Like `set_value()`, `set_values()` raises `EndpointOfflineError` when offline with persistence `none`.
 - A batch counts as one message in the publish queue (`maxQueueSize`).

## Running the crazyfrog example
[tests/crazyfrog](tests/crazyfrog) is a device (the *CrazyFrog endpoint*) and an application that talks to it, to run
against a real ThingsBoard. The endpoint
([tests/crazyfrog/endpoint/crazyfrog.py](tests/crazyfrog/endpoint/crazyfrog.py)) shows each feature in a few lines:

| Feature                                        | Where in `crazyfrog.py`                                     |
|------------------------------------------------|-------------------------------------------------------------|
| Build the model, `start()`, `wait_until_online()` | `_create_model()`, `initialize()`                        |
| `EndpointListener`                             | `CrazyFrogListener`                                         |
| `set_value()` and `EndpointOfflineError`       | `_sinus_set_value()`                                        |
| `write_as_attribute=False`                     | the `forecast` attribute in `_create_model()`               |
| `set_values()`                                 | `send_forecast()`                                           |
| `reconnect()`                                  | `reconnect()`; `kill -HUP <pid>` asks for it                |
| `shutdown()`                                   | `shutdown()`, called when the program ends                  |
| Parameters changed from the cloud              | `attribute_has_changed()`                                   |

To run it:

1. In ThingsBoard create a device and copy its access token.
2. Copy `tests/crazyfrog/config/thingsboard/CrazyFrogEndpoint-template.properties` to
   `~/.config/thingsboard/CrazyFrogEndpoint.properties` and fill in `host`, `port` and `device-access-token`. The template
   asks for TLS (port 8883 and `thingsboard-server-tls-cert`, a file that must exist): for a broker without TLS set the
   port to 1883 and comment out the certificate line.
3. `python tests/crazyfrog/start_endpoint.py`. The device publishes `CrazyFrog/property/_sinus` every
   0.5 s and a one-minute `CrazyFrog/property/forecast` every 20 s. Stop it with Ctrl-C (it calls `shutdown()`), or try
   `kill -HUP <pid>` to see `reconnect()`. Stop the broker, or the network, to see the listener, the offline error and
   the reconnection.
4. Optional, the application side (needs `thingsboard-monitor` 2.1 or newer): copy
   `tests/crazyfrog/config/thingsboard/app/CrazyFrogApp-template.config` to
   `~/.config/thingsboard/app/CrazyFrogApp.config`, fill in the login of ThingsBoard and the id of the device, and run
   `python tests/crazyfrog/start_app.py`: it sets the parameters `_triangle` and `frequency` of the
   endpoint.

The example runs against the fake broker too, as a test (`tests/thingsboard/test_crazyfrog_example.py`), so that it keeps
working with the library.

## Tests
`python -m unittest discover -s tests -t .` with `src` on the path (`PYTHONPATH=src`). The tests that need a real 
ThingsBoard server (and `thingsboard-monitor` 2.1 or newer, which they use to set parameters) are skipped unless the 
environment variable `THINGSBOARD_REAL_TESTS=1` is set. The others run against a fake broker (`tests/thingsboard/fake_mqtt_client.py`).
