13. Log temperature in Google Spreadsheet- Spark Core

As I did in 9. Temperature iPhone App, we can measure temperature using TMP36. I thought it would be great if we could log temperature and draw graph automatically. Let’s use google spreadsheet :)

I used Ruby library to control google spreadsheet. (https://github.com/gimite/google-drive-ruby)

# install the library
% brew tap homebrew/dupes
% brew install libiconv
% gem install nokogiri -- --with-iconv-dir=/usr/local/Cellar/libiconv/1.14/
% gem install google_drive

Spark Core set up is exact same as in 9. Temperature iPhone App as follows.

Spark Core expose API which returns temperature as JSON. You can test your API using curl.

% curl "https://api.spark.io/v1/devices/YOUR_DEVICE_ID/temperature?access_token=YOUR_ACCESS_TOKEN"
{
  "cmd": "VarReturn",
  "name": "temperature",
  "result": 26.717948717948715,
  "coreInfo": {
    "last_app": "",
    "last_heard": "2014-10-01T04:18:13.326Z",
    "connected": true,
    "deviceID": "YOUR_DEVICE_ID"
  } 

Let’s log temperare history in Google Doc Spreadsheet. You need to create one empty document ahead of time.
Then run ruby script, which is simply calling the API and logging the temperature.

require "rubygems"
require "google_drive"
require "json"
require "net/https"
require "uri"
require "pp"

def get_temperature
  # Call temperature API!
  uri = URI.parse("https://api.spark.io/v1/devices/#{ENV['DEVICE_ID']}/temperature?access_token=#{ENV['ACCESS_TOKEN']}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  request = Net::HTTP::Get.new(uri.request_uri)
  response = http.request(request)

  if response.code == "200"
    result = JSON.parse(response.body)
    return result["result"]
  else
    return nil
  end
rescue
  return nil
end

i = 1
while true do
  begin
    t = get_temperature
    if t
      # Logs in to Google
      session = GoogleDrive.login(ENV['GOOGLE_ID'], ENV['GOOGLE_PASSWORD'])

      # First worksheet of
      # https://docs.google.com/spreadsheet/ccc?key=18vExmI-c05Py8jSX7KgNmSTsDFn7i2bxsvwXWA1cZ3I
      ws = session.spreadsheet_by_key("18vExmI-c05Py8jSX7KgNmSTsDFn7i2bxsvwXWA1cZ3I").worksheets[0]
      ws[i, 1] = Time.new
      ws[i, 2] = t
      puts t
      ws.save
      i = i + 1
    end
    sleep 60
  rescue
    sleep 60
  end
end

Here is result.

code is available at my github