nixfilter-mqtt
Version:
Filters for publishing and subscribing to MQTT topics, similar to "mosquitto_pub" and "mosquitto_sub"
82 lines (76 loc) • 2.7 kB
text/coffeescript
'use strict'
# Add those arguments to <argument_parser> that all filter have in common
add_common_arguments = (argument_parser) ->
argument_parser.addArgument ['--host', '--broker', '-b'],
defaultValue: 'localhost'
help: 'The hostname or IP address of the MQTT broker'
argument_parser.addArgument ['--port', '-P'],
type: 'int'
defaultValue: 1883
help: 'The port of the MQTT broker'
argument_parser.addArgument ['--username', '-u'],
help: 'The username to use when connecting'
argument_parser.addArgument ['--password', '-p'],
help: 'The password to use when connecting'
argument_parser.addArgument ['--client_id', '-c'],
help: 'The client ID to use when connecting'
argument_parser.addArgument ['--qos', '-q'],
type: 'int'
choices: [0, 1, 2]
defaultValue: 0
help: 'The QOS level to use'
argument_parser.addArgument ['--status_topic', '-s'],
help: 'The (optional) MQTT topic to publish online/offline status messages to'
argument_parser.addArgument ['--online_message'],
defaultValue: 'online'
help: 'The (retained) message to publish to the (optional) MQTT topic when going online'
argument_parser.addArgument ['--offline_message'],
defaultValue: 'offline'
help: 'The (retained) message to publish to the (optional) MQTT topic when going offline'
argument_parser
# Require the "mqtt" module
mqtt = require('mqtt')
# Connect to the MQTT broker, using the arguments/parameters in <args>
connect_to_mqtt_broker = (args) ->
new Promise (resolve, reject) =>
connect_options =
servers: [
host: args.host
port: args.port
]
clientId: args.client_id
if args.username
connect_options.username = args.username
connect_options.password = args.password
if args.status_topic
connect_options.will =
topic: args.status_topic
payload: args.offline_message
qos: args.qos
retain: true
mqtt_client = mqtt.connect(connect_options)
mqtt_client.once 'connect', =>
if args.status_topic
mqtt_client.publish args.status_topic, args.online_message,
qos: args.qos
retain: true
resolve(mqtt_client)
return
mqtt_client.once 'error', (error) =>
reject(error)
return
mqtt_client.once 'close', =>
reject("Unable to connect to MQTT broker #{args.host}:#{args.port}")
return
return
# Disconnect MQTT client <mqtt_client> from the MQTT broker it is connected to
disconnect_from_mqtt_broker = (mqtt_client) ->
new Promise (resolve, reject) =>
mqtt_client.end ->
resolve(mqtt_client)
return
# What this module exports
module.exports =
add_common_arguments: add_common_arguments
connect_to_mqtt_broker: connect_to_mqtt_broker
disconnect_from_mqtt_broker: disconnect_from_mqtt_broker