| 1 | -module(x_plane_data). |
| 2 | |
| 3 | -include("x_plane_datum_defaults.hrl"). |
| 4 | |
| 5 | -export_type( |
| 6 | [ t/0 |
| 7 | ]). |
| 8 | |
| 9 | -export( |
| 10 | [ of_bin/1 |
| 11 | ]). |
| 12 | |
| 13 | -type parsing_error() :: |
| 14 | packet_unrecognized |
| 15 | | packet_length_invalid |
| 16 | | x_plane_datum:parsing_error() |
| 17 | . |
| 18 | |
| 19 | -type t() :: |
| 20 | [x_plane_datum:t()]. |
| 21 | |
| 22 | -define(BYTE_SIZE_OF_EACH_BLOCK, 36). |
| 23 | |
| 24 | -spec of_bin(binary()) -> |
| 25 | hope_result:t(t(), parsing_error()). |
| 26 | of_bin(<<Packet/binary>>) -> |
| 27 | of_bin(Packet, ?DEFAULT_MAX_INDEX). |
| 28 | |
| 29 | -spec of_bin(binary(), non_neg_integer()) -> |
| 30 | hope_result:t(t(), parsing_error()). |
| 31 | of_bin(<<"DATA", _PacketIndexByte:1/bytes, ContiguousBlocks/binary>>, MaxIndex) -> |
| 32 | % Packet index byte seems to be changing from X-Plane version to version. |
| 33 | % What is it's meaning? |
| 34 | if byte_size(ContiguousBlocks) rem ?BYTE_SIZE_OF_EACH_BLOCK =:= 0 -> |
| 35 | Blocks = blocks_split(ContiguousBlocks), |
| 36 | ParseBlock = fun (B) -> x_plane_datum:of_bin(B, MaxIndex) end, |
| 37 | hope_list:map_result(Blocks, ParseBlock) |
| 38 | ; true -> |
| 39 | {error, packet_length_invalid} |
| 40 | end; |
| 41 | of_bin(<<_/binary>>, _) -> |
| 42 | {error, packet_unrecognized}. |
| 43 | |
| 44 | -spec blocks_split(binary()) -> |
| 45 | [binary()]. |
| 46 | blocks_split(<<>>) -> |
| 47 | []; |
| 48 | blocks_split(<<Block:?BYTE_SIZE_OF_EACH_BLOCK/bytes, Blocks/binary>>) -> |
| 49 | [Block | blocks_split(Blocks)]. |