Module: Serial

Defined in:
lib/ffi-serial.rb,
lib/ffi-serial/bsd.rb,
lib/ffi-serial/linux.rb,
lib/ffi-serial/posix.rb,
lib/ffi-serial/darwin.rb,
lib/ffi-serial/windows.rb

Overview

:nodoc:

Defined Under Namespace

Modules: Posix, Windows

Class Method Summary collapse

Class Method Details

.new(config) ⇒ Object

Create a new Ruby IO configured with the serial port parameters

:call-seq:

new(port: '/dev/tty or COM1')
new(port: '/dev/tty or COM1', baud: 9600, data_bits: 8, stop_bits: 1, parity: :none)


39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/ffi-serial.rb', line 39

def self.new(config)
  driver = if ('Windows_NT' == ENV['OS'])
    @@loaded_ffi_serial_windows ||= begin
      require 'ffi-serial/windows'
      true
    end
    Windows
  else
    @@loaded_ffi_serial_posix ||= begin
      require 'ffi-serial/posix'
      true
    end
    Posix
  end

  config = config.each_with_object({}) { |(k,v),r| r[k.to_s.strip.chomp.downcase.gsub(/\-|\_|\s/, '')] = v }
  
  port = config.delete('port') { raise ArgumentError.new ':port not specified' }
  baud = config.delete('baud') { 9600 }
  data_bits = config.delete('databits') { 8 }
  stop_bits = config.delete('stopbits') { 1 }
  parity = config.delete('parity') { :none }

  if !config.empty?
    raise ArgumentError.new "Unknown options specified: #{config.keys}"
  end

  # Create a new Ruby IO pointing to the serial port and configure it
  # using the OS specific function
  new_instance = driver.method(:new).call(
    port,
    Integer(baud),
    Integer(data_bits),
    Integer(stop_bits),
    parity.to_s.strip.chomp.downcase.to_sym)

  new_instance
end