问题
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
回答1:
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.
回答2:
Can you intereact with the device using a simple script, like this:
require 'rubygems'
require 'serialport'
sp = SerialPort.new "/dev/ttyUSB0"
sp.write "AT\r"
while true do
printf("%c", sp.getc)
end
In this case I was using an GSM modem. Maybe your device is waiting for some command first.
来源:https://stackoverflow.com/questions/10161758/reading-from-serial-port-in-a-ruby-on-rails-application-hangs