Skip to content

Instantly share code, notes, and snippets.

@jmb
Last active January 27, 2019 22:25
Show Gist options
  • Save jmb/ac36d16a5180c3d2032a to your computer and use it in GitHub Desktop.
Save jmb/ac36d16a5180c3d2032a to your computer and use it in GitHub Desktop.
MQTT Data Subscriber for Dashing

Description

Dashing job to subscribe to MQTT messages.

MQTT is a lightweight publish/subscribe messaging transport. This job allows Dashing to subscribe to these messages and send them as events. There is no associated widget as the data can take any form - commonly numbers, but not necessarily. The script as laid out below sends events with value, current (the same contents) and last values so can be plugged directly into the Numbers or Meter widgets using the data-id in the dashboard file. The send_event could easily be modified if required.

Set up

Add to Gemfile:

gem 'mqtt', '>= 0.3.1'

Run

bundle

Then set your MQTT_SERVER and MQTT_TOPICS with associated tags.

Example usage

I use MQTT to publish electricity usage and temperature from a CurrentCost device connected to a linux machine within my home network, hence the topics in the example job file. For the example topics, you could add the Numbers and/or Meter widgets:

    <li data-row="1" data-col="1" data-sizex="1" data-sizey="1">
      <div data-id="watts" data-view="Number" data-title="Current Electricity Use" data-moreinfo="In watts" ></div>
    </li>

    <li data-row="1" data-col="1" data-sizex="1" data-sizey="1">
      <div data-id="cctemp" data-view="Meter" data-title="Temperature" data-min="0" data-max="100"></div>
    </li>
require 'mqtt'
# Set your MQTT server
MQTT_SERVER = 'mqtt://localhost'
# Set the MQTT topics you're interested in and the tag (data-id) to send for dashing events
MQTT_TOPICS = { 'home/sensors/currentcost/watts' => 'watts',
'home/sensors/currentcost/temperature' => 'cctemp',
}
# Start a new thread for the MQTT client
Thread.new {
MQTT::Client.connect(MQTT_SERVER) do |client|
client.subscribe( MQTT_TOPICS.keys )
# Sets the default values to 0 - used when updating 'last_values'
current_values = Hash.new(0)
client.get do |topic,message|
tag = MQTT_TOPICS[topic]
last_value = current_values[tag]
current_values[tag] = message
send_event(tag, { value: message, current: message, last: last_value })
end
end
}
@mapero
Copy link

mapero commented Nov 23, 2015

Hey,

thanks for the initial work. I did some change to your gist to add publish when using clickableWidgets and by dynamically subscribe to a topic: https://gist.github.com/mapero/ee99ce0a8dbc2fe7e335

Maybe it will help you.

Thanks.

@maklumatpemankanan
Copy link

Hey,

how can I add authentication with username and password for my Mqtt-connection in mqtt.rb

@ccsalvesen
Copy link

@maklumatpemankanan - MQTT_SERVER = 'mqtt://username:password@localhost'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment