Class: Subduino::ArdIO

Inherits:
Object
  • Object
show all
Defined in:
lib/subduino/ard_io.rb

Class Method Summary collapse

Class Method Details

.read(&proc) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/subduino/ard_io.rb', line 11

def read(&proc)
  Log.info "[USB] Starting USB Connect..." + sp.get_modem_params.map { |k,v| "#{k}: #{v}" }.join(" ")
  Log.info "[USB] Read Timeout #{sp.read_timeout}" # {sp.write_timeout}"

  #
  # Read I/O
  #
  @iothread ||= Thread.new do
    Thread.current.abort_on_exception = false
    icache = []

    loop do
      begin
        while char = sp.getc
          if char !~ /\n|\r/
            icache << char
          else
            data = icache.join(""); icache = []
            if data =~ /:/
              proc.call(data)
              Log.info "[SENSOR] #{data}"
            else
              proc.call(data) unless data.empty?
              # Log.info "[INPUT] Done."
            end
          end
        end
        sleep 1
      rescue => e
        Log.error "[USB] Error #{e}"
        Log.error e.backtrace.join("\n")
      end
    end
  end
end

.spObject



6
7
8
9
# File 'lib/subduino/ard_io.rb', line 6

def sp
  @sp ||= SerialPort.new(Arduino.find_usb, BAUDS) #, DATA_BITS, DATA_STOP, parity)
  # @sp.read_timeout = 10;# @sp.write_timeout = 10
end

.stop!Object



54
55
56
# File 'lib/subduino/ard_io.rb', line 54

def stop!
  sp.close
end

.write(msg) ⇒ Object



47
48
49
50
51
52
# File 'lib/subduino/ard_io.rb', line 47

def write(msg)
  Log.info "[IO  TX] #{msg}"
  txt = msg.gsub("\n", "\r")
  txt += "\r" unless txt =~ /^\\r/
  sp.write(txt)
end