Created
February 14, 2012 04:56
-
-
Save iainiain32/1823656 to your computer and use it in GitHub Desktop.
Read X-Plane UDP packets with Ruby
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 '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