Skip to content

Instantly share code, notes, and snippets.

@iainiain32
Created February 14, 2012 04:56
Show Gist options
  • Save iainiain32/1823656 to your computer and use it in GitHub Desktop.
Save iainiain32/1823656 to your computer and use it in GitHub Desktop.
Read X-Plane UDP packets with Ruby
require 'rubygems'
require 'socket'
class Xplane
XP_SENDING_PORT = 49001 # X-Plane sends packets on this port
# These define the structure of the UDP packet.
XP_PACKET_HEADER = 'CCCCC'
XP_PACKET_DATA = 'lffffffff'
def initialize
@s = UDPSocket.new
@s.bind('',49001)
end
def getPacket(data_fields)
d = @s.recv(XP_PACKET_HEADER.length + 36*data_fields)
data_with_header = d.unpack(XP_PACKET_HEADER + XP_PACKET_DATA*data_fields)
data = data_with_header[ XP_PACKET_HEADER.length .. (XP_PACKET_HEADER.length + data_fields*XP_PACKET_DATA.length) ]
# At this point "data" is an array of the packet values, but lets go for a hash...
packet_hash = {}
data.each_slice(XP_PACKET_DATA.length).to_a.each do |packet|
packet_hash[packet[0]] = packet[1 .. XP_PACKET_DATA.length - 1]
end
return packet_hash
end
end
# Example use..
x = Xplane.new
p x.getPacket(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment