@vocovo/sparkplug-host-app
v1.4.2
Published
Implementation of Sparkplug host app in JavaScript
Downloads
385
Maintainers
Keywords
Readme
@vocovo/sparkplug-host-app
Provides reusable logic for Sparkplug Host Applications.
Intentionally designed to be:
- Not tied to a particular MQTT Client implementation
- this makes it easier to unit test
- and gives users of this package more flexibility to use other clients
- To not be concerned with how different Sparkplug messages are handled
- so that different hosts can implement only the logic they need
Installation
npm install @vocovo/sparkplug-host-app
Usage
import { connectAsync } from 'mqtt'
import { UPayload } from 'sparkplug-payload/lib/sparkplugbpayload'
import { SparkplugHostApplication, EVENTS, ParsedTopic } from '@vocovo/sparkplug-host-app'
const main = async () => {
const host = new SparkplugHostApplication('hostId')
// Instantiate your own MQTT client
const mqttClient = await connectAsync('mqtt://localhost:1883', {
will: sparkplugHostApp.getOrInitializeWill(),
})
// Making your MQTT client compatible with the MQTTClient interface
sparkplugHostApp.setMqttClient({
on: mqttClient.on.bind(mqttClient),
subscribe: mqttClient.subscribeAsync.bind(mqttClient),
publish: mqttClient.publishAsync.bind(mqttClient),
})
await host.start()
host.on(EVENTS.NBIRTH, (parsedTopic: ParsedTopic, decodedPayload: UPayload) => {
// Will be called whenever an NBIRTH message is received
// Handle it however you want
})
host.on(EVENTS.NDEATH, (parsedTopic: ParsedTopic, decodedPayload: UPayload) => {
// Will be called whenever an NDEATH message is received
// Handle it however you want
})
host.on(EVENTS.NDATA, (parsedTopic: ParsedTopic, decodedPayload: UPayload) => {
// Will be called whenever an NDATA message is received
// Handle it however you want
})
// To terminate the session correctly, we should eventually call the 'shutdown' method
await host.shutdown()
}
main()