Class: MmGPS::Buffer

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/mm_gps/mm_gps_buffer.rb

Overview

A general abstraction for dealing with character streams.

Examples:

Typical usage:

buffer = Buffer.new(START_TOKEN)
buffer.when_updating do
  @sp.read(1) # @sp is an IO instance
end
# more code...
pkt = buffer.next

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sep = "\xFF") ⇒ Buffer

Returns a new instance of Buffer.



20
21
22
23
24
25
26
# File 'lib/mm_gps/mm_gps_buffer.rb', line 20

def initialize(sep="\xFF")
  @update = lambda { empty }
  @encoding = Encoding::BINARY
  fiber_init
  self.separator = sep
  self.clear
end

Instance Attribute Details

#bufferObject (readonly)

Returns the value of attribute buffer.



18
19
20
# File 'lib/mm_gps/mm_gps_buffer.rb', line 18

def buffer
  @buffer
end

#fiberObject (readonly)

Returns the value of attribute fiber.



18
19
20
# File 'lib/mm_gps/mm_gps_buffer.rb', line 18

def fiber
  @fiber
end

#separatorObject

Returns the value of attribute separator.



17
18
19
# File 'lib/mm_gps/mm_gps_buffer.rb', line 17

def separator
  @separator
end

#stop_packetObject (readonly)

Returns the value of attribute stop_packet.



17
18
19
# File 'lib/mm_gps/mm_gps_buffer.rb', line 17

def stop_packet
  @stop_packet
end

Instance Method Details

#clearString

Clear the #buffer and return its last content.

Returns:

  • (String)

    the last buffer content



38
39
40
41
42
# File 'lib/mm_gps/mm_gps_buffer.rb', line 38

def clear
  tmp = @buffer
  @buffer = empty
  return tmp
end

#each {|pkt| ... } ⇒ Enumerator

Iterates a block over incoming packets

Yields:

  • (pkt)

Yield Parameters:

  • pkt (String)

    the next packet

Returns:

  • (Enumerator)

    an Enumerator when called without block



74
75
76
77
78
79
# File 'lib/mm_gps/mm_gps_buffer.rb', line 74

def each
  return enum_for(:each) unless block_given?
  loop do
    yield self.next
  end
end

#nextString

Return the next available packet

Returns:

  • (String)

    the next available packet



65
66
67
# File 'lib/mm_gps/mm_gps_buffer.rb', line 65

def next
  @fiber.resume
end

#updateObject

Call the block set with #when_updating and queues its returned byte into #buffer



58
59
60
# File 'lib/mm_gps/mm_gps_buffer.rb', line 58

def update
  @buffer << (@update.call || empty)
end

#when_updating(&block) ⇒ Object

Sets the block to be executed for updating the #buffer. Typically, this block must read one single byte and return it. Queuing into the #buffer is automatically performed.

Examples:

To read from a serialport instance @sp:

buffer.when_updating do
  @sp.read(1)
end

Parameters:

  • block (Proc)

    the block (with no parameters) that must return a new character every time it is called



53
54
55
# File 'lib/mm_gps/mm_gps_buffer.rb', line 53

def when_updating(&block)
  @update = block
end