Skip to content

Instantly share code, notes, and snippets.

@amit
Forked from dansimpson/ac_stream.rb
Created February 15, 2018 22:49
Show Gist options
  • Select an option

  • Save amit/57ac0330dabde611cbf858c309f3b61c to your computer and use it in GitHub Desktop.

Select an option

Save amit/57ac0330dabde611cbf858c309f3b61c to your computer and use it in GitHub Desktop.

Revisions

  1. @dansimpson dansimpson created this gist Mar 1, 2017.
    53 changes: 53 additions & 0 deletions ac_stream.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    require 'socket'
    require 'json'

    class AircraftPositionStream

    def initialize host, port
    @host = host
    @port = port
    end

    # Stream acList JSON chunks
    def stream_json &block

    depth = 0
    struct = true
    buffer = ''
    socket = TCPSocket.new(@host, @port)

    while byte = socket.getc
    buffer << byte
    if byte == '{' && struct
    depth += 1
    elsif byte == '}' && struct
    depth -= 1
    # Call the block if we have a record
    if depth == 0
    block.call(JSON.parse(buffer))
    buffer = ''
    end
    elsif byte == '"' && buffer[-2] != '\\'
    struct = !struct
    end
    end

    ensure
    socket.close
    end

    # Stream aircraft postition objects
    def stream_updates &block
    stream_json { |records|
    records['acList'].each { |record|
    block.call(record)
    }
    }
    end

    end

    stream = AircraftPositionStream.new('pub-vrs.adsbexchange.com', 32005)
    stream.stream_updates { |record|
    puts "#{Time.now} - #{record['Icao']}"
    }