Module: SerialPacketModule

Included in:
SerialPacket
Defined in:
lib/serial_packet.rb

Overview

SerialPacket is used to define the format of Packets that can be sent and received over a serial link

they are essentially a description how to create a string representation from an array

a packet has the following properties:

data_format(string)
   this is a string that is passed to 'pack' and 'unpack'

header_format(string)
   this is the format of the header of received packets
   this property is used with SerialPacket.matches?

header_data
   an array that is used to decide if a given String is

Class Method Summary collapse

Class Method Details

.included(other) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/serial_packet.rb', line 25

def self.included(other)
  other.class_eval do

    def initialize_from_packet(str)
      self.data = str.unpack(self.class.data_format)
    end

    def initialize(*d)
      self.data = d
    end

    def to_str
      self.class.header_str << self.data.pack(self.class.data_format)
    end

    class << self

      # a packet can only be sent if it has a header
      #
      def sendable?
        (self.header && self.header_format) ? true : false
      end

      def header_str
        if sendable?
          h = self.header || []
          h.pack(self.header_format) || ""
        else
          ""
        end
      end

      # a packet can only be received, if it has a filter-expression
      def receiveable?
        defined? header_format and header_filter
      end

      # checks if some string conforms to the format of this packet
      #
      # this is tested by matching the packet "header" against the
      # provided filter-expression
      #
      def matches?(str)
        header = str.unpack(header_format)
        filter = self.header_filter || []
        filter.zip(header) { |f,a| return false unless f === a }
        return true
      end

      def from_str(str) #:nodoc:
        p = self.allocate
        p.initialize_from_packet(str)
        p
      end

      def create(&block)
        klass = Class.new(self)
        klass.instance_eval(&block) if block
        return klass
      end
    end
  end
end