Skip to content

Instantly share code, notes, and snippets.

@corck
Last active January 13, 2017 15:48
Show Gist options
  • Save corck/baf400b0598fc2c27e956af9b59ed6d4 to your computer and use it in GitHub Desktop.
Save corck/baf400b0598fc2c27e956af9b59ed6d4 to your computer and use it in GitHub Desktop.
Ruby thingsnetwork example mqtt script
require 'mqtt'
require 'base64'
require 'json'
app_id = APP_ID
access_key = ACCESS_KEY
dev_id = DEV_ID
region = eu
client = MQTT::Client.connect("mqtt://#{app_id}:#{access_key}@#{region}.thethings.network:1883")
topic = "#{app_id}/devices/#{dev_id}/up"
topic_down = "#{app_id}/devices/#{dev_id}/down"
message = {
port: 1,
payload_raw: Base64.encode64('hello world').strip
}
# Send Message
client.publish(topic_down, message.to_json)
# Subscribe example
client.get(topic) do |topic,message|
puts "#{topic}: #{message}"
# Parse a string containing a binary packet into an object
payload = JSON.parse(message)
data = payload['payload_raw']
#puts data.unpack data
puts Base64.decode64(data)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment