Method: OpenC3::Interface#read

Defined in:
lib/openc3/interfaces/interface.rb

#readPacket

Retrieves the next packet from the interface.

Returns:

  • (Packet)

    Packet constructed from the data. Packet will be unidentified (nil target and packet names)



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/openc3/interfaces/interface.rb', line 208

def read
  raise "Interface not connected for read: #{@name}" unless connected?
  raise "Interface not readable: #{@name}" unless read_allowed?

  first = true
  loop do
    # Protocols may have cached data for a packet, so initially just inject a blank string
    # Otherwise we can hold off outputing other packets where all the data has already
    # been received
    if !first or @read_protocols.length <= 0
      # Read data for a packet
      data = read_interface()
      unless data
        Logger.info("#{@name}: read_interface requested disconnect")
        return nil
      end
    else
      data = ''
      first = false
    end

    @read_protocols.each do |protocol|
      data = protocol.read_data(data)
      if data == :DISCONNECT
        Logger.info("#{@name}: Protocol #{protocol.class} read_data requested disconnect")
        return nil
      end
      break if data == :STOP
    end
    next if data == :STOP

    packet = convert_data_to_packet(data)

    # Potentially modify packet
    @read_protocols.each do |protocol|
      packet = protocol.read_packet(packet)
      if packet == :DISCONNECT
        Logger.info("#{@name}: Protocol #{protocol.class} read_packet requested disconnect")
        return nil
      end
      break if packet == :STOP
    end
    next if packet == :STOP

    # Return packet
    @read_count += 1
    Logger.warn("#{@name}: Interface unexpectedly requested disconnect") unless packet
    return packet
  end
rescue Exception => err
  Logger.error("#{@name}: Error reading from interface")
  disconnect()
  raise err
end