Class: Sphero::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/sphero/request.rb

Direct Known Subclasses

Sphero

Defined Under Namespace

Classes: Sphero

Constant Summary collapse

SOP1 =
0xFF
SOP2 =
0xFF
SetBackLEDOutput =
make_command Sphero, 0x21
SetRotationRate =
make_command Sphero, 0x03
SetRGB =
make_command Sphero, 0x20
GetRGB =
make_command Sphero, 0x22
Heading =
make_command Sphero, 0x01, 'n'
Roll =
make_command Sphero, 0x30, 'CnC'
Ping =
make_command Request, 0x01
GetVersioning =
make_command Request, 0x02
GetBluetoothInfo =
make_command Request, 0x11
SetAutoReconnect =
make_command Request, 0x12
GetAutoReconnect =
make_command Request, 0x13
GetPowerState =
make_command Request, 0x20
Sleep =
make_command Request, 0x22, 'nC'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(seq, data = []) ⇒ Request


8
9
10
11
12
# File 'lib/sphero/request.rb', line 8

def initialize seq, data = []
  @seq    = seq
  @data   = data
  @did    = 0x00
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data


6
7
8
# File 'lib/sphero/request.rb', line 6

def data
  @data
end

Class Method Details

.make_command(klass, cid, pattern = 'C*', &block) ⇒ Object


60
61
62
63
64
65
66
67
68
# File 'lib/sphero/request.rb', line 60

def self.make_command klass, cid, pattern = 'C*', &block
  Class.new(klass) {
    define_method(:initialize) do |seq, *args|
      super(seq, args)
      @cid     = cid
      @pattern = pattern
    end
  }
end

Instance Method Details

#bytesObject


45
46
47
# File 'lib/sphero/request.rb', line 45

def bytes
  packet_header + packet_body + checksum.chr
end

#checksumObject


41
42
43
# File 'lib/sphero/request.rb', line 41

def checksum
  ~((packet_header + packet_body).unpack('C*').drop(2).reduce(:+) % 256) & 0xFF
end

#dlenObject


49
50
51
# File 'lib/sphero/request.rb', line 49

def dlen
  packet_body.bytesize + 1
end

#headerObject


14
15
16
# File 'lib/sphero/request.rb', line 14

def header
  [SOP1, SOP2, @did, @cid, @seq, dlen]
end

#packet_bodyObject


37
38
39
# File 'lib/sphero/request.rb', line 37

def packet_body
  @data.pack @pattern
end

#packet_headerObject


33
34
35
# File 'lib/sphero/request.rb', line 33

def packet_header
  header.pack 'CCCCCC'
end

#response(header, body) ⇒ Object


23
24
25
26
27
28
29
30
31
# File 'lib/sphero/request.rb', line 23

def response header, body
  name = self.class.name.split('::').last
  klass = if Response.const_defined?(name)
    Response.const_get(name)
  else
    Response
  end
  klass.new header, body
end

#to_strObject

The data to write to the socket


19
20
21
# File 'lib/sphero/request.rb', line 19

def to_str
  bytes
end