Skip to content

Instantly share code, notes, and snippets.

@amclain
Created February 17, 2014 04:05
Show Gist options
  • Save amclain/9044552 to your computer and use it in GitHub Desktop.
Save amclain/9044552 to your computer and use it in GitHub Desktop.
# Convert an object to JSON, push it over MQTT,
# and reconstruct the object.
require 'mqtt'
require 'json'
# ip = '192.168.0.61'
ip = '10.0.1.27'
send = OpenStruct.new val_1:123, val_2:456
@obj = nil
# Topic listener.
thread = Thread.new do
MQTT::Client.connect ip do |c|
# This works, but "c.get do" loops.
# c.get '/test' do |topic, msg|
# @obj = OpenStruct.new JSON.parse(msg)
# p @obj
# end
@obj = OpenStruct.new JSON.parse c.get('/test').last
p @obj
end
end
sleep 0.1
# Topic publisher.
MQTT::Client.connect ip do |c|
c.publish '/test', JSON.generate(send.to_h)
end
thread.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment