Class: Generic::Serial

Inherits:
Object
  • Object
show all
Defined in:
lib/serial/generic.rb

Overview

Simple generic wrapper around the serialport library

Instance Method Summary collapse

Constructor Details

#initialize(port) ⇒ Serial

Returns a new instance of Serial.



10
11
12
13
# File 'lib/serial/generic.rb', line 10

def initialize(port)
  @read_buffer = ""
@device = SerialPort.new(port, 9600, 8, 1, SerialPort::NONE)
end

Instance Method Details

#closeObject



48
49
50
# File 'lib/serial/generic.rb', line 48

def close
  @device = nil
end

#finalizeObject



15
16
17
# File 'lib/serial/generic.rb', line 15

def finalize
  close 
end

#readObject



19
20
21
22
23
24
25
# File 'lib/serial/generic.rb', line 19

def read
  # I don't want a timeout here, because the phone gets really busy with receipts
  char = @device.getc
  raise "Could not read data" if char.nil?
  @read_buffer << sprintf("%c", char)
  char        
end

#read_until(term) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'lib/serial/generic.rb', line 27

def read_until(term)
  term = [term].flatten
  stop = nil
  loop do
    term.each {|t| stop = t and break if @read_buffer.index(t)}
    break if stop
    read
  end
  @read_buffer.slice!(0, @read_buffer.index(stop)+stop.size)
end

#write(data) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/serial/generic.rb', line 38

def write(data)
  begin
    @device.write(data)
  rescue Errno::EIO => e
    raise "Could not write data (IO: #{e.message})"
  rescue Exception => e
    raise "Could not write data (#{e.message})"
  end
end