lunedì 5 dicembre 2011

Using serial port in Ruby

Ruby doesn't have a native library for control serial port. It should be done with standard file I/O opening the device file in /dev/ folder.
Nevertheless the GitHub's user  tenderlove has developed an interesting Ruby library for control RS232 serial port and it can be easily installed like a gem:
gem install serialport

Unfortunately the library is not event-driven, but if you want to throw an event and call a callback while you receive something on serial port you can use a console-like infinite loop. For example:
def check_serial(callback)
opts = {"baud" => 115200, "parity" => SerialPort::NONE, "data_bits" => 8, "stop_bits" => 1}
port = '/dev/ttyS0'
serialport = SerialPort.new(port, opts)
Thread.new do
while true
input = @serialport.gets.chomp
unless input.empty?
callback.call(input)
end
end
end
end

def my_serial_callback(input)
#...do something
end

check_serial(method(:my_serial_callback))