Created
June 16, 2014 06:14
-
-
Save yoggy/95643521c04b5ca288ed to your computer and use it in GitHub Desktop.
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_sensor_pub.rb - Sample script to publish the sensor data using the MQTT | |
# | |
# $ sudo gem install serialport | |
# $ sudo gem install mqtt | |
# | |
require 'rubygems' | |
require 'serialport' | |
require 'mqtt' | |
require 'JSON' | |
dev = "/dev/cu.usbmodem1d1131" | |
conn_opts = { | |
remote_host: "mqtt.example.com", | |
remote_port: 1883, | |
username: "username", | |
password: "password", | |
} | |
sp = SerialPort.new(dev, 9600) | |
loop do | |
begin | |
MQTT::Client.connect(conn_opts) do |c| | |
while true do | |
l = sp.gets | |
puts l | |
begin | |
json = JSON.parse(l) | |
topic = json["name"] | |
json.delete("name") | |
json_str = JSON.generate(json) | |
puts "publish : " + json_str | |
c.publish(topic, json_str) | |
rescue Exception => e | |
puts e | |
end | |
end | |
end | |
rescue Exception => e | |
puts e | |
end | |
sleep 5 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment