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
# File 'lib/rb232/text_protocol.rb', line 35

def start
  @stop = false
  @reader_thread = Thread.new {
    buffer = ""
    while (@stop == false)
      buffer += @port.read_string(1)
      messages = buffer.split(@separator,3)
      if messages.size > 1
        changed
        notify_observers(messages[0])
        buffer = ""
      end
    end
  }
end

#stopObject

Stop processing incoming data from the serial port.



52
53
54
55
# File 'lib/rb232/text_protocol.rb', line 52

def stop
  @stop = true
  @reader_thread.join
end