Class: SerialProtocol::RCA2006Simple
- Defined in:
- lib/protocol/rca2006.rb
Constant Summary
Constants inherited from RCA2006
SerialProtocol::RCA2006::STARTBYTES, SerialProtocol::RCA2006::TYPE
Instance Method Summary collapse
-
#add_char_to_packet(char) ⇒ Object
Big and ugly state machine that does most of the work.
-
#initialize(send_callback, receive_callback, options = {}) ⇒ RCA2006Simple
constructor
A new instance of RCA2006Simple.
-
#send_packet(data, options = {}) ⇒ Object
Wrap a string into a packet.
Methods inherited from RCA2006
#on_raw_receive, #on_raw_send, #receive_handler
Constructor Details
#initialize(send_callback, receive_callback, options = {}) ⇒ RCA2006Simple
Returns a new instance of RCA2006Simple.
128 129 130 131 132 |
# File 'lib/protocol/rca2006.rb', line 128 def initialize(send_callback, receive_callback, = {}) @type = :data_no_crc @counter = 0 super end |
Instance Method Details
#add_char_to_packet(char) ⇒ Object
Big and ugly state machine that does most of the work
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
# File 'lib/protocol/rca2006.rb', line 153 def add_char_to_packet(char) @state = :first_checksum if (@state == 0) case @state when :first_startbyte @data = "" @state = ((char == STARTBYTES[0]) ? :second_startbyte : :first_startbyte) when :second_startbyte @state = (char == STARTBYTES[1]) ? :length : # special case: first startbyte is repeated (char == STARTBYTES[0] ? :second_startbyte : :first_startbyte) when :length @length = char @state = @length when Integer @data << char @state -= 1 when :first_checksum @checksum = (char << 8) @state = :second_checksum when :second_checksum @checksum = @checksum + char @state = :first_startbyte crc = ("" << @length << @data).crc_xmodem # received a valid packet if @type == :data || @type == :data_no_crc if @checksum == crc receive_handler(@type, @counter, @data,@checksum) else # send NACK and discard packet raise ChecksumMismatch, "ChecksumMismatch, expected #{crc}, was #{@checksum}" end else # the packet is ACK, NACK or unknown, call receive-handler # data may be mangled since the checksum is not checked # receive_handler(@type, @counter, @data, @checksum) end end end |
#send_packet(data, options = {}) ⇒ Object
Wrap a string into a packet
the options-hash can be used to override the default packet format
138 139 140 141 142 143 144 145 146 147 148 149 |
# File 'lib/protocol/rca2006.rb', line 138 def send_packet(data, = {}) str = data.to_s checksum = [:checksum] || ("" << str.length << str).crc_xmodem @raw_send_callback.call(:data_no_crc, 0, data, checksum) if @raw_send_callback p = "" << STARTBYTES << str.length << str << [checksum].pack("S").reverse # send the packet, using the callback # @send_callback.call(p) end |