% (c):          Joan Vila Carbó
function [position, rates, eulers, airspeed, brakes]=readXPLANE(port)
[index,data]=UDPreceiveDATA(port);
n=length(index);
for j = 1:n
    switch index(j)
        case 3
            % 7: mph air speed
            % 8: mph ground speed
            airspeed=data((j-1)*8+7);
        case 14
            if data((j-1)*8+2)~=0 
                brakes=1;
            else brakes=0;
            end
        case 16
            rates.pitch=data((j-1)*8+1);
            rates.roll=data((j-1)*8+2);
            rates.heading=data((j-1)*8+3);
        case 17
            eulers.pitch=data((j-1)*8+1);
            eulers.roll=data((j-1)*8+2);
            eulers.heading=data((j-1)*8+3);
        case 22
            position.latitude=data((j-1)*8+1);
        case 23
            position.longitude=data((j-1)*8+1);
        case 24
            position.altitude=data((j-1)*8+1);
    end
end
end

function [index,data]=UDPreceiveDATA(port)
persistent recv_pkt;
if (isempty(recv_pkt))
    recv_pkt = java.net.DatagramPacket(uint8(zeros(1,1085)), 1085);
end
rsock = java.net.DatagramSocket(port);
rsock.receive(recv_pkt);
rsock.close();

recv_data=recv_pkt.getData();

n=recv_pkt.getLength();
i=0;
for j = 6:36:n
    i=i+1;
    index_bytes=recv_data(j:j+3);
    index(i)=typecast(index_bytes,'uint32');
    for k=1:8
        data_bytes=recv_data(j+4*k:j+4*k+3);
        data((i-1)*8+k)=typecast(data_bytes,'single');
    end
end
end