Created
August 21, 2013 19:43
-
-
Save asargent/6299216 to your computer and use it in GitHub Desktop.
Demo of publishing MQTT messages to local RabbitMQ broker. Scenario is a fleet of networked cars that continually transmit telemetry data back to the manufacturer for diagnostic purposes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require 'rubygems' | |
require 'mqtt' | |
# Credits: | |
# https://github.com/njh/ruby-mqtt | |
# How many vehicles we've sold | |
num_vehicles = 100 | |
# What things are transmitting MQTT messages | |
sensor_types = [ | |
"/brakes/front/left/", | |
"/brakes/front/right/", | |
"/brakes/rear/left/", | |
"/brakes/rear/right/", | |
"/engine/battery/", | |
"/headlight/left/", | |
"/headlight/right/", | |
"/airconditioning/", | |
] | |
status_topics = [ | |
"ok", | |
"error", | |
"warning", | |
"nodata" | |
] | |
# Publish example | |
MQTT::Client.connect('localhost') do |c| | |
# Do the following forever... | |
while true do | |
# Pick a random vehicle to report on... | |
vehicle_number = rand(num_vehicles) | |
# For each sensor type in that vehicle... | |
sensor_types.each do |sensor| | |
# Choose which status topic to publish to | |
status_topic = status_topics[rand(status_topics.length)] | |
# Compose our MQTT topic string | |
topic = "vehicle/" + vehicle_number.to_s + sensor + status_topic | |
# Compose our diagnostic message | |
message = topic + "\t\t Diagnostic message " + rand(1000).to_s | |
# ... publish the name of the sensor plus a randomly chosen status message. | |
c.publish(topic, message) | |
# Throttle a bit | |
# sleep 0.1 | |
end | |
end | |
end | |
# Subscribe example | |
# MQTT::Client.connect('test.mosquitto.org') do |c| | |
# If you pass a block to the get method, then it will loop | |
# c.get('test') do |topic,message| | |
# puts "#{topic}: #{message}" | |
# end | |
# end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment