Last active
August 29, 2015 14:02
-
-
Save yoggy/9709c309ab4efeda0077 to your computer and use it in GitHub Desktop.
mqtt & influxdb sample..
This file contains hidden or 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 | |
# -*- encoding: utf-8 -*- | |
# | |
# mqtt & influxdb sample... | |
# | |
# libraries | |
# $ gem install mqtt | |
# $ gem install influxdb | |
# | |
require 'rubygems' | |
require 'mqtt' | |
require 'influxdb' | |
require 'json' | |
require 'logger' | |
# configure | |
mqtt_params = { | |
:remote_host => 'localhost', | |
:remote_port => 1883, | |
:username => 'username', | |
:password => 'password', | |
} | |
influxdb_params = { | |
:host => 'localhost', | |
:username => 'username', | |
:password => 'password', | |
} | |
database = 'database_name' | |
STDOUT.sync = true | |
log = Logger.new(STDOUT) | |
log.level = Logger::INFO | |
influxdb = InfluxDB::Client.new(database, influxdb_params) | |
loop do | |
begin | |
MQTT::Client.connect(mqtt_params) do |c| | |
log.info("connection start...") | |
c.get('#') do |topic, message| | |
log.info("recieve mqtt message : topic=#{topic}, message=#{message}") | |
# check json format | |
json = JSON.parse(message) | |
# write | |
json[:time] = Time.now.to_i | |
influxdb.write_point(topic, json, false, 's') | |
log.info("write : database=#{database}, series=#{topic}, values=#{json.to_s}") | |
end | |
end | |
rescue Exception => e | |
log.error(e) | |
end | |
log.info("connection retry...") | |
sleep 3 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment