node-red-contrib-sound-level 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Train Horn (train-horn.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ # node-red-contrib-sound-level
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A Node-RED node for quick sound level estimates in a free field:
4
+
5
+ - **Level at distance**: dB at a distance from a level known at a reference distance (inverse-square law), with an optional air absorption term.
6
+ - **Distance for target level**: how far away a source drops to a given dB.
7
+ - **Combine levels**: the total of several incoherent sources (two equal sources add about 3 dB).
8
+
9
+ Useful for noise dashboards, siren or horn audibility checks, sensor post-processing and "how loud is it over there?" questions in home automation flows. The math comes from the tested [`trainhorn-calc`](https://www.npmjs.com/package/trainhorn-calc) package.
10
+
11
+ ## Install
12
+
13
+ From the Node-RED palette manager, search for `node-red-contrib-sound-level`, or run in your Node-RED user directory (usually `~/.node-red`):
14
+
15
+ ```sh
16
+ npm install node-red-contrib-sound-level
17
+ ```
18
+
19
+ Requires Node-RED 3.0 or later and Node.js 18.3 or later.
20
+
21
+ ## Usage
22
+
23
+ The node is in the **function** category as **sound level**.
24
+
25
+ ### Level at distance
26
+
27
+ Send either a number (the distance; the other values come from the node settings) or an object:
28
+
29
+ ```json
30
+ { "sourceDb": 150, "refDistance": 10, "distance": 100, "unit": "ft" }
31
+ ```
32
+
33
+ Output (`msg.payload`):
34
+
35
+ ```json
36
+ { "mode": "level", "sourceDb": 150, "refDistance": 10, "distance": 100, "unit": "ft", "absorptionDbPerKm": 0, "levelDb": 130 }
37
+ ```
38
+
39
+ Formula: `L = sourceDb - 20*log10(distance/refDistance) - absorptionDbPerKm * (d_m - ref_m) / 1000`.
40
+
41
+ ### Distance for target level
42
+
43
+ Send a number (the target dB) or `{ sourceDb, refDistance, targetDb, unit, absorptionDbPerKm }`. The output adds `distanceForTarget` in the same unit. For 150 dB at 10 ft, 90 dB is reached at 10,000 ft without absorption, and closer with it.
44
+
45
+ ### Combine levels
46
+
47
+ Send an array of dB values, e.g. `[100, 100]`, or `{ "levels": [100, 100] }`. The output adds `combinedDb` (103.01 here).
48
+
49
+ ### Settings and overrides
50
+
51
+ | Setting | Payload property | Default |
52
+ | --- | --- | --- |
53
+ | Mode | `mode` (`level`, `distance`, `combine`) | `level` |
54
+ | Source dB | `sourceDb` | 150 |
55
+ | Ref. distance | `refDistance` | 10 |
56
+ | Distance | `distance` | from payload |
57
+ | Target dB | `targetDb` | from payload |
58
+ | Unit | `unit` (`ft` or `m`) | `ft` |
59
+ | Air absorption, dB/km | `absorptionDbPerKm` | 0 |
60
+ | Decimals | (node only) | 1; blank means no rounding |
61
+
62
+ Payload properties win over node settings. Other payload properties are passed through unchanged.
63
+
64
+ Typical air absorption at 10 °C and 70 % RH: about 1.9 dB/km at 500 Hz and 3.7 dB/km at 1 kHz.
65
+
66
+ ### Errors
67
+
68
+ Invalid input (missing values, a distance of 0 or less, an unknown unit, non-numbers, an empty list) is reported with `done(err)`, so a **catch** node can handle it, and the node shows a red status.
69
+
70
+ ## Example
71
+
72
+ Import **Menu > Import > Examples > node-red-contrib-sound-level > sound-level-basics**. It shows all three modes with inject and debug nodes.
73
+
74
+ ## Notes
75
+
76
+ The results are free-field estimates, not measurements. Ground, buildings, barriers, wind and temperature gradients change real levels. To try the same calculation in a browser, see the [decibel distance calculator](https://train-horn.com/tools/decibel-distance/).
77
+
78
+ ## Tests
79
+
80
+ ```sh
81
+ npm install
82
+ npm test
83
+ ```
84
+
85
+ The tests use `node-red-node-test-helper` and mocha and cover all modes, the example flow and invalid input.
86
+
87
+ ## License
88
+
89
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,11 @@
1
+ [
2
+ {"id":"sl_tab_comment","type":"comment","z":"","name":"sound-level: level at distance, distance for a target, combined levels","info":"Click each inject button and open the debug sidebar.\n150 dB at 10 ft is about 130 dB at 100 ft (inverse-square law).","x":330,"y":40,"wires":[]},
3
+ {"id":"sl_inj_level","type":"inject","z":"","name":"150 dB @ 10 ft, at 100 ft","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"sourceDb\":150,\"refDistance\":10,\"distance\":100,\"unit\":\"ft\"}","payloadType":"json","x":180,"y":100,"wires":[["sl_level"]]},
4
+ {"id":"sl_inj_level_abs","type":"inject","z":"","name":"same, 1 mile, 1.9 dB/km air","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"sourceDb\":150,\"refDistance\":10,\"distance\":5280,\"unit\":\"ft\",\"absorptionDbPerKm\":1.9}","payloadType":"json","x":190,"y":140,"wires":[["sl_level"]]},
5
+ {"id":"sl_level","type":"sound-level","z":"","name":"","mode":"level","sourceDb":"150","refDistance":"10","distance":"","targetDb":"","unit":"ft","absorptionDbPerKm":"0","decimals":"1","x":440,"y":120,"wires":[["sl_debug"]]},
6
+ {"id":"sl_inj_target","type":"inject","z":"","name":"where is it 90 dB?","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"90","payloadType":"num","x":160,"y":200,"wires":[["sl_distance"]]},
7
+ {"id":"sl_distance","type":"sound-level","z":"","name":"","mode":"distance","sourceDb":"150","refDistance":"10","distance":"","targetDb":"","unit":"ft","absorptionDbPerKm":"0","decimals":"1","x":450,"y":200,"wires":[["sl_debug"]]},
8
+ {"id":"sl_inj_combine","type":"inject","z":"","name":"two horns, 100 + 100 dB","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[100,100]","payloadType":"json","x":180,"y":260,"wires":[["sl_combine"]]},
9
+ {"id":"sl_combine","type":"sound-level","z":"","name":"","mode":"combine","sourceDb":"","refDistance":"10","distance":"","targetDb":"","unit":"ft","absorptionDbPerKm":"0","decimals":"2","x":440,"y":260,"wires":[["sl_debug"]]},
10
+ {"id":"sl_debug","type":"debug","z":"","name":"result","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":670,"y":180,"wires":[]}
11
+ ]
@@ -0,0 +1,124 @@
1
+ <script type="text/javascript">
2
+ RED.nodes.registerType('sound-level', {
3
+ category: 'function',
4
+ color: '#E2D96E',
5
+ defaults: {
6
+ name: { value: '' },
7
+ mode: { value: 'level', required: true },
8
+ sourceDb: { value: '150', validate: RED.validators.number(true) },
9
+ refDistance: { value: '10', validate: RED.validators.number(true) },
10
+ distance: { value: '', validate: RED.validators.number(true) },
11
+ targetDb: { value: '', validate: RED.validators.number(true) },
12
+ unit: { value: 'ft', required: true },
13
+ absorptionDbPerKm: { value: '0', validate: RED.validators.number(true) },
14
+ decimals: { value: '1', validate: RED.validators.number(true) }
15
+ },
16
+ inputs: 1,
17
+ outputs: 1,
18
+ icon: 'font-awesome/fa-volume-up',
19
+ paletteLabel: 'sound level',
20
+ label: function () {
21
+ if (this.name) return this.name;
22
+ return this.mode === 'distance' ? 'distance for dB' : this.mode === 'combine' ? 'combine dB' : 'sound level';
23
+ },
24
+ oneditprepare: function () {
25
+ function toggle() {
26
+ var mode = $('#node-input-mode').val();
27
+ $('.sound-level-row-spl').toggle(mode !== 'combine');
28
+ $('.sound-level-row-level').toggle(mode === 'level');
29
+ $('.sound-level-row-distance').toggle(mode === 'distance');
30
+ }
31
+ $('#node-input-mode').on('change', toggle);
32
+ toggle();
33
+ }
34
+ });
35
+ </script>
36
+
37
+ <script type="text/html" data-template-name="sound-level">
38
+ <div class="form-row">
39
+ <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
40
+ <input type="text" id="node-input-name" placeholder="Name">
41
+ </div>
42
+ <div class="form-row">
43
+ <label for="node-input-mode"><i class="fa fa-cog"></i> Mode</label>
44
+ <select id="node-input-mode">
45
+ <option value="level">Level at distance</option>
46
+ <option value="distance">Distance for target level</option>
47
+ <option value="combine">Combine levels</option>
48
+ </select>
49
+ </div>
50
+ <div class="form-row sound-level-row-spl">
51
+ <label for="node-input-sourceDb"><i class="fa fa-volume-up"></i> Source dB</label>
52
+ <input type="text" id="node-input-sourceDb" placeholder="150">
53
+ </div>
54
+ <div class="form-row sound-level-row-spl">
55
+ <label for="node-input-refDistance">Ref. distance</label>
56
+ <input type="text" id="node-input-refDistance" placeholder="10">
57
+ </div>
58
+ <div class="form-row sound-level-row-level">
59
+ <label for="node-input-distance">Distance</label>
60
+ <input type="text" id="node-input-distance" placeholder="from msg.payload">
61
+ </div>
62
+ <div class="form-row sound-level-row-distance">
63
+ <label for="node-input-targetDb">Target dB</label>
64
+ <input type="text" id="node-input-targetDb" placeholder="from msg.payload">
65
+ </div>
66
+ <div class="form-row sound-level-row-spl">
67
+ <label for="node-input-unit">Unit</label>
68
+ <select id="node-input-unit">
69
+ <option value="ft">feet (ft)</option>
70
+ <option value="m">metres (m)</option>
71
+ </select>
72
+ </div>
73
+ <div class="form-row sound-level-row-spl">
74
+ <label for="node-input-absorptionDbPerKm">Air absorption</label>
75
+ <input type="text" id="node-input-absorptionDbPerKm" placeholder="0" style="width:120px"> dB/km
76
+ </div>
77
+ <div class="form-row">
78
+ <label for="node-input-decimals">Decimals</label>
79
+ <input type="text" id="node-input-decimals" placeholder="blank = no rounding" style="width:120px">
80
+ </div>
81
+ </script>
82
+
83
+ <script type="text/html" data-help-name="sound-level">
84
+ <p>Estimates sound pressure levels in a free field: the level at a distance (inverse-square law with optional
85
+ air absorption), the distance at which a target level is reached, or the combined level of several sources.</p>
86
+
87
+ <h3>Inputs</h3>
88
+ <dl class="message-properties">
89
+ <dt>payload <span class="property-type">number | object | array</span></dt>
90
+ <dd>
91
+ <ul>
92
+ <li><b>Level at distance</b>: a number (the distance) or
93
+ <code>{sourceDb, refDistance, distance, unit, absorptionDbPerKm}</code>.</li>
94
+ <li><b>Distance for target level</b>: a number (the target dB) or
95
+ <code>{sourceDb, refDistance, targetDb, unit, absorptionDbPerKm}</code>.</li>
96
+ <li><b>Combine levels</b>: an array of dB values, or <code>{levels: [...]}</code>.</li>
97
+ </ul>
98
+ Any property missing from the payload falls back to the value set in the node.
99
+ <code>payload.mode</code> (<code>level</code>, <code>distance</code>, <code>combine</code>) overrides the node mode.
100
+ </dd>
101
+ </dl>
102
+
103
+ <h3>Outputs</h3>
104
+ <dl class="message-properties">
105
+ <dt>payload <span class="property-type">object</span></dt>
106
+ <dd>The input values plus <code>levelDb</code>, <code>distanceForTarget</code> or <code>combinedDb</code>,
107
+ rounded to the chosen number of decimals.</dd>
108
+ </dl>
109
+
110
+ <h3>Details</h3>
111
+ <p>Level at distance: <code>L = sourceDb - 20*log10(distance/refDistance) - absorption*(d - ref)/1000</code>
112
+ (absorption in dB/km, distances converted to metres). Each doubling of distance loses about 6 dB, so
113
+ 150 dB at 10 ft is about 130 dB at 100 ft.</p>
114
+ <p>Combine levels: <code>10*log10(sum(10^(L/10)))</code>. Two equal sources add about 3 dB.</p>
115
+ <p>Typical air absorption at 10 °C / 70 % RH: 1.9 dB/km at 500 Hz, 3.7 dB/km at 1 kHz.</p>
116
+ <p>Invalid input (missing values, distance 0 or less, unknown unit, non-numbers) raises an error that a
117
+ <i>catch</i> node can handle, and sets a red status.</p>
118
+ <p>Results are estimates for open ground, not measurements; buildings, terrain and wind change real levels.</p>
119
+
120
+ <h3>References</h3>
121
+ <ul>
122
+ <li><a href="https://train-horn.com/">Train Horn</a>: the reference site behind these calculators</li>
123
+ </ul>
124
+ </script>
@@ -0,0 +1,136 @@
1
+ /**
2
+ * sound-level: a Node-RED node that estimates sound pressure levels.
3
+ *
4
+ * Modes
5
+ * level - level at a distance (inverse-square law, optional air absorption)
6
+ * distance - distance at which a target level is reached
7
+ * combine - combined level of several incoherent sources
8
+ *
9
+ * The math comes from the tested `trainhorn-calc` package (an ES module, loaded
10
+ * once with dynamic import). Results are free-field estimates, not measurements.
11
+ */
12
+ 'use strict';
13
+
14
+ const MODES = ['level', 'distance', 'combine'];
15
+
16
+ let calcPromise = null;
17
+ /** Load trainhorn-calc once (it is ESM; this file is CommonJS). */
18
+ function loadCalc() {
19
+ if (!calcPromise) calcPromise = import('trainhorn-calc');
20
+ return calcPromise;
21
+ }
22
+
23
+ /** Turn a config string into a number, or undefined when blank. */
24
+ function configNumber(value) {
25
+ if (value === undefined || value === null || String(value).trim() === '') return undefined;
26
+ return Number(value);
27
+ }
28
+
29
+ /** Round to `decimals` places when decimals is a non-negative integer. */
30
+ function round(value, decimals) {
31
+ if (!Number.isInteger(decimals) || decimals < 0) return value;
32
+ const f = 10 ** decimals;
33
+ return Math.round(value * f) / f;
34
+ }
35
+
36
+ /** Pick the first defined value. */
37
+ function first(...values) {
38
+ return values.find((v) => v !== undefined && v !== null && v !== '');
39
+ }
40
+
41
+ /**
42
+ * Compute the result for one message payload.
43
+ * @param {object} calc The trainhorn-calc module.
44
+ * @param {object} cfg Node configuration (numbers already parsed).
45
+ * @param {unknown} payload msg.payload.
46
+ * @returns {object} New payload.
47
+ */
48
+ function compute(calc, cfg, payload) {
49
+ const { InputError } = calc;
50
+ const isObj = payload !== null && typeof payload === 'object' && !Array.isArray(payload);
51
+ const input = isObj ? payload : {};
52
+ const mode = first(input.mode, cfg.mode);
53
+ if (!MODES.includes(mode)) {
54
+ throw new InputError(`mode must be one of ${MODES.join(', ')}; got ${JSON.stringify(mode)}`);
55
+ }
56
+
57
+ if (mode === 'combine') {
58
+ let levels;
59
+ if (Array.isArray(payload)) levels = payload;
60
+ else if (isObj && Array.isArray(input.levels)) levels = input.levels;
61
+ else throw new InputError('combine mode needs msg.payload as an array of dB levels or {levels: [...]}');
62
+ const combinedDb = round(calc.combineLevels(levels), cfg.decimals);
63
+ return { ...(isObj ? input : {}), levels, mode, combinedDb };
64
+ }
65
+
66
+ if (!isObj && typeof payload !== 'number' && typeof payload !== 'string') {
67
+ throw new InputError('msg.payload must be a number or an object such as {sourceDb, refDistance, distance, unit}');
68
+ }
69
+
70
+ const sourceDb = first(input.sourceDb, cfg.sourceDb);
71
+ const refDistance = first(input.refDistance, cfg.refDistance, 10);
72
+ const unit = first(input.unit, cfg.unit, 'ft');
73
+ const absorptionDbPerKm = first(input.absorptionDbPerKm, cfg.absorptionDbPerKm, 0);
74
+ const options = { refDistance, unit, absorptionDbPerKm };
75
+ if (sourceDb === undefined) throw new InputError('sourceDb is missing: set it in the node or in msg.payload.sourceDb');
76
+
77
+ if (mode === 'level') {
78
+ const distance = isObj ? first(input.distance, cfg.distance) : payload;
79
+ if (distance === undefined) throw new InputError('distance is missing: send a number or msg.payload.distance');
80
+ const levelDb = round(calc.splAtDistance(sourceDb, distance, options), cfg.decimals);
81
+ return { ...input, mode, sourceDb: Number(sourceDb), refDistance: Number(refDistance), distance: Number(distance), unit, absorptionDbPerKm: Number(absorptionDbPerKm), levelDb };
82
+ }
83
+
84
+ // mode === 'distance'
85
+ const targetDb = isObj ? first(input.targetDb, cfg.targetDb) : payload;
86
+ if (targetDb === undefined) throw new InputError('targetDb is missing: send a number or msg.payload.targetDb');
87
+ const distanceForTarget = round(calc.distanceForSpl(sourceDb, targetDb, options), cfg.decimals);
88
+ return { ...input, mode, sourceDb: Number(sourceDb), refDistance: Number(refDistance), targetDb: Number(targetDb), unit, absorptionDbPerKm: Number(absorptionDbPerKm), distanceForTarget };
89
+ }
90
+
91
+ module.exports = function register(RED) {
92
+ function SoundLevelNode(config) {
93
+ RED.nodes.createNode(this, config);
94
+ const node = this;
95
+ const decimals = configNumber(config.decimals);
96
+ const cfg = {
97
+ mode: config.mode || 'level',
98
+ sourceDb: configNumber(config.sourceDb),
99
+ refDistance: configNumber(config.refDistance),
100
+ distance: configNumber(config.distance),
101
+ targetDb: configNumber(config.targetDb),
102
+ unit: config.unit || 'ft',
103
+ absorptionDbPerKm: configNumber(config.absorptionDbPerKm),
104
+ decimals: decimals === undefined ? undefined : decimals,
105
+ };
106
+
107
+ node.on('input', (msg, send, done) => {
108
+ send = send || function (...args) { node.send.apply(node, args); };
109
+ loadCalc()
110
+ .then((calc) => {
111
+ try {
112
+ msg.payload = compute(calc, cfg, msg.payload);
113
+ } catch (err) {
114
+ node.status({ fill: 'red', shape: 'ring', text: err.message.slice(0, 40) });
115
+ if (done) done(err); else node.error(err, msg);
116
+ return;
117
+ }
118
+ const p = msg.payload;
119
+ const text = p.mode === 'level' ? `${p.levelDb} dB @ ${p.distance} ${p.unit}`
120
+ : p.mode === 'distance' ? `${p.targetDb} dB @ ${p.distanceForTarget} ${p.unit}`
121
+ : `${p.combinedDb} dB combined`;
122
+ node.status({ fill: 'green', shape: 'dot', text });
123
+ send(msg);
124
+ if (done) done();
125
+ })
126
+ .catch((err) => {
127
+ if (done) done(err); else node.error(err, msg);
128
+ });
129
+ });
130
+ }
131
+
132
+ RED.nodes.registerType('sound-level', SoundLevelNode);
133
+ };
134
+
135
+ module.exports.compute = compute;
136
+ module.exports.loadCalc = loadCalc;
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "node-red-contrib-sound-level",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Node-RED node for sound level estimates: dB at a distance (inverse-square law with air absorption), distance for a target level, and combined levels of several sources.",
5
+ "main": "nodes/sound-level.js",
6
+ "files": [
7
+ "nodes/",
8
+ "examples/",
9
+ "README.md",
10
+ "LICENSE"
11
+ ],
12
+ "scripts": {
13
+ "test": "mocha \"test/**/*_spec.js\" --exit"
14
+ },
15
+ "keywords": [
16
+ "node-red",
17
+ "sound",
18
+ "decibel",
19
+ "db",
20
+ "spl",
21
+ "noise",
22
+ "acoustics",
23
+ "inverse-square-law",
24
+ "train-horn"
25
+ ],
26
+ "node-red": {
27
+ "version": ">=3.0.0",
28
+ "nodes": {
29
+ "sound-level": "nodes/sound-level.js"
30
+ }
31
+ },
32
+ "engines": {
33
+ "node": ">=18.3"
34
+ },
35
+ "dependencies": {
36
+ "trainhorn-calc": "^1.0.0"
37
+ },
38
+ "homepage": "https://train-horn.com/",
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/train-horn/node-red-contrib-sound-level.git"
42
+ },
43
+ "bugs": {
44
+ "url": "https://github.com/train-horn/node-red-contrib-sound-level/issues"
45
+ },
46
+ "author": "Train Horn (https://train-horn.com/)",
47
+ "license": "MIT",
48
+ "devDependencies": {
49
+ "mocha": "^12.0.3",
50
+ "node-red": "^5.0.10",
51
+ "node-red-node-test-helper": "^0.3.6"
52
+ }
53
+ }