diff --git a/lib/sphero.rb b/lib/sphero.rb index 3d4fb2e..951ec0a 100644 --- a/lib/sphero.rb +++ b/lib/sphero.rb @@ -1,4 +1,11 @@ -require 'serialport' +$RUBY_SPHERO_RS232 = ENV['RUBY_SPHERO_RS232'] + +if $RUBY_SPHERO_RS232 + require 'rs232' +else + require 'serialport' +end + require 'sphero/request' require 'sphero/response' require 'thread' @@ -7,7 +14,21 @@ class Sphero VERSION = '1.0.0' def initialize dev - @sp = SerialPort.new dev, 115200, 8, 1, SerialPort::NONE + + if $RUBY_SPHERO_RS232 + params = Hash.new + params[:baudrate] = 115200 + params[:bytesize] = 8 + params[:stopbits] = RS232::DCB::ONESTOPBIT + params[:parity] = RS232::DCB::NOPARITY + + @sp = RS232.new dev, params + @sp.report = false + else + @sp = SerialPort.new dev, 115200, 8, 1, SerialPort::NONE + end + + @dev = 0x00 @seq = 0x00 @lock = Mutex.new @@ -93,11 +114,27 @@ def write packet body = nil @lock.synchronize do + + write_len = 6 + packet.dlen + format = "C#{write_len}" + @sp.write packet.to_str @seq += 1 - - header = @sp.read(5).unpack 'C5' - body = @sp.read header.last + + if $RUBY_SPHERO_RS232 + response = @sp.read + count = @sp.count.read_uint32 + + format = "C#{count}" + response = response.unpack(format) + + header = response[0..4] + body = response[5..-1].join + else + header = @sp.read(5).unpack 'C5' + body = @sp.read header.last + end + end response = packet.response header, body @@ -105,7 +142,7 @@ def write packet if response.success? response else - raise response + raise "Response failed" end end end diff --git a/lib/sphero/request.rb b/lib/sphero/request.rb index 10b29c7..7398950 100644 --- a/lib/sphero/request.rb +++ b/lib/sphero/request.rb @@ -8,7 +8,7 @@ class Request def initialize seq, data = [] @seq = seq @data = data - @did = 0x00 + @did = 0x00 # virtual device id for core end def header @@ -52,7 +52,7 @@ def dlen class Sphero < Request def initialize seq, data = [] super - @did = 0x02 + @did = 0x02 # virtual device id for sphero end end