Created
March 1, 2017 03:43
-
-
Save dansimpson/6e326b0e91fc72ac994347c0040d7221 to your computer and use it in GitHub Desktop.
Aircraft position streaming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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']}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment