Class: RB232::TextProtocol

Inherits:
Object
  • Object
show all
Includes:
Observable
Defined in:
lib/rb232/text_protocol.rb

Overview

A helper class for RB232::Port which implements a simple text-based protocol on top of a serial port. Data is read from the serial port and split into individual messages based on a separator character.

This class is Observable. Client code should implement an update(string) function add call TextProtocol#add_observer(self). When a complete message is received, the update() function will be called with the message string.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(port, separator = "\n") ⇒ TextProtocol

Create a protocol object. port should be a RB232::Port object. separator is the character which separates messages in the text protocol, “n” by default.



20
21
22
23
# File 'lib/rb232/text_protocol.rb', line 20

def initialize(port, separator = "\n")
  @port = port
  @separator = separator
end

Instance Attribute Details

#portObject (readonly)

Port object, as specified in TextProtocol#new



29
30
31
# File 'lib/rb232/text_protocol.rb', line 29

def port
  @port
end

#separatorObject (readonly)

Separator character, as specified in TextProtocol#new



26
27
28
# File 'lib/rb232/text_protocol.rb', line 26

def separator
  @separator
end

Instance Method Details

#startObject

Begin processing incoming data from the serial port. A thread is started which monitors the port for data and detects complete messages. Call TextProtocol#stop to halt this process.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rb232/text_protocol.rb', line 35

def start
  @stop = false
  @reader_thread = Thread.new {
    buffer = ""
    while (@stop == false)
      new_string = ""
      # Read in as much data as possible
      begin
        new_string = @port.read_string(255)
        if (new_string.size > 0)
          buffer += new_string
          messages = buffer.split(@separator,2)
          if messages.size > 1
            changed
            notify_observers(messages[0])
            buffer = messages[1] || ""
          end
        end
      end while (new_string.size > 0 && @stop == false)
      sleep(0.5)
    end
  }
end

#stopObject

Stop processing incoming data from the serial port.



60
61
62
63
# File 'lib/rb232/text_protocol.rb', line 60

def stop
  @stop = true
  @reader_thread.join
end