Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from serial port in a Ruby on Rails application hangs

I'm using the serialport gem to read from the serial port in my Ruby on Rails 3.2 application. The serial port itself is used to write data from an Arduino board. The gem is added to Gemfile. The port is initialized in application.rb:

config.serial_port = SerialPort.new "/devttyACM0", 9600
config.serial_port.read_timeout = 100

The problem appears when I try to read from this port.

@sp = ProjectName::Application::config.serial_port
@sp.read

The application hangs deadly. I've tried to perform reading from a pry session and everything was OK. If I set read_timeout to 0, reading from pry also hangs. I already tried to set read_timeout to bigger values with no result. What should I do to make it work?

Update:

I've tried to perform the same actions using sinatra framework. It hangs too.

require "sinatra"
require "serialport"

get '/' do
  read_data
end

helpers do
  def read_data
    sp = SerialPort.new "/dev/ttyACM0", 9600
    sp.read_timeout = 1500
    t = sp.read.match(/\d+(\n|\r)+/)[0].gsub!(/(\n|\r)*/,"") rescue nil
    sp.close
    t
  end
end
like image 937
roman Avatar asked Nov 05 '22 01:11

roman


1 Answers

Had the same problem. The fix was actually easy, the problem is that your rails app is constantly reading new values from the serial port and as long its reading those inputs, it doesn't do anything else, so your site will never be actually built.

Try if it works if for example you simply let it read from the serial port a fixed number of times.

like image 84
Xenplex Avatar answered Nov 09 '22 14:11

Xenplex