Skip to main content

Example 12 - Nonlinear value scaling

Task

A sensor value must be processed within different value ranges with different scalings and offsets. In Python, you can implement the processing as follows, for example:

if raw <= 51:
processed = raw * 0.5
elif raw <= 66:
processed = raw * 1 + 0.33
elif raw <= 101:
processed = raw * 3 + 2.5
else:
processed = 0.0

Solution

1. Create a table

Create the following table under the resource tag "Table":

raw	scale	offset
0 2 0
51 0.5 0
66 1 0.33
101 3 2.5
999 1 0

2. Implementation in the formula text

_sensor = $'Your.Channel';

// select first row, where input value _sensor is less than or equal to value in key 'raw'
_idx = selectRow(_sensor, {table:'Table', colSep:'[ \\t]+', key:'<=raw'});
_scale = getField(_idx, {table:'Table', field:'scale'});",
_offset = getField(_idx, {table:'Table', field:'offset'});

processed = _raw * _scale + _offset1;

Functions used

Explanation

The table is read line by line. Blank lines or lines that begin with three identical "line" characters (here, for example, '---') are skipped. The rows are split at the defined separator (see colSep), unnecessary spaces are removed from the front and back, and they are interpreted as variants. The first row provides the names for the columns (= fields). All other rows provide the data elements for comparison or reading.

This preparation happens only once with a selectRow() function in the formula text, after which the table is available to all other functions under the given name. The specification for the column separator colSep: ';' is optional. By default, a single comma, semicolon, tabulator, or '|' are accepted as regular expressions. The specification of anyKey is also optional and refers to a table entry (text) that matches any of the key values provided.

selectRow() is now used to search for a matching row in the table and return its index as the result value. To do this, the key value (here _sensor) is searched for in the field defined by key. Since the search is performed row by row from top to bottom when the key values are changed, the entries must be sorted in ascending order.

The getField() function is used to read matching entries from the designated column (field) in the same table.