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)



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/openc3/interfaces/interface.rb', line 269

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 outputting other packets where all the data has already
    # been received
    extra = nil
    if !first or @read_protocols.length <= 0
      # Read data for a packet
      data, extra = read_interface()
      unless data
        Logger.info("#{@name}: read_interface requested disconnect")
        return nil
      end
    else
      data = ''
      first = false
    end

    @read_protocols.each do |protocol|
      # Extra check is for backwards compatibility
      if extra
        data, extra = protocol.read_data(data, extra)
      else
        data, extra = protocol.read_data(data)
      end
      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

    # Extra check is for backwards compatibility
    if extra
      packet = convert_data_to_packet(data, extra)
    else
      packet = convert_data_to_packet(data)
    end

    # 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 => e
  Logger.error("#{@name}: Error reading from interface")
  disconnect()
  raise e
end