Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show sensor output using Dino and Sinatra?

I would like to show on my page output from one of my sensor(moisture) connected to Arduino.

Following script, gives me some value(number) every one second.

require 'dino'

board = Dino::Board.new(Dino::TxRx.new)
sensor = Dino::Components::Sensor.new(pin: 'A0', board: board)

on_data = Proc.new do |data|
  puts data
  sleep 1
end

sensor.when_data_received(on_data)

sleep

I think I can use Sinatra as API and Javascript script for showing asynchronously output.

So this should be something like that

%w(sinatra dino haml).each do |lib|
  require lib
end

board = Dino::Board.new(Dino::TxRx.new)
sensor = Dino::Components::Sensor.new(pin: 'A0', board: board)
sleep 1

get '/' do
  haml :index
end

get '/moisture' do
  on_data = Proc.new do |data|
    { moisture_value: data }
    sleep 1
  end

  sensor.when_data_received(on_data)
end

Could you give me some hints or simple good pattern how should I handle with that?

I found sample sinatra app fo dino: https://github.com/austinbv/dino_cannon

like image 390
tomekfranek Avatar asked Dec 23 '12 17:12

tomekfranek


1 Answers

You will need to back the asynchronous data read with some kind of datastore: db, filestore or a memory store. It would be best to abstract your sensor reading code into a separate class and have well defined API to read that data back. I recommend putting MoistureSensor class into a separate file and require it in your server file. Also, I am limiting number of data points in memory store to 1000. Try Following:

%w(json sinatra dino haml).each do |lib|
  require lib
end

class MoistureSensor
  require 'dino'
  board = Dino::Board.new(Dino::TxRx.new)
  sensor = Dino::Components::Sensor.new(pin: 'A0', board: board)
  @@data = []
  on_data = Proc.new do |data|
    @@data.shift if @@data.length > 1000
    @@data << data
    sleep 1
  end
  sensor.when_data_received(on_data)

  def self.data
    @@data
  end

  def self.last_entry
    @@data.last
  end
end

get '/' do
  haml :index
end

get '/moisture.json' do
  content_type :json
  { moisture_value: MoistureSensor.last_entry }.to_json
end
like image 62
Iuri G. Avatar answered Sep 30 '22 08:09

Iuri G.