Class: Subduino::ArdIO
- Inherits:
-
Object
- Object
- Subduino::ArdIO
- Defined in:
- lib/subduino/ard_io.rb
Class Method Summary collapse
-
.read(&proc) ⇒ Object
Read I/O.
-
.sp ⇒ Object
Serial Port.
-
.stop! ⇒ Object
Finish Him!.
-
.write(msg) ⇒ Object
Write I/O.
Class Method Details
.read(&proc) ⇒ Object
Read I/O
Starts a thread that loops fetching serial bytes. It’ll buffer it up until a \n or \r char are found. Feed it with a block to read the text.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/subduino/ard_io.rb', line 23 def read(&proc) Log.info "[USB] Found Device...#{Arduino.find_usb}" Log.info "[USB] Starting Connect..." + sp.get_modem_params.map { |k,v| "#{k}: #{v}" }.join(" ") Log.info "[USB] Read Timeout #{sp.read_timeout}" # {sp.write_timeout}" if sp @iothread ||= Thread.new do # Thread.current.abort_on_exception = false icache = [] loop do begin while char = sp.getc if !char.valid_encoding? bytes = char.bytes.to_a hexes = bytes.map { |b| b.to_s(16) } puts " - Bad char #{char} - (Hex: #{char.unpack('H')} | Byte(s) #{bytes} | Hexe(s) #{hexes}" elsif char !~ /\n|\r/ # print char if Debug icache << char else data = icache.join(""); icache = [] unless data.empty? Log.info "[IO RX] #{data}" proc.call(data) end end # sleep 1 end rescue => e Log.error "[USB] Error #{e}" Log.error e.backtrace.join("\n") stop! exit 1 end end end end end |
.sp ⇒ Object
Serial Port
Direct access to the SerialPort instance.
11 12 13 14 |
# File 'lib/subduino/ard_io.rb', line 11 def sp @sp ||= SerialPort.new(Arduino.find_usb, AppConfig[:bauds] || 57600) #, DATA_BITS, DATA_STOP, parity) # @sp.read_timeout = 10;# @sp.write_timeout = 10 end |
.stop! ⇒ Object
Finish Him!
82 83 84 85 86 |
# File 'lib/subduino/ard_io.rb', line 82 def stop! sp.close Thread.kill @iothread Log.info "[IO] K.I.A" end |
.write(msg) ⇒ Object
Write I/O
Prints bytes to the serial port. It’ll use subduino convention of \n to end the message. Use #sp to write directly to the port. ‘ArdIO.sp.puts (’hi’)‘
70 71 72 73 74 75 76 |
# File 'lib/subduino/ard_io.rb', line 70 def write(msg) Log.info "[IO TX] #{msg}" txt = msg.gsub("\r|\n", "") # txt += "\n" unless txt =~ /^\\n/ puts "=> Sending #{txt.inspect}" if Debug sp.puts(msg) end |