# tlsupportfunctions

> This package includes frequently used functions used by the Transformation Layer. Every aspect of the package can function on its own though the use case is highly specific and it is not recommended to use this package for anything but the project it was

Latest version **0.2.11** (published 2025-04-04) · ISC license · 0 weekly downloads

## Install

```sh
npm install tlsupportfunctions
pnpm add tlsupportfunctions
yarn add tlsupportfunctions
bun add tlsupportfunctions
```

## Health

**Score 25/100 (F)** — status: maintenance-mode.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.2.11 |
| Published | 2025-04-04 |
| First published | 2022-10-06 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 128.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | carl.dolling@bayer.com |
| Maintainers | carldolling, dirk_rodermund |

## Links

- npm: https://www.npmjs.com/package/tlsupportfunctions
- npm.io page: https://npm.io/package/tlsupportfunctions

## Dependencies (1)

- [nyc](https://npm.io/package/nyc.md) ^15.1.0

## Recent versions

- 0.2.11 (latest) — 2025-04-04
- 0.2.10 — 2025-03-03
- 0.2.9 — 2024-07-04
- 0.2.8 — 2024-03-27
- 0.2.7 — 2024-03-27
- 0.2.6 — 2024-03-15
- 0.2.5 — 2023-10-12
- 0.2.4 — 2023-08-03
- 0.2.3 — 2023-03-31
- 0.2.2 — 2023-03-23
- 0.2.1 — 2023-03-21
- 0.2.0 — 2023-03-10
- 0.1.0 — 2023-01-23
- 0.0.8 — 2022-10-13
- 0.0.7 — 2022-10-11
- … 6 more at https://npm.io/package/tlsupportfunctions/versions

## README

# General

This package includes frequently used functions used by the Transformation Layer (node red). Every aspect of the package can function on its own though the use case is highly specific and it is not recommended to use this package for anything but the project it was created for. It can however be used as an inspiration for similar projects.

# Usage

In your user directory, go to ".node-red". Install package with:

> `npm i tlsupportfunctions`

In the same directory, find "settings.js". Locate the object `functionGlobalContext` and add the entry

```js
"tlsupportfunctions": require('tlsupportfunctions')
```

to the object. Now the package can be used in any function node. At the beginning of the function node, add the line 

```js
const tls = global.get("tlsupportfunctions");
```

The functions implemented in the package can be used with the declared constant, for example 

```js
tls.calculateCounterIncrement(10, 8);
```

# Implemented Functions

### calculateCounterIncrement(counter, lastCounter, checkRange = 15, range = false, min = false, reset = false)

Calculates a counter increment given the current counter value (counter) and previous counter value (lastCounter).

Parameters:
- `counter`: current counter value (e.g. 10)
- `lastCounter`: previous counter value (e.g. 8)
- `checkRange` (optional, default 15): detection range for overflows, should always be larger than normal counter increases but only as big as necessary
- `range` (optional): value range of the counter, calculated as max + abs(min) (e.g. 65535)
- `min` (optional): the lowest possible value of the counter, usually 0 or a negative power of 2 (e.g. -32768)
- `reset` (optional): the value the counter takes when manually reset (e.g. 0)

### counterChangedObject(msg, increment)

Returns a specifically formatted object.

Parameters:
- `msg`: the node red message object
- `increment`: the counter increment (e.g. 2)

### runningStateChangedObject(msg, isRunning, faultCodes = [])

Returns a specifically formatted object.

Parameters:
- `msg`: the node red message object
- isRunning: boolean value whether the machine is running (e.g. true)
- `faultCodes` (optional, default []): array containing fault codes of the machine

### messagePreprocessor(msg, dynamic_line_data, lineName, f_metadata, one_time_cyclics, contexualizer_func = false, messageintervall_in_s = 10)

Updated 2023-03-10
- Code refactored and "EndOfMessage" messages added.
- optional parameter added to provide one of the added contextualizer functions (see below)

Prepares a message for later use.

Parameters:
- `msg`: the node red message object
- `dynamic_line_data`: dynamic line data stored in the flow
- `lineName`: line name stored in environment
- `f_metadata`: metadata stored in the flow
- `one_time_cyclics`: cyclics data stored in the flow
- `contexualizer_func`: Contextualizer to be used (see below)
- `messageintervall_in_s`: For non-time-synced OPC servers (metadata isTimeSynced=false), this is the capture time frame on the OPC forwarder (Default is 10 seconds)

The function returns the following object:
```js
{
    success: false,
    error_text: false,
    flow_dynamic_line_data: false,
    flow_one_time_cyclics: false,
    returnMsg: false
}
```

Example usage:
```js
let ppmsg = tls.messagePreprocessor(  msg, 
                                flow.get("dynamic_line_data", "file"), 
                                env.get("LineName"),
                                flow.get("metadata"),
                                flow.get("one_time_cyclics"));
if(ppmsg.success){
    msg = ppmsg.returnMsg;
    flow.set("dynamic_line_data", ppmsg.flow_dynamic_line_data);
    flow.set("one_time_cyclics", ppmsg.flow_one_time_cyclics);
} else {
    node.error(ppmsg.error_text);
}
```

### edhMsg2JSON(msg)
#### (Obsolete)
Converts and formats incoming messages.

Parameters:
- `msg`: the node red message object

# Contextualizers
The transfomation layer needs some context information of the data to be processes. Therefore the `messagePreprocessor` is enabled to add a context to each individual tag message.

The `messagePreprocessor` expects a contextualizer to be a void function:
```js
(tag, machine_metadata) => { /* adding the context to the tag */ }
```

Contectualizers...
- extende an existing property named `Context` on the tag message.
- have to flag the tag as valid for properly assigned conext information, by changing the tag property `InvalidTagName` to `false`. Invalid tags will not be processed by the transformation layer.

The `Context` get extended with following properties:
- `Category` : To categorize the tag in groups of similar concerns, e.g. status, faults, counters, etc.
- `Parameter` : Semantical name of the tag
- `Attribute` : Optional context information for further differentiation of a parameter

This version of the `tlsupportfunctions` provide two predefined contextualizers:

## ctx_by_naming_convention_berlin

This contextualizer reads the context information from the `tag.id` based on the local standard.
It sets the tag as valid if `Category` and `Parameter` are set.

## ctx_by_metadata_whitelist

This contextualizer does a lookup in the `machine_metadata` property `TagWhitelistAndContext`. It provides a white list of supported tags with each's context values:
```js
    TagWhitelistAndContext: {
        "This.is.tag.a": { "Category": "MSTATE", "Parameter": "CurrentState", "Attribute": "PDA" },
        "This.is.tag.b": { "Category": "MFAULT", "Parameter": "MachineStop", "Attribute": "Code" },
        "This.is.tag.c": { "Category": "COUNTER", "Parameter": "Good" }
    }
```
It sets the tag as valid if the `tag.id` exists as object in the `TagWhitelistAndContext` and provides context details for `Category` and `Parameter`.

# Fault code handlers

These handler are providing standard functionality to maintain the a machiens fault code array base on the technical representation of machine faults.

The fault codes are maintained in an array of objects with the properties
- `code` : storing the numeric value of the machines fault code
- `t` : the timestamp as provided by the connected OPC server in milliseconds

```js
    faultArray = [
        {code: 1234, t : 1679392604015},
        {code: 815, t : 1679350658430},
        ...
    ];
```

### OPC Tag provides just one numeric value

#### Capturing the last fault code only
Returning an updated fault code array, not chaning the provided array. A value of zero empties the array, any other value gets stored in `code` along with `t` the timestamp or replaces the existing value.

```js
    let result = update_fault_codes_by_numeric_tag_value(fault_codes, preprocessed_tag);
```
#### Capturing fault codes in the array
Returning an updated fault code array, not chaning the provided array. A value of zero gets ignored, any other value gets added (pushed) with `code` and `t` the timestamp to the resulting array.

```js
    let result = update_fault_codes_by_adding_numeric_tag_value(fault_codes, preprocessed_tag);
```

### OPC Tag provides a blooean flag for one fault code
Returning an updated fault code array, not chaning the provided array.
The tag's context attribute provides the related fault code.
Any numeric tag value greater than zero indicated the fault is set active, otherwise the fault is set inactive.
Active fault codes gets added to the 'fault_codes' array if not already existing, inactive fault code gets removed from the array if existing.

```js
    let result = update_fault_codes_by_tag_value_boolean(fault_codes, preprocessed_tag);
```

### OPC Tag provides a bitbask based coding of multiple fault codes in one OPC tag.
(this implementation is based on a Siemens PLC representation)

The tag's context attribute provides details about the  1 up to 4 bytes sized tag value, including the start and end value of the bit rang, and optionally a mask to filter out non fault relevant bits that must be ignored.
Example: 0-7-254
- 0 : lower number of the bit range
- 7 : higer number of the bit range (low and high together must be a range of 8, 15, 24 or 32)
- 254 : is the mask, masking out bit 0 as to be ignored.
A tag value of 3 (0b00000011) will be masked with 254 (0b00000010), so bit 0 gets ignored.
Only bit 1 is set and according to the range it represents fault code 1. (if the range would go from 8 to 15, this bit would represent the fault code 9).

All masked bit gets updated in the fault code array, for a set bit (active fault) the code get added to the fault code array, an unset bit (inactive fault), the code gets removed. This happens in decending order! That means the highest value gets updates first.

```js
    let result = update_fault_codes_by_tag_value_bitwise_siemens(fault_codes, preprocessed_tag);
```

# Testing
there are automated tests prepared to have a technical secification to check any code changes against.

It utilizes the mocha test framework and it is recommended to install the "Mocha Test Explorer" in VSCode for interacice code testing during development.

### Installation of test framework depedencies
use the following statemnt to install all development dependencies on the development computer 
> `npm install --save-dev`

This installs the following "devDependencies" as registered in the `package.json` file:
- Mocha
- Chai
- Chai-things

# Deployment
follow this sequence to deploy the tlsupportfunction to NPM:
- push code changes to github
- increase NPM package version number: `npm version patch`
- publish npm package `npm publish`
- push code changes to github for new version number

---
_Source: https://npm.io/package/tlsupportfunctions · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
