Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Adafruit Naming Examples

To run these examples, you'll need the Ruby MQTT library:

$ gem install mqtt

And you'll need to set the various environment variables the scripts expect to find. To do that, create a file named profile in the same directory you plan to run the scripts from. Fill in the AIO_USER and AIO_KEY values with your own.

$ cat <<EOF > profile

export AIO_USER=test_username
export AIO_KEY=123456789abcandsuch
export AIO_URL=io.adafruit.com
export AIO_PROTOCOL=mqtts
export AIO_PORT=8883

EOF

Then you just have to source profile before running scripts:

$ source profile
$ ruby adafruit-errors-sub.rb

Any environment variables you'd like to override for a single run of a script can be given as the first argument in the command line. For example, if I'd like to set the AIO_FEED_NAME value on the fly, I could write my command like this:

$ AIO_FEED_NAME="Test Mode Evaluator" ruby adafruit-sub.rb
require 'rubygems'
require 'mqtt'
USER = ENV['AIO_USER']
PASS = ENV['AIO_KEY']
URL = ENV['AIO_URL']
PROTOCOL = ENV['AIO_PROTOCOL']
PORT = ENV['AIO_PORT']
connect_uri = "#{PROTOCOL}://#{USER}:#{PASS}@#{URL}"
puts "CONNECT #{ connect_uri }"
client = MQTT::Client.connect(connect_uri, PORT)
client.get({"#{USER}/errors" => 1}) do |topic,message|
puts "[#{ topic } #{Time.now}] #{ message }"
end
require 'rubygems'
require 'mqtt'
USER = ENV['AIO_USER']
PASS = ENV['AIO_KEY']
URL = ENV['AIO_URL']
PROTOCOL = ENV['AIO_PROTOCOL']
PORT = ENV['AIO_PORT']
FEED = ENV['AIO_FEED_NAME']
connect_uri = "#{PROTOCOL}://#{USER}:#{PASS}@#{URL}"
puts "CONNECT TO #{ connect_uri }"
client = MQTT::Client.connect(connect_uri, PORT)
full_topic = "#{USER}/f/#{FEED}"
puts "PUBLISHING TO #{ full_topic }"
Signal.trap("INT") {
puts "exiting..."
client.disconnect
exit
}
while true do
t = rand(Time.now.to_i) % 10000000
puts "PUB #{ t } to #{full_topic} at #{ Time.now }"
client.publish full_topic, t
sleep 3
end
require 'rubygems'
require 'mqtt'
USER = ENV['AIO_USER']
PASS = ENV['AIO_KEY']
URL = ENV['AIO_URL']
PROTOCOL = ENV['AIO_PROTOCOL']
PORT = ENV['AIO_PORT']
FEED = ENV['AIO_FEED_NAME']
connect_uri = "#{PROTOCOL}://#{USER}:#{PASS}@#{URL}"
puts "CONNECT #{ connect_uri }"
client = MQTT::Client.connect(connect_uri, PORT)
full_topic = "#{USER}/f/#{FEED}"
puts "SUB #{ full_topic }"
client.get({full_topic => 1}) do |topic,message|
puts "[%s %s] %s" % [topic, Time.now.to_s, message]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment