how to use Xively API Library on Ruby?

275 views Asked by At

i'm triyng to upload some data to xively from ruby, i did install all the gems and this test code runs ok, but nothing changes in the xively graph of my device.

This small code was isolated from the fragment of a bigger code that works fine, and post data to my server with an interface written in php, but now i want to use xively to log the data.

I did remove my personal data from this code, API_KEY, Feed number and feed Name.

#!/usr/bin/ruby

require 'rubygems'
require 'json'
require 'xively-rb'

##Creating the xively client instance
API_KEY = "MY_API_KEY_WAS_HERE"
client = Xively::Client.new(API_KEY)

#on an endless loop
while true

  #n is a random float between 0 y 1
  n = rand()

  ##Creating datapoint and sendig it to xively
  puts "Creating datapoint "+Time.now.to_s+", "+n.to_s+" and sending it to xively"

  datapoint = Xively::Datapoint.new(:at => Time.now, :value => n)

  client.post('/api/v2/feeds/[number]/datastreams/[name]', :body => {:datapoints => [datapoint]}.to_json)

end

it would be nice to get an example on how to use that library, i didn't find any concise example.

(It's possible to find some silly errors in the code, if it's so, it's ok because im learning ruby at the moment, if it isn't critical just point it out briefly to not go offtopic, i will be happy to research and learn later)

im really looking forward for some answer, so thanks in advance.

1

There are 1 answers

0
rccursach On

I receive a solution that works from a classmate, it was in a post about Cosm the beta of what now is xively, what previously was pachube also.

we were about two weeks looking for something like this:

afulki.net more-on-ruby-and-cosm

#!/usr/bin/ruby

require 'xively-rb'
require 'json'
require 'rubygems'

class XivelyConnector
  API_KEY = 'MY_API_KEY_HARD-CODED_HERE'

  def initialize( xively_feed_id )
    @feed_id = xively_feed_id

    @xively_response = Xively::Client.get("/v2/feeds/#{@feed_id}.json", :headers => {"X-ApiKey" => API_KEY})
  end

  def post_polucion( sensor, polucion_en_mgxm3 )
    return unless has_sensor? sensor

    post_path          = "/v2/feeds/#{@feed_id}/datastreams/#{sensor}/datapoints"
    datapoint          = Xively::Datapoint.new(:at => Time.now, :value => polucion_en_mgxm3.to_s )
    response           = Xively::Client.post(post_path,
      :headers => {"X-ApiKey" => API_KEY},
      :body    => {:datapoints => [datapoint]}.to_json)
  end

  def has_sensor?( sensor )
    @xively_response["datastreams"].index { |ds| ds["id"] == sensor }
  end
end

Using that class:

#!/usr/bin/ruby

require 'rubygems'
require 'json' 
require 'xively-rb'
require_relative 'XivelyConnector'

xively_connector = XivelyConnector.new( MY_FEED_ID_HERE )

while true
n = rand()
xively_connector.post_polucion 'Sensor-Asdf', n

sleep 1

end