@ctrlas/sparkplug-host-app
v0.0.4
Published
Sparkplug hostapp
Readme
sparkplug-host-app
A Node.js library for connecting to a Sparkplug B MQTT broker as a Host Application, consuming messages from edge nodes/devices, and exposing a simple event-based API.
Installation
npm install @ctrlas/sparkplug-host-appFor local development in this repository:
npm installConfiguration (.env)
MQTT_BROKER_URL=mqtt://localhost:1883
MQTT_CLIENT_ID=sparkplug-host-app
MQTT_USERNAME=
MQTT_PASSWORD=
PRIMARY_HOST_ID=mqtt2opcua
PRIMARY_HOST_ENABLED=false
STATS_EMITTER_ENABLED=true
STATS_SNAPSHOT_INTERVAL_MS=30000
STATS_IMMEDIATE_FIELDS=online
STATS_INCLUDE_FULL_ON_CHANGE=falseQuick Start
import dotenv from 'dotenv'
import spBHostApp from '@ctrlas/sparkplug-host-app'
dotenv.config()
const host = new spBHostApp()
host.on('message', (payload) => {
console.log(payload.topic, payload.messageType)
})
host.on('NBIRTH', ({ edgeNode }) => {
console.log('Edge node online:', edgeNode.baseTopic)
})
host.on('DBIRTH', ({ device }) => {
console.log('Device online:', device.baseTopic)
})
await host.connect()
await host.startStatsEmitter()Important Events
message: All incoming Sparkplug messages (topic,msg,messageType,baseTopic)NBIRTH,NDEATH,NDATADBIRTH,DDEATH,DDATANCMD,DCMDstats: Emitted byStatsEmitter(snapshot/change events)statsEmitterError: Errors from the stats emitter
StatsEmitter
startStatsEmitter() publishes stats events for:
- host
- edge nodes
- devices
Example stats event:
host.on('stats', (event) => {
// event.eventType: "snapshot" | "change"
// event.entityType: "host" | "edgeNode" | "device"
// event.entityId: e.g. "spBv1.0/groupA/node1"
// event.changed: fields that changed
console.log(event)
})Stop emitter:
await host.stopStatsEmitter()Send Command (NCMD/DCMD)
sendXCMD(source, type, value) sends a write/command to a node or device.
sourceformat:<topic>|<metricName>- a topic with 3 segments is sent as
NCMD(spBv1.0/<group>/<edgeNode>) - a topic with 4 segments is sent as
DCMD(spBv1.0/<group>/<edgeNode>/<device>)
Example:
await host.sendXCMD('spBv1.0/groupA/edge01|Node Control/Rebirth', 'Boolean', true)
await host.sendXCMD('spBv1.0/groupA/edge01/device01|Device Control/Rebirth', 'Boolean', true)Run Local Example
npm startThis runs example/index.js.
