From 32e25cbca210a359b09768537b6f443fe90a3070 Mon Sep 17 00:00:00 2001 From: Romain Forlot Date: Tue, 20 Jun 2017 10:24:05 +0000 Subject: Separation Generator to a dedicated repo Change-Id: Id94831651c3266861435272a6e36c7884bef2c45 Signed-off-by: Romain Forlot --- libs/CMakeLists.txt | 20 + libs/bitfield-c/.gitignore | 5 + libs/bitfield-c/.travis.yml | 7 + libs/bitfield-c/CHANGELOG.mkd | 5 + libs/bitfield-c/CMakeLists.txt | 43 + libs/bitfield-c/LICENSE | 24 + libs/bitfield-c/Makefile | 53 + libs/bitfield-c/README.mkd | 107 + libs/bitfield-c/runtests.sh | 17 + libs/bitfield-c/src/bitfield/8byte.c | 61 + libs/bitfield-c/src/bitfield/8byte.h | 88 + libs/bitfield-c/src/bitfield/bitarray.c | 145 + libs/bitfield-c/src/bitfield/bitfield.c | 74 + libs/bitfield-c/src/bitfield/bitfield.h | 220 + libs/bitfield-c/src/canutil/read.c | 34 + libs/bitfield-c/src/canutil/read.h | 81 + libs/bitfield-c/src/canutil/write.c | 48 + libs/bitfield-c/src/canutil/write.h | 57 + libs/bitfield-c/tests/8byte_tests.c | 261 + libs/bitfield-c/tests/bitfield_tests.c | 132 + libs/bitfield-c/tests/read_tests.c | 67 + libs/bitfield-c/tests/write_tests.c | 105 + libs/ini-config/CMakeLists.txt | 38 + libs/ini-config/ini-config.cpp | 100 + libs/ini-config/ini-config.hpp | 61 + libs/isotp-c/.gitignore | 6 + libs/isotp-c/.travis.yml | 8 + libs/isotp-c/CHANGELOG.mkd | 10 + libs/isotp-c/CMakeLists.txt | 42 + libs/isotp-c/LICENSE | 24 + libs/isotp-c/Makefile | 56 + libs/isotp-c/README.mkd | 142 + libs/isotp-c/runtests.sh | 17 + libs/isotp-c/src/isotp/isotp.c | 32 + libs/isotp-c/src/isotp/isotp.h | 41 + libs/isotp-c/src/isotp/isotp_types.h | 144 + libs/isotp-c/src/isotp/receive.c | 166 + libs/isotp-c/src/isotp/receive.h | 86 + libs/isotp-c/src/isotp/send.c | 89 + libs/isotp-c/src/isotp/send.h | 86 + libs/isotp-c/tests/common.c | 91 + libs/isotp-c/tests/test_core.c | 78 + libs/isotp-c/tests/test_receive.c | 176 + libs/isotp-c/tests/test_send.c | 103 + libs/nanopb/.gitignore | 28 + libs/nanopb/.travis.yml | 54 + libs/nanopb/AUTHORS | 31 + libs/nanopb/BUILD | 21 + libs/nanopb/CHANGELOG.txt | 272 + libs/nanopb/CONTRIBUTING.md | 32 + libs/nanopb/LICENSE.txt | 20 + libs/nanopb/README.md | 71 + libs/nanopb/docs/Makefile | 9 + libs/nanopb/docs/concepts.rst | 392 + libs/nanopb/docs/generator_flow.svg | 2869 +++++ libs/nanopb/docs/index.rst | 127 + libs/nanopb/docs/logo/logo.png | Bin 0 -> 14973 bytes libs/nanopb/docs/logo/logo.svg | 1470 +++ libs/nanopb/docs/logo/logo16px.png | Bin 0 -> 854 bytes libs/nanopb/docs/logo/logo48px.png | Bin 0 -> 2577 bytes libs/nanopb/docs/lsr.css | 240 + libs/nanopb/docs/menu.rst | 13 + libs/nanopb/docs/migration.rst | 289 + libs/nanopb/docs/reference.rst | 770 ++ libs/nanopb/docs/security.rst | 84 + libs/nanopb/examples/cmake_simple/CMakeLists.txt | 16 + libs/nanopb/examples/cmake_simple/README.txt | 18 + libs/nanopb/examples/cmake_simple/simple.c | 71 + libs/nanopb/examples/cmake_simple/simple.proto | 9 + libs/nanopb/examples/network_server/Makefile | 17 + libs/nanopb/examples/network_server/README.txt | 60 + libs/nanopb/examples/network_server/client.c | 142 + libs/nanopb/examples/network_server/common.c | 40 + libs/nanopb/examples/network_server/common.h | 9 + .../examples/network_server/fileproto.options | 13 + .../nanopb/examples/network_server/fileproto.proto | 20 + libs/nanopb/examples/network_server/server.c | 158 + libs/nanopb/examples/simple/Makefile | 22 + libs/nanopb/examples/simple/README.txt | 29 + libs/nanopb/examples/simple/simple.c | 71 + libs/nanopb/examples/simple/simple.proto | 9 + libs/nanopb/examples/using_double_on_avr/Makefile | 24 + .../nanopb/examples/using_double_on_avr/README.txt | 25 + .../examples/using_double_on_avr/decode_double.c | 33 + .../using_double_on_avr/double_conversion.c | 123 + .../using_double_on_avr/double_conversion.h | 26 + .../examples/using_double_on_avr/doubleproto.proto | 15 + .../examples/using_double_on_avr/encode_double.c | 25 + .../using_double_on_avr/test_conversions.c | 56 + libs/nanopb/examples/using_union_messages/Makefile | 20 + .../examples/using_union_messages/README.txt | 52 + libs/nanopb/examples/using_union_messages/decode.c | 96 + libs/nanopb/examples/using_union_messages/encode.c | 85 + .../examples/using_union_messages/unionproto.proto | 32 + libs/nanopb/extra/FindNanopb.cmake | 274 + libs/nanopb/extra/nanopb-config-version.cmake.in | 11 + libs/nanopb/extra/nanopb-config.cmake | 1 + libs/nanopb/extra/nanopb.mk | 37 + libs/nanopb/extra/pb_syshdr.h | 112 + libs/nanopb/generator/nanopb/options.proto | 120 + libs/nanopb/generator/nanopb_generator.py | 1671 +++ libs/nanopb/generator/proto/Makefile | 4 + libs/nanopb/generator/proto/__init__.py | 0 .../proto/google/protobuf/descriptor.proto | 714 ++ libs/nanopb/generator/proto/nanopb.proto | 112 + libs/nanopb/generator/proto/plugin.proto | 148 + libs/nanopb/generator/protoc-gen-nanopb | 13 + libs/nanopb/generator/protoc-gen-nanopb.bat | 12 + libs/nanopb/library.json | 23 + libs/nanopb/pb.h | 583 + libs/nanopb/pb_common.c | 97 + libs/nanopb/pb_common.h | 42 + libs/nanopb/pb_decode.c | 1388 +++ libs/nanopb/pb_decode.h | 153 + libs/nanopb/pb_encode.c | 803 ++ libs/nanopb/pb_encode.h | 154 + libs/nanopb/tests/Makefile | 21 + libs/nanopb/tests/SConstruct | 157 + libs/nanopb/tests/alltypes/SConscript | 35 + libs/nanopb/tests/alltypes/alltypes.options | 3 + libs/nanopb/tests/alltypes/alltypes.proto | 125 + libs/nanopb/tests/alltypes/decode_alltypes.c | 229 + libs/nanopb/tests/alltypes/encode_alltypes.c | 155 + libs/nanopb/tests/alltypes_callback/SConscript | 28 + .../tests/alltypes_callback/alltypes.options | 8 + .../alltypes_callback/decode_alltypes_callback.c | 442 + .../alltypes_callback/encode_alltypes_callback.c | 411 + libs/nanopb/tests/alltypes_pointer/SConscript | 40 + .../nanopb/tests/alltypes_pointer/alltypes.options | 4 + .../alltypes_pointer/decode_alltypes_pointer.c | 186 + .../alltypes_pointer/encode_alltypes_pointer.c | 200 + libs/nanopb/tests/alltypes_proto3/SConscript | 45 + libs/nanopb/tests/alltypes_proto3/alltypes.options | 4 + libs/nanopb/tests/alltypes_proto3/alltypes.proto | 100 + .../nanopb/tests/alltypes_proto3/decode_alltypes.c | 167 + .../nanopb/tests/alltypes_proto3/encode_alltypes.c | 111 + .../tests/alltypes_proto3_callback/SConscript | 23 + .../alltypes_proto3_callback/alltypes.options | 8 + .../decode_alltypes_callback.c | 376 + .../encode_alltypes_callback.c | 343 + libs/nanopb/tests/anonymous_oneof/SConscript | 30 + libs/nanopb/tests/anonymous_oneof/decode_oneof.c | 88 + libs/nanopb/tests/anonymous_oneof/oneof.proto | 23 + .../tests/backwards_compatibility/SConscript | 11 + .../backwards_compatibility/alltypes_legacy.c | 153 + .../backwards_compatibility/alltypes_legacy.h | 274 + .../alltypes_legacy.options | 3 + .../backwards_compatibility/alltypes_legacy.proto | 110 + .../tests/backwards_compatibility/decode_legacy.c | 199 + .../tests/backwards_compatibility/encode_legacy.c | 135 + libs/nanopb/tests/basic_buffer/SConscript | 12 + libs/nanopb/tests/basic_buffer/decode_buffer.c | 88 + libs/nanopb/tests/basic_buffer/encode_buffer.c | 38 + libs/nanopb/tests/basic_stream/SConscript | 12 + libs/nanopb/tests/basic_stream/decode_stream.c | 84 + libs/nanopb/tests/basic_stream/encode_stream.c | 40 + libs/nanopb/tests/buffer_only/SConscript | 28 + libs/nanopb/tests/callbacks/SConscript | 14 + libs/nanopb/tests/callbacks/callbacks.proto | 18 + libs/nanopb/tests/callbacks/decode_callbacks.c | 97 + libs/nanopb/tests/callbacks/encode_callbacks.c | 92 + libs/nanopb/tests/common/SConscript | 48 + libs/nanopb/tests/common/malloc_wrappers.c | 54 + libs/nanopb/tests/common/malloc_wrappers.h | 7 + libs/nanopb/tests/common/malloc_wrappers_syshdr.h | 15 + libs/nanopb/tests/common/person.proto | 22 + libs/nanopb/tests/common/test_helpers.h | 17 + libs/nanopb/tests/common/unittestproto.proto | 43 + libs/nanopb/tests/common/unittests.h | 14 + libs/nanopb/tests/cxx_main_program/SConscript | 25 + libs/nanopb/tests/cyclic_messages/SConscript | 11 + libs/nanopb/tests/cyclic_messages/cyclic.proto | 27 + .../tests/cyclic_messages/cyclic_callback.options | 7 + .../tests/cyclic_messages/encode_cyclic_callback.c | 148 + libs/nanopb/tests/decode_unittests/SConscript | 4 + .../tests/decode_unittests/decode_unittests.c | 388 + libs/nanopb/tests/encode_unittests/SConscript | 5 + .../tests/encode_unittests/encode_unittests.c | 355 + libs/nanopb/tests/enum_sizes/SConscript | 12 + libs/nanopb/tests/enum_sizes/enumsizes.proto | 86 + libs/nanopb/tests/enum_sizes/enumsizes_unittests.c | 72 + libs/nanopb/tests/enum_to_string/SConscript | 7 + libs/nanopb/tests/enum_to_string/enum.proto | 19 + libs/nanopb/tests/enum_to_string/enum_to_string.c | 19 + libs/nanopb/tests/extensions/SConscript | 16 + libs/nanopb/tests/extensions/decode_extensions.c | 60 + libs/nanopb/tests/extensions/encode_extensions.c | 54 + libs/nanopb/tests/extensions/extensions.options | 1 + libs/nanopb/tests/extensions/extensions.proto | 19 + libs/nanopb/tests/extra_fields/SConscript | 16 + .../extra_fields/alltypes_with_extra_fields.pb | Bin 0 -> 523 bytes .../extra_fields/person_with_extra_field.expected | 14 + .../tests/extra_fields/person_with_extra_field.pb | Bin 0 -> 124 bytes libs/nanopb/tests/field_size_16/SConscript | 29 + libs/nanopb/tests/field_size_16/alltypes.options | 4 + libs/nanopb/tests/field_size_16/alltypes.proto | 123 + libs/nanopb/tests/field_size_16_proto3/SConscript | 34 + .../tests/field_size_16_proto3/alltypes.options | 4 + .../tests/field_size_16_proto3/alltypes.proto | 100 + .../tests/field_size_16_proto3/decode_alltypes.c | 167 + .../tests/field_size_16_proto3/encode_alltypes.c | 111 + libs/nanopb/tests/field_size_32/SConscript | 29 + libs/nanopb/tests/field_size_32/alltypes.options | 3 + libs/nanopb/tests/field_size_32/alltypes.proto | 123 + libs/nanopb/tests/fuzztest/SConscript | 43 + .../nanopb/tests/fuzztest/alltypes_pointer.options | 3 + libs/nanopb/tests/fuzztest/alltypes_static.options | 4 + libs/nanopb/tests/fuzztest/fuzzstub.c | 189 + libs/nanopb/tests/fuzztest/fuzztest.c | 432 + libs/nanopb/tests/fuzztest/generate_message.c | 101 + libs/nanopb/tests/fuzztest/run_radamsa.sh | 12 + libs/nanopb/tests/fuzztest/sample_data/sample1.pb | Bin 0 -> 573 bytes libs/nanopb/tests/fuzztest/sample_data/sample2.pb | Bin 0 -> 466 bytes libs/nanopb/tests/inline/SConscript | 16 + libs/nanopb/tests/inline/inline.expected | 3 + libs/nanopb/tests/inline/inline.proto | 17 + libs/nanopb/tests/inline/inline_unittests.c | 73 + libs/nanopb/tests/intsizes/SConscript | 12 + libs/nanopb/tests/intsizes/intsizes.proto | 41 + libs/nanopb/tests/intsizes/intsizes_unittests.c | 122 + libs/nanopb/tests/io_errors/SConscript | 15 + libs/nanopb/tests/io_errors/alltypes.options | 3 + libs/nanopb/tests/io_errors/io_errors.c | 140 + libs/nanopb/tests/io_errors_pointers/SConscript | 26 + .../tests/io_errors_pointers/alltypes.options | 3 + libs/nanopb/tests/mem_release/SConscript | 13 + libs/nanopb/tests/mem_release/mem_release.c | 187 + libs/nanopb/tests/mem_release/mem_release.proto | 35 + libs/nanopb/tests/message_sizes/SConscript | 11 + libs/nanopb/tests/message_sizes/dummy.c | 9 + libs/nanopb/tests/message_sizes/messages1.proto | 29 + libs/nanopb/tests/message_sizes/messages2.proto | 10 + libs/nanopb/tests/missing_fields/SConscript | 8 + libs/nanopb/tests/missing_fields/missing_fields.c | 53 + .../tests/missing_fields/missing_fields.proto | 140 + libs/nanopb/tests/multiple_files/SConscript | 16 + .../nanopb/tests/multiple_files/multifile1.options | 1 + libs/nanopb/tests/multiple_files/multifile1.proto | 34 + libs/nanopb/tests/multiple_files/multifile2.proto | 22 + .../tests/multiple_files/subdir/multifile2.proto | 25 + .../tests/multiple_files/test_multiple_files.c | 30 + libs/nanopb/tests/no_errmsg/SConscript | 28 + libs/nanopb/tests/no_messages/SConscript | 7 + libs/nanopb/tests/no_messages/no_messages.proto | 9 + libs/nanopb/tests/oneof/SConscript | 33 + libs/nanopb/tests/oneof/decode_oneof.c | 131 + libs/nanopb/tests/oneof/encode_oneof.c | 64 + libs/nanopb/tests/oneof/oneof.proto | 32 + libs/nanopb/tests/options/SConscript | 12 + libs/nanopb/tests/options/options.expected | 20 + libs/nanopb/tests/options/options.proto | 98 + libs/nanopb/tests/options/proto3_options.expected | 4 + libs/nanopb/tests/options/proto3_options.proto | 11 + libs/nanopb/tests/package_name/SConscript | 38 + libs/nanopb/tests/regression/issue_118/SConscript | 12 + .../tests/regression/issue_118/enumdef.proto | 8 + .../tests/regression/issue_118/enumuse.proto | 7 + libs/nanopb/tests/regression/issue_125/SConscript | 9 + .../regression/issue_125/extensionbug.expected | 3 + .../regression/issue_125/extensionbug.options | 4 + .../tests/regression/issue_125/extensionbug.proto | 18 + libs/nanopb/tests/regression/issue_141/SConscript | 8 + .../tests/regression/issue_141/testproto.expected | 7 + .../tests/regression/issue_141/testproto.proto | 52 + libs/nanopb/tests/regression/issue_145/SConscript | 9 + .../tests/regression/issue_145/comments.expected | 3 + .../tests/regression/issue_145/comments.options | 6 + .../tests/regression/issue_145/comments.proto | 7 + libs/nanopb/tests/regression/issue_166/SConscript | 13 + .../tests/regression/issue_166/enum_encoded_size.c | 43 + libs/nanopb/tests/regression/issue_166/enums.proto | 18 + libs/nanopb/tests/regression/issue_172/SConscript | 16 + libs/nanopb/tests/regression/issue_172/msg_size.c | 9 + .../issue_172/submessage/submessage.options | 1 + .../issue_172/submessage/submessage.proto | 4 + libs/nanopb/tests/regression/issue_172/test.proto | 6 + libs/nanopb/tests/regression/issue_188/SConscript | 6 + libs/nanopb/tests/regression/issue_188/oneof.proto | 29 + libs/nanopb/tests/regression/issue_195/SConscript | 10 + .../tests/regression/issue_195/test.expected | 1 + libs/nanopb/tests/regression/issue_195/test.proto | 8 + libs/nanopb/tests/regression/issue_203/SConscript | 9 + libs/nanopb/tests/regression/issue_203/file1.proto | 10 + libs/nanopb/tests/regression/issue_203/file2.proto | 10 + libs/nanopb/tests/regression/issue_205/SConscript | 14 + .../tests/regression/issue_205/size_corruption.c | 12 + .../regression/issue_205/size_corruption.proto | 11 + libs/nanopb/tests/regression/issue_227/SConscript | 14 + .../tests/regression/issue_227/unaligned_uint64.c | 14 + .../regression/issue_227/unaligned_uint64.proto | 8 + libs/nanopb/tests/regression/issue_229/SConscript | 13 + .../tests/regression/issue_229/multiple_oneof.c | 35 + .../regression/issue_229/multiple_oneof.proto | 11 + libs/nanopb/tests/regression/issue_242/SConscript | 13 + .../nanopb/tests/regression/issue_242/zero_value.c | 51 + .../tests/regression/issue_242/zero_value.proto | 15 + libs/nanopb/tests/regression/issue_247/SConscript | 14 + libs/nanopb/tests/regression/issue_247/padding.c | 32 + .../tests/regression/issue_247/padding.proto | 12 + libs/nanopb/tests/regression/issue_249/SConscript | 12 + libs/nanopb/tests/regression/issue_249/test.c | 59 + libs/nanopb/tests/regression/issue_249/test.proto | 10 + libs/nanopb/tests/regression/issue_253/SConscript | 15 + .../tests/regression/issue_253/short_array.c | 24 + .../tests/regression/issue_253/short_array.proto | 7 + libs/nanopb/tests/regression/issue_256/SConscript | 16 + .../tests/regression/issue_256/submsg_array.c | 38 + .../tests/regression/issue_256/submsg_array.proto | 11 + libs/nanopb/tests/site_scons/site_init.py | 109 + libs/nanopb/tests/site_scons/site_tools/nanopb.py | 126 + libs/nanopb/tests/special_characters/SConscript | 6 + .../funny-proto+name has.characters.proto | 1 + libs/nanopb/tests/splint/SConscript | 16 + libs/nanopb/tests/splint/splint.rc | 37 + libs/nanopb/tools/make_linux_package.sh | 50 + libs/nanopb/tools/make_mac_package.sh | 49 + libs/nanopb/tools/make_windows_package.sh | 55 + libs/nanopb/tools/set_version.sh | 13 + libs/openxc-message-format/.gitignore | 1 + libs/openxc-message-format/CHANGELOG.md | 57 + libs/openxc-message-format/CMakeLists.txt | 43 + libs/openxc-message-format/JSON.mkd | 435 + libs/openxc-message-format/LICENSE | 24 + libs/openxc-message-format/Makefile | 11 + libs/openxc-message-format/README.md | 177 + .../benchmark/proto/.gitignore | 1 + .../benchmark/proto/compare_sizes.py | 96 + libs/openxc-message-format/gen/README.mkd | 11 + libs/openxc-message-format/gen/cpp/openxc.pb | Bin 0 -> 3497 bytes libs/openxc-message-format/gen/cpp/openxc.pb.c | 184 + libs/openxc-message-format/gen/cpp/openxc.pb.h | 426 + .../gen/java/com/openxc/BinaryMessages.java | 12099 +++++++++++++++++++ .../openxc-message-format/gen/python/openxc_pb2.py | 1316 ++ libs/openxc-message-format/openxc.options | 10 + libs/openxc-message-format/openxc.proto | 174 + libs/openxc-message-format/pip-requirements.txt | 1 + libs/openxc-message-format/script/bootstrap.sh | 179 + libs/uds-c/.gitignore | 5 + libs/uds-c/.travis.yml | 8 + libs/uds-c/CHANGELOG.mkd | 9 + libs/uds-c/CMakeLists.txt | 41 + libs/uds-c/LICENSE | 24 + libs/uds-c/Makefile | 56 + libs/uds-c/README.mkd | 196 + libs/uds-c/runtests.sh | 17 + libs/uds-c/src/uds/extras.c | 39 + libs/uds-c/src/uds/extras.h | 71 + libs/uds-c/src/uds/uds.c | 400 + libs/uds-c/src/uds/uds.h | 165 + libs/uds-c/src/uds/uds_types.h | 200 + libs/uds-c/tests/common.c | 43 + libs/uds-c/tests/test_core.c | 526 + 352 files changed, 45591 insertions(+) create mode 100644 libs/CMakeLists.txt create mode 100644 libs/bitfield-c/.gitignore create mode 100644 libs/bitfield-c/.travis.yml create mode 100644 libs/bitfield-c/CHANGELOG.mkd create mode 100644 libs/bitfield-c/CMakeLists.txt create mode 100644 libs/bitfield-c/LICENSE create mode 100644 libs/bitfield-c/Makefile create mode 100644 libs/bitfield-c/README.mkd create mode 100644 libs/bitfield-c/runtests.sh create mode 100644 libs/bitfield-c/src/bitfield/8byte.c create mode 100644 libs/bitfield-c/src/bitfield/8byte.h create mode 100644 libs/bitfield-c/src/bitfield/bitarray.c create mode 100644 libs/bitfield-c/src/bitfield/bitfield.c create mode 100644 libs/bitfield-c/src/bitfield/bitfield.h create mode 100644 libs/bitfield-c/src/canutil/read.c create mode 100644 libs/bitfield-c/src/canutil/read.h create mode 100644 libs/bitfield-c/src/canutil/write.c create mode 100644 libs/bitfield-c/src/canutil/write.h create mode 100644 libs/bitfield-c/tests/8byte_tests.c create mode 100644 libs/bitfield-c/tests/bitfield_tests.c create mode 100644 libs/bitfield-c/tests/read_tests.c create mode 100644 libs/bitfield-c/tests/write_tests.c create mode 100644 libs/ini-config/CMakeLists.txt create mode 100644 libs/ini-config/ini-config.cpp create mode 100644 libs/ini-config/ini-config.hpp create mode 100644 libs/isotp-c/.gitignore create mode 100644 libs/isotp-c/.travis.yml create mode 100644 libs/isotp-c/CHANGELOG.mkd create mode 100644 libs/isotp-c/CMakeLists.txt create mode 100644 libs/isotp-c/LICENSE create mode 100644 libs/isotp-c/Makefile create mode 100644 libs/isotp-c/README.mkd create mode 100644 libs/isotp-c/runtests.sh create mode 100644 libs/isotp-c/src/isotp/isotp.c create mode 100644 libs/isotp-c/src/isotp/isotp.h create mode 100644 libs/isotp-c/src/isotp/isotp_types.h create mode 100644 libs/isotp-c/src/isotp/receive.c create mode 100644 libs/isotp-c/src/isotp/receive.h create mode 100644 libs/isotp-c/src/isotp/send.c create mode 100644 libs/isotp-c/src/isotp/send.h create mode 100644 libs/isotp-c/tests/common.c create mode 100644 libs/isotp-c/tests/test_core.c create mode 100644 libs/isotp-c/tests/test_receive.c create mode 100644 libs/isotp-c/tests/test_send.c create mode 100644 libs/nanopb/.gitignore create mode 100644 libs/nanopb/.travis.yml create mode 100644 libs/nanopb/AUTHORS create mode 100644 libs/nanopb/BUILD create mode 100644 libs/nanopb/CHANGELOG.txt create mode 100644 libs/nanopb/CONTRIBUTING.md create mode 100644 libs/nanopb/LICENSE.txt create mode 100644 libs/nanopb/README.md create mode 100644 libs/nanopb/docs/Makefile create mode 100644 libs/nanopb/docs/concepts.rst create mode 100644 libs/nanopb/docs/generator_flow.svg create mode 100644 libs/nanopb/docs/index.rst create mode 100644 libs/nanopb/docs/logo/logo.png create mode 100644 libs/nanopb/docs/logo/logo.svg create mode 100644 libs/nanopb/docs/logo/logo16px.png create mode 100644 libs/nanopb/docs/logo/logo48px.png create mode 100644 libs/nanopb/docs/lsr.css create mode 100644 libs/nanopb/docs/menu.rst create mode 100644 libs/nanopb/docs/migration.rst create mode 100644 libs/nanopb/docs/reference.rst create mode 100644 libs/nanopb/docs/security.rst create mode 100644 libs/nanopb/examples/cmake_simple/CMakeLists.txt create mode 100644 libs/nanopb/examples/cmake_simple/README.txt create mode 100644 libs/nanopb/examples/cmake_simple/simple.c create mode 100644 libs/nanopb/examples/cmake_simple/simple.proto create mode 100644 libs/nanopb/examples/network_server/Makefile create mode 100644 libs/nanopb/examples/network_server/README.txt create mode 100644 libs/nanopb/examples/network_server/client.c create mode 100644 libs/nanopb/examples/network_server/common.c create mode 100644 libs/nanopb/examples/network_server/common.h create mode 100644 libs/nanopb/examples/network_server/fileproto.options create mode 100644 libs/nanopb/examples/network_server/fileproto.proto create mode 100644 libs/nanopb/examples/network_server/server.c create mode 100644 libs/nanopb/examples/simple/Makefile create mode 100644 libs/nanopb/examples/simple/README.txt create mode 100644 libs/nanopb/examples/simple/simple.c create mode 100644 libs/nanopb/examples/simple/simple.proto create mode 100644 libs/nanopb/examples/using_double_on_avr/Makefile create mode 100644 libs/nanopb/examples/using_double_on_avr/README.txt create mode 100644 libs/nanopb/examples/using_double_on_avr/decode_double.c create mode 100644 libs/nanopb/examples/using_double_on_avr/double_conversion.c create mode 100644 libs/nanopb/examples/using_double_on_avr/double_conversion.h create mode 100644 libs/nanopb/examples/using_double_on_avr/doubleproto.proto create mode 100644 libs/nanopb/examples/using_double_on_avr/encode_double.c create mode 100644 libs/nanopb/examples/using_double_on_avr/test_conversions.c create mode 100644 libs/nanopb/examples/using_union_messages/Makefile create mode 100644 libs/nanopb/examples/using_union_messages/README.txt create mode 100644 libs/nanopb/examples/using_union_messages/decode.c create mode 100644 libs/nanopb/examples/using_union_messages/encode.c create mode 100644 libs/nanopb/examples/using_union_messages/unionproto.proto create mode 100644 libs/nanopb/extra/FindNanopb.cmake create mode 100644 libs/nanopb/extra/nanopb-config-version.cmake.in create mode 100644 libs/nanopb/extra/nanopb-config.cmake create mode 100644 libs/nanopb/extra/nanopb.mk create mode 100644 libs/nanopb/extra/pb_syshdr.h create mode 100644 libs/nanopb/generator/nanopb/options.proto create mode 100755 libs/nanopb/generator/nanopb_generator.py create mode 100644 libs/nanopb/generator/proto/Makefile create mode 100644 libs/nanopb/generator/proto/__init__.py create mode 100644 libs/nanopb/generator/proto/google/protobuf/descriptor.proto create mode 100644 libs/nanopb/generator/proto/nanopb.proto create mode 100644 libs/nanopb/generator/proto/plugin.proto create mode 100755 libs/nanopb/generator/protoc-gen-nanopb create mode 100644 libs/nanopb/generator/protoc-gen-nanopb.bat create mode 100644 libs/nanopb/library.json create mode 100644 libs/nanopb/pb.h create mode 100644 libs/nanopb/pb_common.c create mode 100644 libs/nanopb/pb_common.h create mode 100644 libs/nanopb/pb_decode.c create mode 100644 libs/nanopb/pb_decode.h create mode 100644 libs/nanopb/pb_encode.c create mode 100644 libs/nanopb/pb_encode.h create mode 100644 libs/nanopb/tests/Makefile create mode 100644 libs/nanopb/tests/SConstruct create mode 100644 libs/nanopb/tests/alltypes/SConscript create mode 100644 libs/nanopb/tests/alltypes/alltypes.options create mode 100644 libs/nanopb/tests/alltypes/alltypes.proto create mode 100644 libs/nanopb/tests/alltypes/decode_alltypes.c create mode 100644 libs/nanopb/tests/alltypes/encode_alltypes.c create mode 100644 libs/nanopb/tests/alltypes_callback/SConscript create mode 100644 libs/nanopb/tests/alltypes_callback/alltypes.options create mode 100644 libs/nanopb/tests/alltypes_callback/decode_alltypes_callback.c create mode 100644 libs/nanopb/tests/alltypes_callback/encode_alltypes_callback.c create mode 100644 libs/nanopb/tests/alltypes_pointer/SConscript create mode 100644 libs/nanopb/tests/alltypes_pointer/alltypes.options create mode 100644 libs/nanopb/tests/alltypes_pointer/decode_alltypes_pointer.c create mode 100644 libs/nanopb/tests/alltypes_pointer/encode_alltypes_pointer.c create mode 100644 libs/nanopb/tests/alltypes_proto3/SConscript create mode 100644 libs/nanopb/tests/alltypes_proto3/alltypes.options create mode 100644 libs/nanopb/tests/alltypes_proto3/alltypes.proto create mode 100644 libs/nanopb/tests/alltypes_proto3/decode_alltypes.c create mode 100644 libs/nanopb/tests/alltypes_proto3/encode_alltypes.c create mode 100644 libs/nanopb/tests/alltypes_proto3_callback/SConscript create mode 100644 libs/nanopb/tests/alltypes_proto3_callback/alltypes.options create mode 100644 libs/nanopb/tests/alltypes_proto3_callback/decode_alltypes_callback.c create mode 100644 libs/nanopb/tests/alltypes_proto3_callback/encode_alltypes_callback.c create mode 100644 libs/nanopb/tests/anonymous_oneof/SConscript create mode 100644 libs/nanopb/tests/anonymous_oneof/decode_oneof.c create mode 100644 libs/nanopb/tests/anonymous_oneof/oneof.proto create mode 100644 libs/nanopb/tests/backwards_compatibility/SConscript create mode 100644 libs/nanopb/tests/backwards_compatibility/alltypes_legacy.c create mode 100644 libs/nanopb/tests/backwards_compatibility/alltypes_legacy.h create mode 100644 libs/nanopb/tests/backwards_compatibility/alltypes_legacy.options create mode 100644 libs/nanopb/tests/backwards_compatibility/alltypes_legacy.proto create mode 100644 libs/nanopb/tests/backwards_compatibility/decode_legacy.c create mode 100644 libs/nanopb/tests/backwards_compatibility/encode_legacy.c create mode 100644 libs/nanopb/tests/basic_buffer/SConscript create mode 100644 libs/nanopb/tests/basic_buffer/decode_buffer.c create mode 100644 libs/nanopb/tests/basic_buffer/encode_buffer.c create mode 100644 libs/nanopb/tests/basic_stream/SConscript create mode 100644 libs/nanopb/tests/basic_stream/decode_stream.c create mode 100644 libs/nanopb/tests/basic_stream/encode_stream.c create mode 100644 libs/nanopb/tests/buffer_only/SConscript create mode 100644 libs/nanopb/tests/callbacks/SConscript create mode 100644 libs/nanopb/tests/callbacks/callbacks.proto create mode 100644 libs/nanopb/tests/callbacks/decode_callbacks.c create mode 100644 libs/nanopb/tests/callbacks/encode_callbacks.c create mode 100644 libs/nanopb/tests/common/SConscript create mode 100644 libs/nanopb/tests/common/malloc_wrappers.c create mode 100644 libs/nanopb/tests/common/malloc_wrappers.h create mode 100644 libs/nanopb/tests/common/malloc_wrappers_syshdr.h create mode 100644 libs/nanopb/tests/common/person.proto create mode 100644 libs/nanopb/tests/common/test_helpers.h create mode 100644 libs/nanopb/tests/common/unittestproto.proto create mode 100644 libs/nanopb/tests/common/unittests.h create mode 100644 libs/nanopb/tests/cxx_main_program/SConscript create mode 100644 libs/nanopb/tests/cyclic_messages/SConscript create mode 100644 libs/nanopb/tests/cyclic_messages/cyclic.proto create mode 100644 libs/nanopb/tests/cyclic_messages/cyclic_callback.options create mode 100644 libs/nanopb/tests/cyclic_messages/encode_cyclic_callback.c create mode 100644 libs/nanopb/tests/decode_unittests/SConscript create mode 100644 libs/nanopb/tests/decode_unittests/decode_unittests.c create mode 100644 libs/nanopb/tests/encode_unittests/SConscript create mode 100644 libs/nanopb/tests/encode_unittests/encode_unittests.c create mode 100644 libs/nanopb/tests/enum_sizes/SConscript create mode 100644 libs/nanopb/tests/enum_sizes/enumsizes.proto create mode 100644 libs/nanopb/tests/enum_sizes/enumsizes_unittests.c create mode 100644 libs/nanopb/tests/enum_to_string/SConscript create mode 100644 libs/nanopb/tests/enum_to_string/enum.proto create mode 100644 libs/nanopb/tests/enum_to_string/enum_to_string.c create mode 100644 libs/nanopb/tests/extensions/SConscript create mode 100644 libs/nanopb/tests/extensions/decode_extensions.c create mode 100644 libs/nanopb/tests/extensions/encode_extensions.c create mode 100644 libs/nanopb/tests/extensions/extensions.options create mode 100644 libs/nanopb/tests/extensions/extensions.proto create mode 100644 libs/nanopb/tests/extra_fields/SConscript create mode 100644 libs/nanopb/tests/extra_fields/alltypes_with_extra_fields.pb create mode 100644 libs/nanopb/tests/extra_fields/person_with_extra_field.expected create mode 100644 libs/nanopb/tests/extra_fields/person_with_extra_field.pb create mode 100644 libs/nanopb/tests/field_size_16/SConscript create mode 100644 libs/nanopb/tests/field_size_16/alltypes.options create mode 100644 libs/nanopb/tests/field_size_16/alltypes.proto create mode 100644 libs/nanopb/tests/field_size_16_proto3/SConscript create mode 100644 libs/nanopb/tests/field_size_16_proto3/alltypes.options create mode 100644 libs/nanopb/tests/field_size_16_proto3/alltypes.proto create mode 100644 libs/nanopb/tests/field_size_16_proto3/decode_alltypes.c create mode 100644 libs/nanopb/tests/field_size_16_proto3/encode_alltypes.c create mode 100644 libs/nanopb/tests/field_size_32/SConscript create mode 100644 libs/nanopb/tests/field_size_32/alltypes.options create mode 100644 libs/nanopb/tests/field_size_32/alltypes.proto create mode 100644 libs/nanopb/tests/fuzztest/SConscript create mode 100644 libs/nanopb/tests/fuzztest/alltypes_pointer.options create mode 100644 libs/nanopb/tests/fuzztest/alltypes_static.options create mode 100644 libs/nanopb/tests/fuzztest/fuzzstub.c create mode 100644 libs/nanopb/tests/fuzztest/fuzztest.c create mode 100644 libs/nanopb/tests/fuzztest/generate_message.c create mode 100755 libs/nanopb/tests/fuzztest/run_radamsa.sh create mode 100644 libs/nanopb/tests/fuzztest/sample_data/sample1.pb create mode 100644 libs/nanopb/tests/fuzztest/sample_data/sample2.pb create mode 100644 libs/nanopb/tests/inline/SConscript create mode 100644 libs/nanopb/tests/inline/inline.expected create mode 100644 libs/nanopb/tests/inline/inline.proto create mode 100644 libs/nanopb/tests/inline/inline_unittests.c create mode 100644 libs/nanopb/tests/intsizes/SConscript create mode 100644 libs/nanopb/tests/intsizes/intsizes.proto create mode 100644 libs/nanopb/tests/intsizes/intsizes_unittests.c create mode 100644 libs/nanopb/tests/io_errors/SConscript create mode 100644 libs/nanopb/tests/io_errors/alltypes.options create mode 100644 libs/nanopb/tests/io_errors/io_errors.c create mode 100644 libs/nanopb/tests/io_errors_pointers/SConscript create mode 100644 libs/nanopb/tests/io_errors_pointers/alltypes.options create mode 100644 libs/nanopb/tests/mem_release/SConscript create mode 100644 libs/nanopb/tests/mem_release/mem_release.c create mode 100644 libs/nanopb/tests/mem_release/mem_release.proto create mode 100644 libs/nanopb/tests/message_sizes/SConscript create mode 100644 libs/nanopb/tests/message_sizes/dummy.c create mode 100644 libs/nanopb/tests/message_sizes/messages1.proto create mode 100644 libs/nanopb/tests/message_sizes/messages2.proto create mode 100644 libs/nanopb/tests/missing_fields/SConscript create mode 100644 libs/nanopb/tests/missing_fields/missing_fields.c create mode 100644 libs/nanopb/tests/missing_fields/missing_fields.proto create mode 100644 libs/nanopb/tests/multiple_files/SConscript create mode 100644 libs/nanopb/tests/multiple_files/multifile1.options create mode 100644 libs/nanopb/tests/multiple_files/multifile1.proto create mode 100644 libs/nanopb/tests/multiple_files/multifile2.proto create mode 100644 libs/nanopb/tests/multiple_files/subdir/multifile2.proto create mode 100644 libs/nanopb/tests/multiple_files/test_multiple_files.c create mode 100644 libs/nanopb/tests/no_errmsg/SConscript create mode 100644 libs/nanopb/tests/no_messages/SConscript create mode 100644 libs/nanopb/tests/no_messages/no_messages.proto create mode 100644 libs/nanopb/tests/oneof/SConscript create mode 100644 libs/nanopb/tests/oneof/decode_oneof.c create mode 100644 libs/nanopb/tests/oneof/encode_oneof.c create mode 100644 libs/nanopb/tests/oneof/oneof.proto create mode 100644 libs/nanopb/tests/options/SConscript create mode 100644 libs/nanopb/tests/options/options.expected create mode 100644 libs/nanopb/tests/options/options.proto create mode 100644 libs/nanopb/tests/options/proto3_options.expected create mode 100644 libs/nanopb/tests/options/proto3_options.proto create mode 100644 libs/nanopb/tests/package_name/SConscript create mode 100644 libs/nanopb/tests/regression/issue_118/SConscript create mode 100644 libs/nanopb/tests/regression/issue_118/enumdef.proto create mode 100644 libs/nanopb/tests/regression/issue_118/enumuse.proto create mode 100644 libs/nanopb/tests/regression/issue_125/SConscript create mode 100644 libs/nanopb/tests/regression/issue_125/extensionbug.expected create mode 100644 libs/nanopb/tests/regression/issue_125/extensionbug.options create mode 100644 libs/nanopb/tests/regression/issue_125/extensionbug.proto create mode 100644 libs/nanopb/tests/regression/issue_141/SConscript create mode 100644 libs/nanopb/tests/regression/issue_141/testproto.expected create mode 100644 libs/nanopb/tests/regression/issue_141/testproto.proto create mode 100644 libs/nanopb/tests/regression/issue_145/SConscript create mode 100644 libs/nanopb/tests/regression/issue_145/comments.expected create mode 100644 libs/nanopb/tests/regression/issue_145/comments.options create mode 100644 libs/nanopb/tests/regression/issue_145/comments.proto create mode 100644 libs/nanopb/tests/regression/issue_166/SConscript create mode 100644 libs/nanopb/tests/regression/issue_166/enum_encoded_size.c create mode 100644 libs/nanopb/tests/regression/issue_166/enums.proto create mode 100644 libs/nanopb/tests/regression/issue_172/SConscript create mode 100644 libs/nanopb/tests/regression/issue_172/msg_size.c create mode 100644 libs/nanopb/tests/regression/issue_172/submessage/submessage.options create mode 100644 libs/nanopb/tests/regression/issue_172/submessage/submessage.proto create mode 100644 libs/nanopb/tests/regression/issue_172/test.proto create mode 100644 libs/nanopb/tests/regression/issue_188/SConscript create mode 100644 libs/nanopb/tests/regression/issue_188/oneof.proto create mode 100644 libs/nanopb/tests/regression/issue_195/SConscript create mode 100644 libs/nanopb/tests/regression/issue_195/test.expected create mode 100644 libs/nanopb/tests/regression/issue_195/test.proto create mode 100644 libs/nanopb/tests/regression/issue_203/SConscript create mode 100644 libs/nanopb/tests/regression/issue_203/file1.proto create mode 100644 libs/nanopb/tests/regression/issue_203/file2.proto create mode 100644 libs/nanopb/tests/regression/issue_205/SConscript create mode 100644 libs/nanopb/tests/regression/issue_205/size_corruption.c create mode 100644 libs/nanopb/tests/regression/issue_205/size_corruption.proto create mode 100644 libs/nanopb/tests/regression/issue_227/SConscript create mode 100644 libs/nanopb/tests/regression/issue_227/unaligned_uint64.c create mode 100644 libs/nanopb/tests/regression/issue_227/unaligned_uint64.proto create mode 100644 libs/nanopb/tests/regression/issue_229/SConscript create mode 100644 libs/nanopb/tests/regression/issue_229/multiple_oneof.c create mode 100644 libs/nanopb/tests/regression/issue_229/multiple_oneof.proto create mode 100644 libs/nanopb/tests/regression/issue_242/SConscript create mode 100644 libs/nanopb/tests/regression/issue_242/zero_value.c create mode 100644 libs/nanopb/tests/regression/issue_242/zero_value.proto create mode 100644 libs/nanopb/tests/regression/issue_247/SConscript create mode 100644 libs/nanopb/tests/regression/issue_247/padding.c create mode 100644 libs/nanopb/tests/regression/issue_247/padding.proto create mode 100644 libs/nanopb/tests/regression/issue_249/SConscript create mode 100644 libs/nanopb/tests/regression/issue_249/test.c create mode 100644 libs/nanopb/tests/regression/issue_249/test.proto create mode 100644 libs/nanopb/tests/regression/issue_253/SConscript create mode 100644 libs/nanopb/tests/regression/issue_253/short_array.c create mode 100644 libs/nanopb/tests/regression/issue_253/short_array.proto create mode 100644 libs/nanopb/tests/regression/issue_256/SConscript create mode 100644 libs/nanopb/tests/regression/issue_256/submsg_array.c create mode 100644 libs/nanopb/tests/regression/issue_256/submsg_array.proto create mode 100644 libs/nanopb/tests/site_scons/site_init.py create mode 100644 libs/nanopb/tests/site_scons/site_tools/nanopb.py create mode 100644 libs/nanopb/tests/special_characters/SConscript create mode 100644 libs/nanopb/tests/special_characters/funny-proto+name has.characters.proto create mode 100644 libs/nanopb/tests/splint/SConscript create mode 100644 libs/nanopb/tests/splint/splint.rc create mode 100755 libs/nanopb/tools/make_linux_package.sh create mode 100755 libs/nanopb/tools/make_mac_package.sh create mode 100755 libs/nanopb/tools/make_windows_package.sh create mode 100755 libs/nanopb/tools/set_version.sh create mode 100644 libs/openxc-message-format/.gitignore create mode 100644 libs/openxc-message-format/CHANGELOG.md create mode 100644 libs/openxc-message-format/CMakeLists.txt create mode 100644 libs/openxc-message-format/JSON.mkd create mode 100644 libs/openxc-message-format/LICENSE create mode 100644 libs/openxc-message-format/Makefile create mode 100644 libs/openxc-message-format/README.md create mode 100644 libs/openxc-message-format/benchmark/proto/.gitignore create mode 100755 libs/openxc-message-format/benchmark/proto/compare_sizes.py create mode 100644 libs/openxc-message-format/gen/README.mkd create mode 100644 libs/openxc-message-format/gen/cpp/openxc.pb create mode 100644 libs/openxc-message-format/gen/cpp/openxc.pb.c create mode 100644 libs/openxc-message-format/gen/cpp/openxc.pb.h create mode 100644 libs/openxc-message-format/gen/java/com/openxc/BinaryMessages.java create mode 100644 libs/openxc-message-format/gen/python/openxc_pb2.py create mode 100644 libs/openxc-message-format/openxc.options create mode 100644 libs/openxc-message-format/openxc.proto create mode 100644 libs/openxc-message-format/pip-requirements.txt create mode 100755 libs/openxc-message-format/script/bootstrap.sh create mode 100644 libs/uds-c/.gitignore create mode 100644 libs/uds-c/.travis.yml create mode 100644 libs/uds-c/CHANGELOG.mkd create mode 100644 libs/uds-c/CMakeLists.txt create mode 100644 libs/uds-c/LICENSE create mode 100644 libs/uds-c/Makefile create mode 100644 libs/uds-c/README.mkd create mode 100644 libs/uds-c/runtests.sh create mode 100644 libs/uds-c/src/uds/extras.c create mode 100644 libs/uds-c/src/uds/extras.h create mode 100644 libs/uds-c/src/uds/uds.c create mode 100644 libs/uds-c/src/uds/uds.h create mode 100644 libs/uds-c/src/uds/uds_types.h create mode 100644 libs/uds-c/tests/common.c create mode 100644 libs/uds-c/tests/test_core.c (limited to 'libs') diff --git a/libs/CMakeLists.txt b/libs/CMakeLists.txt new file mode 100644 index 00000000..995c4e77 --- /dev/null +++ b/libs/CMakeLists.txt @@ -0,0 +1,20 @@ +########################################################################### +# Copyright 2015, 2016, 2017 IoT.bzh +# +# author: Fulup Ar Foll +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +########################################################################### + +# Add target to project dependency list +project_subdirs_add() \ No newline at end of file diff --git a/libs/bitfield-c/.gitignore b/libs/bitfield-c/.gitignore new file mode 100644 index 00000000..834a305d --- /dev/null +++ b/libs/bitfield-c/.gitignore @@ -0,0 +1,5 @@ +*.o +.DS_Store +*~ +*.bin +build diff --git a/libs/bitfield-c/.travis.yml b/libs/bitfield-c/.travis.yml new file mode 100644 index 00000000..7654abaa --- /dev/null +++ b/libs/bitfield-c/.travis.yml @@ -0,0 +1,7 @@ +language: c +compiler: + - gcc +script: make test +before_install: + - sudo apt-get update -qq + - sudo apt-get install check diff --git a/libs/bitfield-c/CHANGELOG.mkd b/libs/bitfield-c/CHANGELOG.mkd new file mode 100644 index 00000000..eea48c06 --- /dev/null +++ b/libs/bitfield-c/CHANGELOG.mkd @@ -0,0 +1,5 @@ +# Bitfield Utilities in C + +## v0.1 + +* Initial release diff --git a/libs/bitfield-c/CMakeLists.txt b/libs/bitfield-c/CMakeLists.txt new file mode 100644 index 00000000..d4c91128 --- /dev/null +++ b/libs/bitfield-c/CMakeLists.txt @@ -0,0 +1,43 @@ +########################################################################### +# Copyright 2015, 2016, 2017 IoT.bzh +# +# author: Fulup Ar Foll +# contrib: Romain Forlot +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +########################################################################### + +# Add target to project dependency list +PROJECT_TARGET_ADD(bitfield-c) + + # Define project Target + add_library(${TARGET_NAME} STATIC + src/bitfield/8byte.c + src/bitfield/bitarray.c + src/bitfield/bitfield.c + src/canutil/read.c + src/canutil/write.c) + + # Binder exposes a unique public entry point + SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + OUTPUT_NAME ${TARGET_NAME} + ) + + # Define target includes + TARGET_INCLUDE_DIRECTORIES(${TARGET_NAME} + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + + # Library dependencies (include updates automatically) + TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${link_libraries}) \ No newline at end of file diff --git a/libs/bitfield-c/LICENSE b/libs/bitfield-c/LICENSE new file mode 100644 index 00000000..330d61f4 --- /dev/null +++ b/libs/bitfield-c/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2013 Ford Motor Company +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/libs/bitfield-c/Makefile b/libs/bitfield-c/Makefile new file mode 100644 index 00000000..e93efb47 --- /dev/null +++ b/libs/bitfield-c/Makefile @@ -0,0 +1,53 @@ +CC = gcc +INCLUDES = -Isrc +CFLAGS = $(INCLUDES) -c -Wall -Werror -g -ggdb -coverage +LDFLAGS = -coverage -lm +LDLIBS = -lcheck + +TEST_DIR = tests +TEST_OBJDIR = build + +# Guard against \r\n line endings only in Cygwin +OSTYPE := $(shell uname) +ifneq ($(OSTYPE),Darwin) + OSTYPE := $(shell uname -o) + ifeq ($(OSTYPE),Cygwin) + TEST_SET_OPTS = igncr + endif +endif + +SRC = $(wildcard src/**/*.c) +OBJS = $(SRC:.c=.o) +OBJS = $(patsubst %,$(TEST_OBJDIR)/%,$(SRC:.c=.o)) +TEST_SRC = $(wildcard $(TEST_DIR)/*_tests.c) +TESTS=$(patsubst %.c,$(TEST_OBJDIR)/%.bin,$(TEST_SRC)) + +all: $(OBJS) + +test: $(TESTS) + @set -o $(TEST_SET_OPTS) >/dev/null 2>&1 + @export SHELLOPTS + @sh runtests.sh $(TEST_OBJDIR)/$(TEST_DIR) + +COVERAGE_INFO_FILENAME = coverage.info +COVERAGE_INFO_PATH = $(TEST_OBJDIR)/$(COVERAGE_INFO_FILENAME) +coverage: + @lcov --base-directory . --directory $(TEST_OBJDIR) --zerocounters -q + @make clean + @make test + @lcov --base-directory . --directory $(TEST_OBJDIR) -c -o $(TEST_OBJDIR)/coverage.info + @lcov --remove $(COVERAGE_INFO_PATH) "/usr/*" -o $(COVERAGE_INFO_PATH) + @genhtml -o $(TEST_OBJDIR)/coverage -t "isotp-c test coverage" --num-spaces 4 $(COVERAGE_INFO_PATH) + @$(BROWSER) $(TEST_OBJDIR)/coverage/index.html + @echo "$(GREEN)Coverage information generated in $(TEST_OBJDIR)/coverage/index.html.$(COLOR_RESET)" + +$(TEST_OBJDIR)/%.o: %.c + @mkdir -p $(dir $@) + $(CC) $(CFLAGS) $(CC_SYMBOLS) $(INCLUDES) -o $@ $< + +$(TEST_OBJDIR)/%.bin: $(TEST_OBJDIR)/%.o $(OBJS) $(TEST_SUPPORT_OBJS) + @mkdir -p $(dir $@) + $(CC) $(LDFLAGS) $(CC_SYMBOLS) $(INCLUDES) -o $@ $^ $(LDLIBS) + +clean: + rm -rf $(TEST_OBJDIR) diff --git a/libs/bitfield-c/README.mkd b/libs/bitfield-c/README.mkd new file mode 100644 index 00000000..439b3dd0 --- /dev/null +++ b/libs/bitfield-c/README.mkd @@ -0,0 +1,107 @@ +Bitfield Utilities in C +=========================== + +This is a C library with functions to help encode and decode Controller Area +Network (CAN) message payloads or other bitfields. + +The header files contain complete function documentation, but to get you +started, here are examples using the API: + +## Bitfield Manipulation + +The bitfields are stored in `uint8_t[]`. + + uint8_t data[4] = {0x12, 0x34, 0x56, 0x78}; + uint8_t result = get_byte(data, sizeof(data), 0); + // result = 0x12; + result = get_nibble(data, sizeof(data), 0); + // result = 0x1; + bool success = copy_bits_right_aligned(data, 4, 4, 12, result, 4) + // success == true + // result[0] == 0x2 + // result[1] == 0x34 + +## 8 Byte Helpers + +If you are dealing with 8 byte CAN messages as `uint64_t`, there are some +additional functions prefixed with `eightbyte_` that may be faster or more +useful. + +### 8 Byte Decoding + + uint64_t data = 0x8000000000000000; + uint64_t result = eightbyte_get_bitfield(data, 0, 1, false); + // result == 0x1 + + data = 0x0402574d555a0401; + result = eightbyte_get_bitfield(data, 16, 32, false); + // result = 0x574d555a; + + data = 0x00000000F34DFCFF; + result = eightbyte_get_byte(data, 0, false); + //result = 0x0 + + result = eightbyte_get_byte(data, 4, false); + //result = 0xF3 + + result = eightbyte_get_nibble(data, 10, false); + //result = 0x4; + +### 8 Byte Encoding + + uint64_t data = 0; + fail_unless(8byte_set_bitfield(1, 0, 1, &data)); + uint64_t result = eightbyte_get_bitfield(data, 0, 1, false); + ck_assert_int_eq(result, 0x1); + +### CAN Signal Encoding + +The library supports encoding floating point CAN signals as well as booleans +into a uint64_t payload. + + uint64_t payload = eightbyte_encode_float(1, 1, 3, 1, 0) + // payload == 0x1000000000000000 + + payload = eightbyte_encode_bool(true, 1, 3); + // payload == 0x1000000000000000 + +### CAN Signal Decoding + +The library supports parsing floating point CAN signals as well as booleans. + + uint64_t payload = 0xeb00000000000000; + float float_result = eightbyte_parse_float(payload, + 2, // starting bit + 4, // width of the signal's field + 1001.0, // transformation factor for the signal value + -30000.0); // transformation offset for the signal value + // float_result == -19990.0 + + bool bool_result = eightbyte_parse_bool(payload, + 0, // starting bit + 1, // width of the signal's field + 1.0, // transformation factor for the signal value + 0); // transformation offset for the signal value + // bool_result == true + +## Testing + +The library includes a test suite that uses the `check` C unit test library. It +requires the unit testing library `check`. + + $ make test + +You can also see the test coverage if you have `lcov` installed and the +`BROWSER` environment variable set to your choice of web browsers: + + $ BROWSER=google-chrome-stable make coverage + +## Authors + +Chris Peplin cpeplin@ford.com + +## License + +Copyright (c) 2013 Ford Motor Company + +Licensed under the BSD license. diff --git a/libs/bitfield-c/runtests.sh b/libs/bitfield-c/runtests.sh new file mode 100644 index 00000000..4781636b --- /dev/null +++ b/libs/bitfield-c/runtests.sh @@ -0,0 +1,17 @@ +echo "Running unit tests:" + +for i in $1/*.bin +do + if test -f $i + then + if ./$i + then + echo $i PASS + else + echo "ERROR in test $i:" + exit 1 + fi + fi +done + +echo "${txtbld}$(tput setaf 2)All unit tests passed.$(tput sgr0)" diff --git a/libs/bitfield-c/src/bitfield/8byte.c b/libs/bitfield-c/src/bitfield/8byte.c new file mode 100644 index 00000000..9325ed1b --- /dev/null +++ b/libs/bitfield-c/src/bitfield/8byte.c @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include + +#define EIGHTBYTE_BIT (8 * sizeof(uint64_t)) + +uint8_t eightbyte_get_nibble(const uint64_t source, const uint8_t nibble_index, + const bool data_is_big_endian) { + return (uint8_t) eightbyte_get_bitfield(source, NIBBLE_SIZE * nibble_index, + NIBBLE_SIZE, data_is_big_endian); +} + +uint8_t eightbyte_get_byte(uint64_t source, const uint8_t byte_index, + const bool data_is_big_endian) { + if(data_is_big_endian) { + source = __builtin_bswap64(source); + } + return (source >> (EIGHTBYTE_BIT - ((byte_index + 1) * CHAR_BIT))) & 0xFF; +} + +// TODO is this funciton necessary anymore? is it any faster for uint64_t than +// get_bitfield(data[], ...)? is the performance better on a 32 bit platform +// like the PIC32? +uint64_t eightbyte_get_bitfield(uint64_t source, const uint16_t offset, + const uint16_t bit_count, const bool data_is_big_endian) { + int startByte = offset / CHAR_BIT; + int endByte = (offset + bit_count - 1) / CHAR_BIT; + + if(!data_is_big_endian) { + source = __builtin_bswap64(source); + } + + uint8_t* bytes = (uint8_t*)&source; + uint64_t ret = bytes[startByte]; + if(startByte != endByte) { + // The lowest byte address contains the most significant bit. + uint8_t i; + for(i = startByte + 1; i <= endByte; i++) { + ret = ret << 8; + ret = ret | bytes[i]; + } + } + + ret >>= 8 - find_end_bit(offset + bit_count); + return ret & bitmask(bit_count); +} + +bool eightbyte_set_bitfield(uint64_t value, const uint16_t offset, + const uint16_t bit_count, uint64_t* destination) { + if(value > bitmask(bit_count)) { + return false; + } + + int shiftDistance = EIGHTBYTE_BIT - offset - bit_count; + value <<= shiftDistance; + *destination &= ~(bitmask(bit_count) << shiftDistance); + *destination |= value; + return true; +} diff --git a/libs/bitfield-c/src/bitfield/8byte.h b/libs/bitfield-c/src/bitfield/8byte.h new file mode 100644 index 00000000..04512690 --- /dev/null +++ b/libs/bitfield-c/src/bitfield/8byte.h @@ -0,0 +1,88 @@ +#ifndef __8BYTE_H__ +#define __8BYTE_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public: Reads a subset of bits into a uint64_t. + * + * source - the bytes in question. + * offset - the starting index of the bit field (beginning from 0). + * bit_count - the width of the bit field to extract. + * data_is_big_endian - if the data passed in is little endian, set this to false and it + * will be flipped before grabbing the bit field. + * + * Bit fields are positioned according to big-endian bit layout. + * + * For example, the bit layout of the value "42" (i.e. 00101010 set at position + * 14 with length 6 is: + * + * 000000000000001010100000000000000000000000000000000000000000000 + * + * and the same value and position but with length 8 is: + * + * 000000000000000010101000000000000000000000000000000000000000000 + * + * If the architecture where is code is running is little-endian, the input data + * will be swapped before grabbing the bit field. + * + * Examples + * + * uint64_t value = get_bitfield(data, 2, 4); + * + * Returns the value of the requested bit field, right aligned in a uint64_t. + */ +uint64_t eightbyte_get_bitfield(uint64_t source, const uint16_t offset, + const uint16_t bit_count, const bool data_is_big_endian); + +/* Public: Return a single nibble from the payload, with range checking. + * + * source - the source payload. + * nibble_index - the index of the nibble to retreive. The leftmost nibble is + * index 0. + * data_is_big_endian - if the data passed in is little endian, set this to false and it + * will be flipped before grabbing the bit field. + * + * Returns the retreived nibble, right aligned in a uint8_t. + */ +uint8_t eightbyte_get_nibble(const uint64_t source, const uint8_t nibble_index, + const bool data_is_big_endian); + +/* Public: Return a single byte from the payload, with range checking. + * + * source - the source byte array. + * byte_index - the index of the byte to retreive. The leftmost byte is index 0. + * data_is_big_endian - if the data passed in is little endian, set this to false and it + * will be flipped before grabbing the bit field. + * + * Returns the retreived byte. + */ +uint8_t eightbyte_get_byte(const uint64_t source, const uint8_t byte_index, + const bool data_is_big_endian); + +/* Public: Set the bit field in the given data array to the new value. + * + * destination - a byte array with size at least offset + bit_count. + * value - the value to set in the bit field. + * offset - the starting index of the bit field (beginning from 0). + * bit_count - the number of bits to set in the data. + * + * Returns true if the bit_count is enough to fully represent the value, and + * false if it will not fit. + */ +bool eightbyte_set_bitfield(uint64_t value, + const uint16_t offset, const uint16_t bit_count, uint64_t* destination); + +/* Private: Determine the index of the last bit used. + */ +uint8_t find_end_bit(const uint16_t num_bits); + +#ifdef __cplusplus +} +#endif + +#endif // __8BYTE_H__ diff --git a/libs/bitfield-c/src/bitfield/bitarray.c b/libs/bitfield-c/src/bitfield/bitarray.c new file mode 100644 index 00000000..dcb9a08f --- /dev/null +++ b/libs/bitfield-c/src/bitfield/bitarray.c @@ -0,0 +1,145 @@ +#include +#include +#include +#include + +#define PREPARE_FIRST_COPY() \ + do { \ + if (bit_count >= (CHAR_BIT - destination_offset_modulo)) { \ + *destination &= reverse_mask[destination_offset_modulo]; \ + bit_count -= CHAR_BIT - destination_offset_modulo; \ + } else { \ + *destination &= reverse_mask[destination_offset_modulo] \ + | reverse_mask_xor[destination_offset_modulo + bit_count + 1];\ + c &= reverse_mask[destination_offset_modulo + bit_count ];\ + bit_count = 0; \ + } } while (0) + +static const uint8_t reverse_mask[] = + { 0x55, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff }; +static const uint8_t reverse_mask_xor[] = + { 0xff, 0x7f, 0x3f, 0x1f, 0x0f, 0x07, 0x03, 0x01, 0x00 }; + +bool copy_bits(const uint8_t* source_origin, const uint16_t source_length, + const uint16_t source_offset, uint16_t bit_count, + uint8_t* destination_origin, const uint16_t destination_length, + const uint16_t destination_offset) { + if(bit_count < 1) { + return false; + } + + if(source_offset + bit_count > source_length * CHAR_BIT || + destination_offset + bit_count > destination_length * CHAR_BIT ) { + return false; + } + + const uint8_t* source = source_origin + (source_offset / CHAR_BIT); + uint8_t* destination = destination_origin + (destination_offset / CHAR_BIT); + int source_offset_modulo = source_offset % CHAR_BIT; + int destination_offset_modulo = destination_offset % CHAR_BIT; + + if(source_offset_modulo == destination_offset_modulo) { + if(source_offset_modulo > 0) { + uint8_t c = reverse_mask_xor[destination_offset_modulo] & *source++; + PREPARE_FIRST_COPY(); + *destination++ |= c; + } + + int byte_len = bit_count / CHAR_BIT; + int bit_count_modulo = bit_count % CHAR_BIT; + + if(byte_len > 0) { + memcpy(destination, source, byte_len); + source += byte_len; + destination += byte_len; + } + + if(bit_count_modulo > 0) { + *destination &= reverse_mask_xor[bit_count_modulo]; + *destination |= reverse_mask[bit_count_modulo] & *source; + } + } else { + int bit_diff_left_shift; + int bit_diff_right_shift; + uint8_t c; + /* + * Begin: Line things up on destination. + */ + if(source_offset_modulo > destination_offset_modulo) { + bit_diff_left_shift = source_offset_modulo - destination_offset_modulo; + bit_diff_right_shift = CHAR_BIT - bit_diff_left_shift; + + c = *source++ << bit_diff_left_shift; + c |= *source >> bit_diff_right_shift; + c &= reverse_mask_xor[destination_offset_modulo]; + } else { + bit_diff_right_shift = destination_offset_modulo - source_offset_modulo; + bit_diff_left_shift = CHAR_BIT - bit_diff_right_shift; + + c = *source >> bit_diff_right_shift & + reverse_mask_xor[destination_offset_modulo]; + } + PREPARE_FIRST_COPY(); + *destination++ |= c; + + /* + * Middle: copy with only shifting the source. + */ + int byte_len = bit_count / CHAR_BIT; + while(--byte_len >= 0) { + c = *source++ << bit_diff_left_shift; + c |= *source >> bit_diff_right_shift; + *destination++ = c; + } + + /* + * End: copy the remaing bits; + */ + int bit_count_modulo = bit_count % CHAR_BIT; + if(bit_count_modulo > 0) { + c = *source++ << bit_diff_left_shift; + c |= *source >> bit_diff_right_shift; + c &= reverse_mask[bit_count_modulo]; + + *destination &= reverse_mask_xor[bit_count_modulo]; + *destination |= c; + } + } + return true; +} + +uint16_t bits_to_bytes(uint32_t bits) { + uint8_t byte_count = bits / CHAR_BIT; + if(bits % CHAR_BIT != 0) { + ++byte_count; + } + return byte_count; +} + +/** + * Find the ending bit of a bitfield within the final byte. + * + * Returns: a bit position from 0 to 7. + */ +uint8_t find_end_bit(const uint16_t numBits) { + int endBit = numBits % CHAR_BIT; + return endBit == 0 ? CHAR_BIT : endBit; +} + +bool copy_bits_right_aligned(const uint8_t source[], const uint16_t source_length, + const uint16_t offset, const uint16_t bit_count, + uint8_t* destination, const uint16_t destination_length) { + return copy_bits(source, source_length, offset, bit_count, destination, + destination_length, + // provide a proper destination offset so the result is right + // aligned + (destination_length - bits_to_bytes(bit_count)) * CHAR_BIT + + CHAR_BIT - find_end_bit(bit_count)); +} + +bool copy_bytes_right_aligned(const uint8_t source[], const uint16_t source_length, + const uint16_t offset, const uint16_t byte_count, + uint8_t* destination, const uint16_t destination_length) { + return copy_bits_right_aligned(source, source_length, offset * CHAR_BIT, + byte_count * CHAR_BIT, destination, destination_length); +} diff --git a/libs/bitfield-c/src/bitfield/bitfield.c b/libs/bitfield-c/src/bitfield/bitfield.c new file mode 100644 index 00000000..795f0208 --- /dev/null +++ b/libs/bitfield-c/src/bitfield/bitfield.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include +#include + +uint64_t bitmask(const uint8_t bit_count) { + return (((uint64_t)0x1) << bit_count) - 1; +} + +uint8_t get_nibble(const uint8_t source[], const uint8_t source_length, + const uint8_t nibble_index) { + uint8_t byte_index = nibble_index / 2; + uint8_t result = get_byte(source, source_length, byte_index); + if(nibble_index % 2 == 0) { + result >>= NIBBLE_SIZE; + } + result &= bitmask(NIBBLE_SIZE); + return result; +} + +uint8_t get_byte(const uint8_t source[], const uint8_t source_length, + const uint8_t byte_index) { + if(byte_index < source_length) { + return source[byte_index]; + } + return 0; +} + +uint64_t get_bitfield(const uint8_t source[], const uint8_t source_length, + const uint16_t offset, const uint16_t bit_count) { + if(bit_count > 64 || bit_count < 1) { + // TODO error reporting? + return 0; + } + + ArrayOrBytes combined; + memset(combined.bytes, 0, sizeof(combined.bytes)); + if(copy_bits_right_aligned(source, source_length, offset, bit_count, + combined.bytes, sizeof(combined.bytes))) { + if(BYTE_ORDER == LITTLE_ENDIAN) { + combined.whole = __builtin_bswap64(combined.whole); + } + } else { + // debug("couldn't copy enough bits from source") + } + return combined.whole; +} + +bool set_nibble(const uint16_t nibble_index, const uint8_t value, + uint8_t* destination, const uint16_t destination_length) { + return copy_bits(&value, CHAR_BIT, NIBBLE_SIZE, NIBBLE_SIZE, destination, + destination_length, nibble_index * NIBBLE_SIZE); +} + +bool set_bitfield(const uint64_t value, const uint16_t offset, + const uint16_t bit_count, uint8_t destination[], + uint16_t destination_length) { + if(value > bitmask(bit_count)) { + return false; + } + + ArrayOrBytes combined = { + whole: value + }; + + if(BYTE_ORDER == LITTLE_ENDIAN) { + combined.whole = __builtin_bswap64(combined.whole); + } + + return copy_bits(combined.bytes, sizeof(combined.bytes), + sizeof(combined.bytes) * CHAR_BIT - bit_count, bit_count, + destination, destination_length, offset); +} diff --git a/libs/bitfield-c/src/bitfield/bitfield.h b/libs/bitfield-c/src/bitfield/bitfield.h new file mode 100644 index 00000000..df92639a --- /dev/null +++ b/libs/bitfield-c/src/bitfield/bitfield.h @@ -0,0 +1,220 @@ +#ifndef __BITFIELD_H__ +#define __BITFIELD_H__ + +#include +#include + +#define NIBBLE_SIZE (CHAR_BIT / 2) + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public: Reads a subset of bits into a uint64_t, right aligned so they may be + * interpreted as a number. + * + * source - the bytes in question. + * source_size - the number of bytes in the source. + * offset - the starting index of the bit field (beginning from 0). + * bit_count - the width of the bit field to extract. This must be less than or + * equal to 64. + * + * Bit fields are positioned according to big-endian bit layout and the data is + * swapped automatically as necessary depending on the compiled architecture. + * + * For example, the bit layout of the value "42" (i.e. 00101010 set at position + * 14 with length 6 is: + * + * 000000000000001010100000000000000000000000000000000000000000000 + * + * and the same value and position but with length 8 is: + * + * 000000000000000010101000000000000000000000000000000000000000000 + * + * Examples + * + * uint64_t value = get_bitfield(data, data_size, 2, 4); + * + * Returns the value of the requested bit field, right aligned in a uint64_t. + */ +uint64_t get_bitfield(const uint8_t source[], const uint8_t source_length, + const uint16_t offset, const uint16_t bit_count); + +/* Public: Return a single nibble from the byte array, with range checking. + * + * source - the source byte array. + * source_length - the total length of the source array. + * nibble_index - the index of the nibble to retreive. The leftmost nibble is + * index 0. + * + * Returns the retreived nibble, right aligned in a uint8_t. + */ +uint8_t get_nibble(const uint8_t source[], const uint8_t source_length, + const uint8_t nibble_index); + +/* Public: Return a single byte from the byte array, with range checking. + * + * source - the source byte array. + * source_length - the total length of the source array. + * byte_index - the index of the byte to retreive. The leftmost byte is index 0. + * + * Returns the retreived byte. + */ +uint8_t get_byte(const uint8_t source[], const uint8_t source_length, + const uint8_t byte_index); + +/* Public: Copy a range of bits from one bit array to another. + * + * The range does not need to be byte aligned, and the source and destination do + * not have to be the same size (as long as the desitnation has enough room to + * fit the range). + * + * A bit array with regards to this function always has the leftmost bit in byte + * 0, i.e. bit index is the leftmost bit of byte 0. Endianness does not matter. + * + * For example: + * + * uint8_t source[4] = {0x11, 0x22, 0x33, 0x44}; + * uint8_t destination[4] = {0}; + * copy_bits(source, sizeof(source), 8, 8, destination, + * sizeof(destination), 0); + * // destination[0] == 0x22 + * // destination[1] == 0x0 + * // destination[2] == 0x0 + * // destination[3] == 0x0 + * + * Thanks to + * http://stackoverflow.com/questions/3534535/whats-a-time-efficient-algorithm-to-copy-unaligned-bit-arrays + * for the implementation of the algorithm. + * + * source_origin - the source array. + * source_length - the total length of the source array in bytes, + * for range checking. + * source_offset - an offset in bits to start the copy from the source array. + * Specify 0 to start from source_origin. + * bit_count - the number of bits to copy. + * destination_origin - the destination array. + * desitnation_length - the total length of the destination array in bytes, + * for range checking. + * destination_offset - an offset in bits to start placing the copied range into + * the destination array. Specify 0 to start from the beginning of the + * destination. If you are copying a range not aligned on a byte, you + * probably want to set this to a positive offset to right the resulting + * bits in the destination. + * + * Returns true if the copy was successful and false if the range exceeded the + * size of the source or destination, or if the range size negative or 0. + */ +bool copy_bits(const uint8_t* source_origin, const uint16_t source_length, + const uint16_t source_offset, uint16_t bit_count, + uint8_t* destination_origin, const uint16_t destination_length, + const uint16_t destination_offset); + +/* Public: Copy a range of bits from one array to another, right aligning the + * result. + * + * This is mostly useful if you want to cast the result to an integer type + * instead of a byte array. + * + * For example: + * + * uint8_t source[4] = {0x11, 0x22, 0x33, 0x44}; + * uint8_t destination[4] = {0}; + * copy_bits_right_aligned(source, sizeof(source), 8, 8, destination, + * sizeof(destination)); + * // destination[0] == 0x0 + * // destination[1] == 0x0 + * // destination[2] == 0x0 + * // destination[3] == 0x22 + * + * int value = (int)destination; + * // value == 0x22 == 32 + * + * The arguments are the same as copy_bits, but without the destination_offset + * option - that's set automatically to right align the result. + * + * Returns true if the copy was successful and false if the range exceeded the + * size of the source or destination, or if the range size negative or 0. + */ +bool copy_bits_right_aligned(const uint8_t source[], const uint16_t source_length, + const uint16_t offset, const uint16_t bit_count, + uint8_t* destination, const uint16_t destination_length); + +/* Public: Copy a range of bytes from one byte array to another. + * + * The source and destination do not have to be the same size (as long as the + * desitnation has enough room to fit the range). + * + * source_origin - the source array. + * source_length - the total length of the source array in bytes, + * for range checking. + * source_offset - a byte offset to start the copy from the source array. + * Specify 0 to start from source_origin. + * byte_count - the number of bytes to copy. + * destination_origin - the destination array. + * desitnation_length - the total length of the destination array in bytes, + * for range checking. + * destination_offset - an offset in bytes to start placing the copied range into + * the destination array. Specify 0 to start from the beginning of the + * destination. + * + * Returns true if the copy was successful and false if the range exceeded the + * size of the source or destination, or if the range size negative or 0. + */ +bool copy_bytes_right_aligned(const uint8_t source[], const uint16_t source_length, + const uint16_t offset, const uint16_t byte_count, + uint8_t* destination, const uint16_t destination_length); + +/* Public: Set the a nibble in the given data array to the new value. + * + * nibble_index - the index of the nibble to retreive. The leftmost nibble is + * index 0. + * value - the value to set in the bit field. + * destination - the destination array. + * destination_length - the total length of the destination array in bytes, + * for range checking. + * + * Returns true if the bit_count is enough to fully represent the value, and + * false if it will not fit. + */ +bool set_nibble(const uint16_t nibble_index, const uint8_t value, + uint8_t* destination, const uint16_t destination_length); + +/* Public: Set the bit field in the given data array to the new value. + * + * value - the value to set in the bit field. + * offset - the starting index of the bit field (beginning from 0). + * bit_count - the number of bits to set in the data. + * destination - the destination array. + * destination_length - the total length of the destination array in bytes, + * for range checking. + * + * Returns true if the bit_count is enough to fully represent the value, and + * false if it will not fit. + */ +bool set_bitfield(const uint64_t value, const uint16_t offset, + const uint16_t bit_count, uint8_t destination[], + uint16_t destination_length); + +/* Public: Return a right aligned bitmask for a uint64_t. + * + * bit_count - the number of bits to mask, right aligned. + */ +uint64_t bitmask(const uint8_t bit_count); + +/* Private: + */ +uint16_t bits_to_bytes(uint32_t bits); + +/* Private: A union to assist swapping between uint64_t and a uint8_t array. + */ +typedef union { + uint64_t whole; + uint8_t bytes[sizeof(uint64_t)]; +} ArrayOrBytes; + +#ifdef __cplusplus +} +#endif + +#endif // __BITFIELD_H__ diff --git a/libs/bitfield-c/src/canutil/read.c b/libs/bitfield-c/src/canutil/read.c new file mode 100644 index 00000000..d0cbb71a --- /dev/null +++ b/libs/bitfield-c/src/canutil/read.c @@ -0,0 +1,34 @@ +#include +#include +#include + +static float decode_float(uint64_t raw, float factor, float offset) { + return raw * factor + offset; +} + +float eightbyte_parse_float(uint64_t data, uint8_t bit_offset, uint8_t bit_size, + float factor, float offset) { + return decode_float(eightbyte_get_bitfield(data, bit_offset, bit_size, + true), factor, offset); +} + +bool eightbyte_parse_bool(uint64_t data, uint8_t bit_offset, uint8_t bit_size, + float factor, float offset) { + float value = eightbyte_parse_float(data, bit_offset, bit_size, factor, offset); + return value == 0.0 ? false : true; +} + +float bitfield_parse_float(const uint8_t source[], const uint16_t source_length, + const uint8_t bit_offset, const uint8_t bit_size, const float factor, + const float offset) { + return decode_float(get_bitfield(source, source_length, bit_offset, bit_size), + factor, offset); +} + +bool bitfield_parse_bool(const uint8_t source[], const uint16_t source_length, + const uint8_t bit_offset, const uint8_t bit_size, const float factor, + const float offset) { + float value = bitfield_parse_float(source, source_length, bit_offset, + bit_size, factor, offset); + return value == 0.0 ? false : true; +} diff --git a/libs/bitfield-c/src/canutil/read.h b/libs/bitfield-c/src/canutil/read.h new file mode 100644 index 00000000..86fea785 --- /dev/null +++ b/libs/bitfield-c/src/canutil/read.h @@ -0,0 +1,81 @@ +#ifndef __READ_H__ +#define __READ_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public: Parse a CAN signal from a message and apply required transformation. + * + * source - the payload containing the signal. + * bit_offset - the starting bit for the signal. + * bit_size - the width of the signal. + * factor - the transformation factor for the signal value, applied after + * pulling out the bit field. Use 1.0 for no factor. + * offset - the transformation offset for the signal value, applied after + * pulling out the bit field. Use 0 for no offset. + * + * Returns the decoded and transformed value of the signal. + */ +float eightbyte_parse_float(const uint64_t source, const uint8_t bit_offset, + const uint8_t bit_size, const float factor, const float offset); + +/* Public: Parse a CAN signal from a message storage as a byte array and apply + * required transformation. + * + * source - the payload containing the signal. + * source_size - the size of the payload in bytes. + * bit_offset - the starting bit for the signal. + * bit_size - the width of the signal. + * factor - the transformation factor for the signal value, applied after + * pulling out the bit field. Use 1.0 for no factor. + * offset - the transformation offset for the signal value, applied after + * pulling out the bit field. Use 0 for no offset. + * + * Returns the decoded and transformed value of the signal. + */ +float bitfield_parse_float(const uint8_t source[], const uint16_t source_size, + const uint8_t bit_offset, const uint8_t bit_size, const float factor, + const float offset); + +/* Public: Parse a CAN signal from a message and interpret it as a boolean. + * + * source - the payload containing the signal. + * bit_offset - the starting bit for the signal. + * bit_size - the width of the signal. + * factor - the transformation factor for the signal value, applied after + * pulling out the bit field. Use 1.0 for no factor. + * offset - the transformation offset for the signal value, applied after + * pulling out the bit field. Use 0 for no offset. + * + * Returns false if the value was 0, otherwise true. + */ +bool eightbyte_parse_bool(uint64_t source, uint8_t bit_offset, uint8_t bit_size, + float factor, float offset); + +/* Public: Parse a CAN signal from a message storage as a byte array and + * interpret it as a boolean. + * + * source - the payload containing the signal. + * source_size - the size of the payload in bytes. + * bit_offset - the starting bit for the signal. + * bit_size - the width of the signal. + * factor - the transformation factor for the signal value, applied after + * pulling out the bit field. Use 1.0 for no factor. + * offset - the transformation offset for the signal value, applied after + * pulling out the bit field. Use 0 for no offset. + * + * Returns false if the value was 0, otherwise true. + */ +bool bitfield_parse_bool(const uint8_t source[], const uint16_t source_size, + const uint8_t bit_offset, const uint8_t bit_size, const float factor, + const float offset); + +#ifdef __cplusplus +} +#endif + +#endif // __READ_H__ diff --git a/libs/bitfield-c/src/canutil/write.c b/libs/bitfield-c/src/canutil/write.c new file mode 100644 index 00000000..7f3a3e04 --- /dev/null +++ b/libs/bitfield-c/src/canutil/write.c @@ -0,0 +1,48 @@ +#include +#include +#include + +uint64_t float_to_fixed_point(const float value, const float factor, + const float offset) { + float raw = (value - offset) / factor; + if(raw > 0) { + // round up to avoid losing precision when we cast to an int + // TODO do we need a way to encode an int back to a signal without any + // rounding? + raw += 0.5; + } + return (uint64_t)raw; +} + +uint64_t eightbyte_encode_float(float value, uint8_t bit_offset, uint8_t bit_size, + float factor, float offset) { + uint64_t result = 0; + if(!eightbyte_set_bitfield(float_to_fixed_point(value, factor, offset), + bit_offset, bit_size, &result)) { + // debug("%f will not fit in a %d bit field", value, bit_size); + } + return result; +} + +uint64_t eightbyte_encode_bool(const bool value, const uint8_t bit_offset, + const uint8_t bit_size) { + return eightbyte_encode_float(value, bit_offset, bit_size, 1.0, 0); +} + +bool bitfield_encode_float(const float value, const uint8_t bit_offset, + const uint8_t bit_size, const float factor, const float offset, + uint8_t destination[], const uint8_t destination_length) { + if(!set_bitfield(float_to_fixed_point(value, factor, offset), bit_offset, + bit_size, destination, destination_length)) { + // debug("%f will not fit in a %d bit field", value, bit_size); + return false; + } + return true; +} + +bool bitfield_encode_bool(const bool value, const uint8_t bit_offset, + const uint8_t bit_size, uint8_t destination[], + const uint16_t destination_length) { + return bitfield_encode_float(value, bit_offset, bit_size, 1.0, 0, + destination, destination_length); +} diff --git a/libs/bitfield-c/src/canutil/write.h b/libs/bitfield-c/src/canutil/write.h new file mode 100644 index 00000000..c2bef20e --- /dev/null +++ b/libs/bitfield-c/src/canutil/write.h @@ -0,0 +1,57 @@ +#ifndef __WRITE_H__ +#define __WRITE_H__ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public: Encode a floating point number into a fixed point, fixed bit width + * field in a bit array. + * + * value - the floating point value to encode. + * bit_offset - the starting point for the encoded bits in the returned value. + * bit_size - The max width of the field in the resulting bit array. If bit_size + * isn't big enough to store the fixed point version of the value, the + * bitfeld will *not* be set. TODO some error reporting would be nice. + * factor - a factor used to transform from floating to fixed point before + * encoding. Use 1.0 for no factor. + * offset - an offset used to transform from floating to fixed point before + * encoding. Use 0 for no offset. + * + * Returns a big-endian uint64_t with the value encoded as a bitfield. + */ +uint64_t eightbyte_encode_float(float value, uint8_t bit_offset, + uint8_t bit_size, float factor, float offset); + +uint64_t float_to_fixed_point(const float value, const float factor, + const float offset); + +bool bitfield_encode_float(const float value, const uint8_t bit_offset, + const uint8_t bit_size, const float factor, const float offset, + uint8_t destination[], const uint8_t destination_length); + +/* Public: Encode a boolean into fixed bit width field in a bit array. + * + * value - the boolean value to encode - true will be 1, false will be 0. + * bit_offset - the starting point for the encoded bits in the returned value. + * bit_size - The max width of the field in the resulting bit array. If bit_size + * isn't big enough to store the fixed point version of the value, the + * bitfeld will *not* be set. TODO some error reporting would be nice. + * + * Returns a big-endian uint64_t with the value encoded as a bitfield. + */ +uint64_t eightbyte_encode_bool(const bool value, const uint8_t bit_offset, + const uint8_t bit_size); + +bool bitfield_encode_bool(const bool value, const uint8_t bit_offset, const + uint8_t bit_size, uint8_t destination[], + const uint16_t destination_length); + +#ifdef __cplusplus +} +#endif + +#endif // __WRITE_H__ diff --git a/libs/bitfield-c/tests/8byte_tests.c b/libs/bitfield-c/tests/8byte_tests.c new file mode 100644 index 00000000..64554acc --- /dev/null +++ b/libs/bitfield-c/tests/8byte_tests.c @@ -0,0 +1,261 @@ +#include +#include +#include +#include + +START_TEST (test_large_bitmask) +{ + uint64_t result = bitmask(32); + fail_if(result != 0xffffffff); +} +END_TEST + +START_TEST (test_one_bit_not_swapped) +{ + uint64_t data = 0x80; + uint64_t result = eightbyte_get_bitfield(data, 0, 1, false); + fail_if(result == 1); +} +END_TEST + +START_TEST (test_one_bit) +{ + uint64_t data = 0x8000000000000000; + uint64_t result = eightbyte_get_bitfield(data, 0, 1, false); + fail_unless(result == 0x1, + "First bit in 0x%llx was 0x%llx instead of 0x1", data, result); +} +END_TEST + +START_TEST (test_32_bit_parse) +{ + uint64_t data = 0x0402574d555a0401; + uint64_t result = eightbyte_get_bitfield(data, 16, 32, false); + uint64_t expectedValue = 0x574d555a; + fail_unless(result == expectedValue, + "Field retrieved in 0x%llx was 0x%llx instead of 0x%llx", data, + result, expectedValue); +} +END_TEST + +START_TEST (test_16_bit_parse) +{ + uint64_t data = 0xF34DFCFF00000000; + uint64_t result = eightbyte_get_bitfield(data, 16, 16, false); + uint64_t expectedValue = 0xFCFF; + fail_unless(result == expectedValue, + "Field retrieved in 0x%llx was 0x%llx instead of 0x%llx", data, + result, expectedValue); +} +END_TEST + +START_TEST (test_one_byte) +{ + uint64_t data = 0xFA00000000000000; + uint64_t result = eightbyte_get_bitfield(data, 0, 4, false); + fail_unless(result == 0xF, + "First nibble in 0x%llx was 0x%llx instead of 0xF", data, result); + result = eightbyte_get_bitfield(data, 4, 4, false); + fail_unless(result == 0xA, + "Second nibble in 0x%llx was 0x%llx instead of 0xA", data, result); + result = eightbyte_get_bitfield(data, 0, 8, false); + fail_unless(result == 0xFA, + "All bits in 0x%llx were 0x%llx instead of 0x%llx", data, result, data); +} +END_TEST + +START_TEST (test_multi_byte) +{ + uint64_t data = 0x12FA000000000000; + uint64_t result = eightbyte_get_bitfield(data, 0, 4, false); + fail_unless(result == 0x1, + "First 4 bits in 0x%llx was 0x%llx instead of 0xF", (data >> 60) & 0xF, + result); + result = eightbyte_get_bitfield(data, 4, 4, false); + fail_unless(result == 0x2, + "Second 4 bits in 0x%llx was 0x%llx instead of 0xA", (data >> 56) & 0xF, + result); + result = eightbyte_get_bitfield(data, 8, 4, false); + fail_unless(result == 0xF, + "First 4 bits in 0x%llx was 0x%llx instead of 0x1", (data >> 52) & 0xF, + result); + result = eightbyte_get_bitfield(data, 12, 4, false); + fail_unless(result == 0xA, + "Second 4 bits in 0x%llx was 0x%llx instead of 0x2", (data >> 48) % 0xF, + result); +} +END_TEST + +START_TEST (test_get_multi_byte) +{ + uint64_t data = 0x12FA000000000000; + uint64_t result = eightbyte_get_bitfield(data, 0, 9, false); + ck_assert_int_eq(result, 0x25); +} +END_TEST + +START_TEST (test_get_off_byte_boundary) +{ + uint64_t data = 0x000012FA00000000; + uint64_t result = eightbyte_get_bitfield(data, 12, 8, false); + ck_assert_int_eq(result, 0x01); +} END_TEST + +START_TEST (test_set_wont_fit) +{ + uint64_t data = 0; + fail_if(eightbyte_set_bitfield(100, 0, 1, &data)); +} +END_TEST + +START_TEST (test_set_field) +{ + uint64_t data = 0; + fail_unless(eightbyte_set_bitfield(1, 0, 1, &data)); + uint64_t result = eightbyte_get_bitfield(data, 0, 1, false); + ck_assert_int_eq(result, 0x1); + data = 0; + fail_unless(eightbyte_set_bitfield(1, 1, 1, &data)); + result = eightbyte_get_bitfield(data, 1, 1, false); + ck_assert_int_eq(result, 0x1); + + data = 0; + fail_unless(eightbyte_set_bitfield(0xf, 3, 4, &data)); + result = eightbyte_get_bitfield(data, 3, 4, false); + ck_assert_int_eq(result, 0xf); +} +END_TEST + +START_TEST (test_set_doesnt_clobber_existing_data) +{ + uint64_t data = 0xFFFC4DF300000000; + fail_unless(eightbyte_set_bitfield(0x4fc8, 16, 16, &data)); + uint64_t result = eightbyte_get_bitfield(data, 16, 16, false); + fail_unless(result == 0x4fc8, + "Field retrieved in 0x%llx was 0x%llx instead of 0x%x", data, result, + 0xc84f); + + data = 0x8000000000000000; + fail_unless(eightbyte_set_bitfield(1, 21, 1, &data)); + fail_unless(data == 0x8000040000000000LLU, + "Expected combined value 0x8000040000000000 but got 0x%llx%llx", + data >> 32, data); +} +END_TEST + +START_TEST (test_set_off_byte_boundary) +{ + uint64_t data = 0xFFFC4DF300000000; + fail_unless(eightbyte_set_bitfield(0x12, 12, 8, &data)); + uint64_t result = eightbyte_get_bitfield(data, 12, 12, false); + ck_assert_int_eq(result,0x12d); +} +END_TEST + +START_TEST (test_set_odd_number_of_bits) +{ + uint64_t data = 0xFFFC4DF300000000LLU; + fail_unless(eightbyte_set_bitfield(0x12, 11, 5, &data)); + uint64_t result = eightbyte_get_bitfield(data, 11, 5, false); + fail_unless(result == 0x12, + "Field set in 0x%llx%llx%llx%llx was 0x%llx instead of 0x%llx", data, result, + 0x12); + + data = 0xFFFC4DF300000000LLU; + fail_unless(eightbyte_set_bitfield(0x2, 11, 5, &data)); + result = eightbyte_get_bitfield(data, 11, 5, false); + fail_unless(result == 0x2, + "Field set in 0x%llx%llx%llx%llx was 0x%llx instead of 0x%llx", data, result, + 0x2); +} +END_TEST + +START_TEST(test_eightbyte_get_byte) +{ + uint64_t data = 0x00000000F34DFCFF; + uint8_t result = eightbyte_get_byte(data, 0, false); + uint8_t expected = 0x0; + ck_assert_int_eq(result, expected); + + result = eightbyte_get_byte(data, 4, false); + expected = 0xF3; + ck_assert_int_eq(result, expected); + + result = eightbyte_get_byte(data, 5, false); + expected = 0x4D; + ck_assert_int_eq(result, expected); + + result = eightbyte_get_byte(data, 6, false); + expected = 0xFC; + ck_assert_int_eq(result, expected); + + result = eightbyte_get_byte(data, 7, false); + expected = 0xFF; + ck_assert_int_eq(result, expected); +} +END_TEST + +START_TEST(test_eightbyte_get_nibble) +{ + uint64_t data = 0x00000000F34DFCFF; + uint8_t result = eightbyte_get_nibble(data, 0, false); + uint8_t expected = 0x0; + ck_assert_int_eq(result, expected); + + result = eightbyte_get_nibble(data, 2, false); + expected = 0x0; + ck_assert_int_eq(result, expected); + + result = eightbyte_get_nibble(data, 8, false); + expected = 0xF; + ck_assert_int_eq(result, expected); + + result = eightbyte_get_nibble(data, 9, false); + expected = 0x3; + ck_assert_int_eq(result, expected); + + result = eightbyte_get_nibble(data, 10, false); + expected = 0x4; + ck_assert_int_eq(result, expected); + + result = eightbyte_get_nibble(data, 13, false); + expected = 0xC; + ck_assert_int_eq(result, expected); +} +END_TEST + +Suite* bitfieldSuite(void) { + Suite* s = suite_create("bitfield"); + TCase *tc_core = tcase_create("core"); + tcase_add_test(tc_core, test_large_bitmask); + tcase_add_test(tc_core, test_one_bit); + tcase_add_test(tc_core, test_one_bit_not_swapped); + tcase_add_test(tc_core, test_one_byte); + tcase_add_test(tc_core, test_16_bit_parse); + tcase_add_test(tc_core, test_32_bit_parse); + tcase_add_test(tc_core, test_multi_byte); + tcase_add_test(tc_core, test_get_multi_byte); + tcase_add_test(tc_core, test_get_off_byte_boundary); + tcase_add_test(tc_core, test_set_wont_fit); + tcase_add_test(tc_core, test_set_field); + tcase_add_test(tc_core, test_set_doesnt_clobber_existing_data); + tcase_add_test(tc_core, test_set_off_byte_boundary); + tcase_add_test(tc_core, test_set_odd_number_of_bits); + tcase_add_test(tc_core, test_eightbyte_get_nibble); + tcase_add_test(tc_core, test_eightbyte_get_byte); + suite_add_tcase(s, tc_core); + + return s; +} + +int main(void) { + int numberFailed; + Suite* s = bitfieldSuite(); + SRunner *sr = srunner_create(s); + // Don't fork so we can actually use gdb + srunner_set_fork_status(sr, CK_NOFORK); + srunner_run_all(sr, CK_NORMAL); + numberFailed = srunner_ntests_failed(sr); + srunner_free(sr); + return (numberFailed == 0) ? 0 : 1; +} diff --git a/libs/bitfield-c/tests/bitfield_tests.c b/libs/bitfield-c/tests/bitfield_tests.c new file mode 100644 index 00000000..b8c83b59 --- /dev/null +++ b/libs/bitfield-c/tests/bitfield_tests.c @@ -0,0 +1,132 @@ +#include +#include +#include + +START_TEST (test_get_byte) +{ + uint8_t data[4] = {0x12, 0x34, 0x56, 0x78}; + uint8_t result = get_byte(data, sizeof(data), 0); + ck_assert_int_eq(result, 0x12); + result = get_byte(data, sizeof(data), 3); + ck_assert_int_eq(result, 0x78); +} +END_TEST + +START_TEST (test_set_nibble) +{ + uint8_t data[4] = {0}; + fail_unless(set_nibble(0, 0x1, data, sizeof(data))); + fail_unless(set_nibble(1, 0x2, data, sizeof(data))); + fail_unless(set_nibble(2, 0x3, data, sizeof(data))); + fail_unless(set_nibble(3, 0x4, data, sizeof(data))); + fail_unless(set_nibble(4, 0x5, data, sizeof(data))); + ck_assert_int_eq(data[0], 0x12); + ck_assert_int_eq(data[1], 0x34); + ck_assert_int_eq(data[2], 0x50); +} +END_TEST + +START_TEST (test_set_bitfield) +{ + uint8_t data[4] = {0}; + fail_unless(set_bitfield(0x12, 0, 8, data, sizeof(data))); + fail_unless(set_bitfield(bitmask(3), 10, 3, data, sizeof(data))); + ck_assert_int_eq(data[0], 0x12); + ck_assert_int_eq(data[1], 0x38); +} +END_TEST + +START_TEST (test_set_bitfield_doesnt_fit) +{ + uint8_t data[4] = {0}; + fail_if(set_bitfield(0xffff, 0, 8, data, sizeof(data))); + ck_assert_int_eq(data[0], 0); + ck_assert_int_eq(data[1], 0); + ck_assert_int_eq(data[2], 0); + ck_assert_int_eq(data[3], 0); +} +END_TEST + +START_TEST (test_get_nibble) +{ + uint8_t data[4] = {0x12, 0x34, 0x56, 0x78}; + uint8_t result = get_nibble(data, sizeof(data), 0); + ck_assert_int_eq(result, 0x1); + result = get_nibble(data, sizeof(data), 1); + ck_assert_int_eq(result, 0x2); + result = get_nibble(data, sizeof(data), 2); + ck_assert_int_eq(result, 0x3); +} +END_TEST + +START_TEST (test_get_bits_out_of_range) +{ + uint8_t data[4] = {0x12, 0x34, 0x56, 0x78}; + uint8_t result[4]; + fail_if(copy_bits_right_aligned(data, sizeof(data), 25, 16, result, + sizeof(result))); +} +END_TEST + +START_TEST (test_get_bits) +{ + uint8_t data[4] = {0x12, 0x34, 0x56, 0x78}; + uint8_t result[4] = {0}; + fail_unless(copy_bits_right_aligned(data, sizeof(data), 0, 16, result, + sizeof(result))); + ck_assert_int_eq(result[2], 0x12); + ck_assert_int_eq(result[3], 0x34); +} +END_TEST + +START_TEST (test_copy_bytes) +{ + uint8_t data[4] = {0x12, 0x34, 0x56, 0x78}; + uint8_t result[4] = {0}; + fail_unless(copy_bytes_right_aligned(data, sizeof(data), 1, 3, result, + sizeof(result))); + ck_assert_int_eq(result[1], 0x34); + ck_assert_int_eq(result[2], 0x56); + ck_assert_int_eq(result[3], 0x78); +} +END_TEST + +START_TEST (test_get_uneven_bits) +{ + uint8_t data[4] = {0x12, 0x34, 0x56, 0x78}; + uint8_t result[4] = {0}; + fail_unless(copy_bits_right_aligned(data, sizeof(data), 4, 12, result, + sizeof(result))); + ck_assert_int_eq(result[2], 0x2); + ck_assert_int_eq(result[3], 0x34); +} +END_TEST + +Suite* bitfieldSuite(void) { + Suite* s = suite_create("bitfield"); + TCase *tc_core = tcase_create("core"); + tcase_add_test(tc_core, test_get_byte); + tcase_add_test(tc_core, test_get_nibble); + tcase_add_test(tc_core, test_set_nibble); + tcase_add_test(tc_core, test_set_bitfield); + tcase_add_test(tc_core, test_set_bitfield_doesnt_fit); + tcase_add_test(tc_core, test_get_bits); + tcase_add_test(tc_core, test_copy_bytes); + tcase_add_test(tc_core, test_get_bits_out_of_range); + tcase_add_test(tc_core, test_get_uneven_bits); + suite_add_tcase(s, tc_core); + + return s; +} + +int main(void) { + int numberFailed; + Suite* s = bitfieldSuite(); + SRunner *sr = srunner_create(s); + // Don't fork so we can actually use gdb + srunner_set_fork_status(sr, CK_NOFORK); + srunner_run_all(sr, CK_NORMAL); + numberFailed = srunner_ntests_failed(sr); + srunner_free(sr); + return (numberFailed == 0) ? 0 : 1; +} diff --git a/libs/bitfield-c/tests/read_tests.c b/libs/bitfield-c/tests/read_tests.c new file mode 100644 index 00000000..5008cc52 --- /dev/null +++ b/libs/bitfield-c/tests/read_tests.c @@ -0,0 +1,67 @@ +#include +#include +#include + +const uint64_t BIG_ENDIAN_TEST_DATA = __builtin_bswap64(0xEB00000000000000); +const uint8_t ARRAY_TEST_DATA[] = {0xEB, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}; + +START_TEST (test_eightbyte_parse_float) +{ + float result = eightbyte_parse_float(BIG_ENDIAN_TEST_DATA, 2, 4, 1001.0, + -30000.0); + float correctResult = 0xA * 1001.0 - 30000.0; + fail_unless(result == correctResult, + "parse is incorrect: %f but should be %f", result, correctResult); +} +END_TEST + +START_TEST (test_eightbyte_parse_bool) +{ + bool result = eightbyte_parse_bool(BIG_ENDIAN_TEST_DATA, 0, 1, 1.0, 0); + bool correctResult = true; + fail_unless(result == correctResult, + "parse is incorrect: %d but should be %d", result, correctResult); +} +END_TEST + +START_TEST (test_bitfield_parse_float) +{ + float result = bitfield_parse_float(ARRAY_TEST_DATA, + sizeof(ARRAY_TEST_DATA), 2, 4, 1001.0, -30000.0); + float correctResult = 0xA * 1001.0 - 30000.0; + fail_unless(result == correctResult, + "parse is incorrect: %f but should be %f", result, correctResult); +} +END_TEST + +START_TEST (test_bitfield_parse_bool) +{ + fail_unless(bitfield_parse_bool(ARRAY_TEST_DATA, sizeof(ARRAY_TEST_DATA), + 0, 1, 1.0, 0)); +} +END_TEST + +Suite* canreadSuite(void) { + Suite* s = suite_create("read"); + TCase *tc_core = tcase_create("core"); + tcase_add_checked_fixture(tc_core, NULL, NULL); + tcase_add_test(tc_core, test_eightbyte_parse_float); + tcase_add_test(tc_core, test_eightbyte_parse_bool); + tcase_add_test(tc_core, test_bitfield_parse_float); + tcase_add_test(tc_core, test_bitfield_parse_bool); + suite_add_tcase(s, tc_core); + + return s; +} + +int main(void) { + int numberFailed; + Suite* s = canreadSuite(); + SRunner *sr = srunner_create(s); + // Don't fork so we can actually use gdb + srunner_set_fork_status(sr, CK_NOFORK); + srunner_run_all(sr, CK_NORMAL); + numberFailed = srunner_ntests_failed(sr); + srunner_free(sr); + return (numberFailed == 0) ? 0 : 1; +} diff --git a/libs/bitfield-c/tests/write_tests.c b/libs/bitfield-c/tests/write_tests.c new file mode 100644 index 00000000..4d5d8fc3 --- /dev/null +++ b/libs/bitfield-c/tests/write_tests.c @@ -0,0 +1,105 @@ +#include +#include +#include + +START_TEST (test_eightbyte_encode_float_precision) +{ + uint64_t value = eightbyte_encode_float(50, 2, 19, 0.001, 0); + ck_assert_int_eq(value, 0x061a800000000000LLU); +} +END_TEST + +START_TEST (test_eightbyte_encode_float) +{ + uint64_t value = eightbyte_encode_float(0, 1, 3, 1, 0); + ck_assert_int_eq(value, 0); + + value = eightbyte_encode_float(1, 1, 3, 1, 0); + ck_assert_int_eq(value, 0x1000000000000000LLU); +} +END_TEST + +START_TEST (test_eightbyte_encode_bool) +{ + uint64_t value = eightbyte_encode_bool(true, 1, 3); + ck_assert_int_eq(value, 0x1000000000000000LLU); + value = eightbyte_encode_bool(false, 1, 3); + ck_assert_int_eq(value, 0x0000000000000000LLU); +} +END_TEST + +START_TEST (test_bitfield_encode_float) +{ + uint8_t data[8] = {0}; + bitfield_encode_float(0, 1, 3, 1, 0, data, sizeof(data)); + ck_assert_int_eq(data[0], 0); + ck_assert_int_eq(data[1], 0); + ck_assert_int_eq(data[2], 0); + ck_assert_int_eq(data[3], 0); + ck_assert_int_eq(data[4], 0); + ck_assert_int_eq(data[5], 0); + ck_assert_int_eq(data[6], 0); + ck_assert_int_eq(data[7], 0); + + bitfield_encode_float(1, 1, 3, 1, 0, data, sizeof(data)); + ck_assert_int_eq(data[0], 0x10); + ck_assert_int_eq(data[1], 0); + ck_assert_int_eq(data[2], 0); + ck_assert_int_eq(data[3], 0); + ck_assert_int_eq(data[4], 0); + ck_assert_int_eq(data[5], 0); + ck_assert_int_eq(data[6], 0); + ck_assert_int_eq(data[7], 0); +} +END_TEST + +START_TEST (test_bitfield_encode_bool) +{ + uint8_t data[8] = {0}; + bitfield_encode_bool(true, 1, 3, data, sizeof(data)); + ck_assert_int_eq(data[0], 0x10); + ck_assert_int_eq(data[1], 0); + ck_assert_int_eq(data[2], 0); + ck_assert_int_eq(data[3], 0); + ck_assert_int_eq(data[4], 0); + ck_assert_int_eq(data[5], 0); + ck_assert_int_eq(data[6], 0); + ck_assert_int_eq(data[7], 0); + + bitfield_encode_bool(false, 1, 3, data, sizeof(data)); + ck_assert_int_eq(data[0], 0); + ck_assert_int_eq(data[1], 0); + ck_assert_int_eq(data[2], 0); + ck_assert_int_eq(data[3], 0); + ck_assert_int_eq(data[4], 0); + ck_assert_int_eq(data[5], 0); + ck_assert_int_eq(data[6], 0); + ck_assert_int_eq(data[7], 0); +} +END_TEST + +Suite* canwriteSuite(void) { + Suite* s = suite_create("write"); + TCase *tc_core = tcase_create("core"); + tcase_add_checked_fixture(tc_core, NULL, NULL); + tcase_add_test(tc_core, test_eightbyte_encode_float); + tcase_add_test(tc_core, test_eightbyte_encode_bool); + tcase_add_test(tc_core, test_eightbyte_encode_float_precision); + tcase_add_test(tc_core, test_bitfield_encode_float); + tcase_add_test(tc_core, test_bitfield_encode_bool); + suite_add_tcase(s, tc_core); + + return s; +} + +int main(void) { + int numberFailed; + Suite* s = canwriteSuite(); + SRunner *sr = srunner_create(s); + // Don't fork so we can actually use gdb + srunner_set_fork_status(sr, CK_NOFORK); + srunner_run_all(sr, CK_NORMAL); + numberFailed = srunner_ntests_failed(sr); + srunner_free(sr); + return (numberFailed == 0) ? 0 : 1; +} diff --git a/libs/ini-config/CMakeLists.txt b/libs/ini-config/CMakeLists.txt new file mode 100644 index 00000000..ceb48259 --- /dev/null +++ b/libs/ini-config/CMakeLists.txt @@ -0,0 +1,38 @@ +########################################################################### +# Copyright 2015, 2016, 2017 IoT.bzh +# +# author: Fulup Ar Foll +# contrib: Romain Forlot +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +########################################################################### + +# Add target to project dependency list +PROJECT_TARGET_ADD(ini-config) + + # Define project Target + add_library(${TARGET_NAME} STATIC ${TARGET_NAME}.cpp) + + # Binder exposes a unique public entry point + SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + OUTPUT_NAME ${TARGET_NAME} + ) + + # Define target includes + TARGET_INCLUDE_DIRECTORIES(${TARGET_NAME} + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} + ) + + # Library dependencies (include updates automatically) + TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${link_libraries}) diff --git a/libs/ini-config/ini-config.cpp b/libs/ini-config/ini-config.cpp new file mode 100644 index 00000000..ef3ab25c --- /dev/null +++ b/libs/ini-config/ini-config.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (C) 2015, 2016 ,2017 "IoT.bzh" + * Author "Loïc Collignon" + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ini-config.hpp" + +bool starts_with(const std::string& text, const std::string& token) +{ + if(text.length() < token.length()) return false; + return (text.compare(0, token.length(), token) == 0); +} + +void ini_config::read_file(const std::string& filename) +{ + std::ifstream f(filename); + if (f) + { + std::regex r_section("^\\s*\\[([^\\]]+)\\]\\s*(#.*)?$"); + std::regex r_key("^\\s*([^\\s]+)\\s*=\\s*\"([^\"]+)\"\\s*(#.*)?$"); + std::string current_section; + std::string line; + while (std::getline(f, line)) + { + std::smatch mr; + + switch (qualify(line)) + { + case line_type::section: + if (std::regex_match(line, mr, r_section) && mr.size() >= 2 && mr[1].matched) + { + current_section = mr[1].str(); + } + break; + case line_type::key: + if(std::regex_match(line, mr, r_key) && mr.size() >= 2 && mr[1].matched) + { + std::string key = current_section + '/' + mr[1].str(); + config_[key] = (mr.size() >= 3 && mr[2].matched) ? mr[2].str() : ""; + } + break; + case line_type::ignore: + break; + } + } + } +} + +ini_config::map ini_config::get_keys(const std::string& section, bool wo_prefix) +{ + map ret; + std::string key; + + std::string prefix = section + '/'; + for(auto i = config_.begin(); + i != config_.end(); + ++i) + { + if (starts_with(i->first, prefix)) + { + if(wo_prefix) + key = i->first.substr(section.size()+1); + else + key = i->first; + ret[key] = i->second; + } + } + return ret; +} + +std::string ini_config::get_value(const std::string& section, const std::string& key) +{ + return config_[section + '/' + key]; +} + +ini_config::line_type ini_config::qualify(std::string& line) +{ + if (line.size()) + { + for (std::string::value_type c : line) + { + if (c == '#') return line_type::ignore; + if (c == '[') return line_type::section; + if (!std::isspace(c, std::locale("C"))) return line_type::key; + } + } + return line_type::ignore; +} \ No newline at end of file diff --git a/libs/ini-config/ini-config.hpp b/libs/ini-config/ini-config.hpp new file mode 100644 index 00000000..4c8cc118 --- /dev/null +++ b/libs/ini-config/ini-config.hpp @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2015, 2016 ,2017 "IoT.bzh" + * Author "Loïc Collignon" + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef INI_CONFIG_HPP +#define INI_CONFIG_HPP + +#include +#include +#include +#include +#include + +// Représente un fichier de configuration. +class ini_config +{ +public: + using map = std::map; + + void read_file(const std::string& filename); + + map get_keys(const std::string& section, bool wo_prefix=true); + std::string get_value(const std::string& section, const std::string& key); + + typename map::size_type size() const { return config_.size(); } + typename map::iterator begin() { return config_.begin(); } + typename map::iterator end() { return config_.end(); } + typename map::const_iterator cbegin() const { return config_.cbegin(); } + typename map::const_iterator cend() const { return config_.cend(); } + typename map::reverse_iterator rbegin() { return config_.rbegin(); } + typename map::reverse_iterator rend() { return config_.rend(); } + typename map::const_reverse_iterator crbegin() const { return config_.crbegin(); } + typename map::const_reverse_iterator crend() const { return config_.crend(); } + +private: + map config_; + + enum class line_type + { + ignore = 0, + section = 1, + key = 2 + }; + + line_type qualify(std::string& line); +}; + +#endif // INI_CONFIG_HPP diff --git a/libs/isotp-c/.gitignore b/libs/isotp-c/.gitignore new file mode 100644 index 00000000..96a3694f --- /dev/null +++ b/libs/isotp-c/.gitignore @@ -0,0 +1,6 @@ +*.o +.DS_Store +*~ +*.bin +*.gcno +build diff --git a/libs/isotp-c/.travis.yml b/libs/isotp-c/.travis.yml new file mode 100644 index 00000000..31bfdeb3 --- /dev/null +++ b/libs/isotp-c/.travis.yml @@ -0,0 +1,8 @@ +language: c +compiler: + - gcc +script: make test +before_install: + - git submodule update --init + - sudo apt-get update -qq + - sudo apt-get install check diff --git a/libs/isotp-c/CHANGELOG.mkd b/libs/isotp-c/CHANGELOG.mkd new file mode 100644 index 00000000..e6fd5cc0 --- /dev/null +++ b/libs/isotp-c/CHANGELOG.mkd @@ -0,0 +1,10 @@ +# ISO 15765-2 Support Library in C + +## v0.2 + +* Add multi-frame support for diagnostic responses. An IsoTpMessage payload is + currently limited to 256 bytes. + +## v0.1 + +* Initial release diff --git a/libs/isotp-c/CMakeLists.txt b/libs/isotp-c/CMakeLists.txt new file mode 100644 index 00000000..fbb5161f --- /dev/null +++ b/libs/isotp-c/CMakeLists.txt @@ -0,0 +1,42 @@ +########################################################################### +# Copyright 2015, 2016, 2017 IoT.bzh +# +# author: Fulup Ar Foll +# contrib: Romain Forlot +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +########################################################################### + +# Add target to project dependency list +PROJECT_TARGET_ADD(isotp-c) + + # Define project Target + add_library(${TARGET_NAME} STATIC + src/isotp/isotp.c + src/isotp/receive.c + src/isotp/send.c) + + # Binder exposes a unique public entry point + SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + OUTPUT_NAME ${TARGET_NAME} + ) + + # Define target includes + TARGET_INCLUDE_DIRECTORIES(${TARGET_NAME} + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + + # Library dependencies (include updates automatically) + TARGET_LINK_LIBRARIES(${TARGET_NAME} + bitfield-c + ${link_libraries}) diff --git a/libs/isotp-c/LICENSE b/libs/isotp-c/LICENSE new file mode 100644 index 00000000..330d61f4 --- /dev/null +++ b/libs/isotp-c/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2013 Ford Motor Company +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/libs/isotp-c/Makefile b/libs/isotp-c/Makefile new file mode 100644 index 00000000..90165ba6 --- /dev/null +++ b/libs/isotp-c/Makefile @@ -0,0 +1,56 @@ +CC = gcc +INCLUDES = -Isrc -Ideps/bitfield-c/src +CFLAGS = $(INCLUDES) -c -Wall -Werror -g -ggdb -std=gnu99 -coverage +LDFLAGS = -coverage +LDLIBS = -lcheck -lm -lrt -lpthread + +TEST_DIR = tests +TEST_OBJDIR = build + +# Guard against \r\n line endings only in Cygwin +OSTYPE := $(shell uname) +ifneq ($(OSTYPE),Darwin) + OSTYPE := $(shell uname -o) + ifeq ($(OSTYPE),Cygwin) + TEST_SET_OPTS = igncr + endif +endif + +LIBS_PATH = deps +SRC = $(wildcard src/**/*.c) +SRC += $(wildcard deps/bitfield-c/src/**/*.c) +OBJS = $(patsubst %,$(TEST_OBJDIR)/%,$(SRC:.c=.o)) +TEST_SRC = $(wildcard $(TEST_DIR)/test_*.c) +TESTS=$(patsubst %.c,$(TEST_OBJDIR)/%.bin,$(TEST_SRC)) +TEST_SUPPORT_SRC = $(TEST_DIR)/common.c +TEST_SUPPORT_OBJS = $(patsubst %,$(TEST_OBJDIR)/%,$(TEST_SUPPORT_SRC:.c=.o)) + +all: $(OBJS) + +test: $(TESTS) + @set -o $(TEST_SET_OPTS) >/dev/null 2>&1 + @export SHELLOPTS + @sh runtests.sh $(TEST_OBJDIR)/$(TEST_DIR) + +COVERAGE_INFO_FILENAME = coverage.info +COVERAGE_INFO_PATH = $(TEST_OBJDIR)/$(COVERAGE_INFO_FILENAME) +coverage: + @lcov --base-directory . --directory src --zerocounters -q + @make clean + @make test + @lcov --base-directory . --directory $(TEST_OBJDIR) -c -o $(TEST_OBJDIR)/coverage.info + @lcov --remove $(COVERAGE_INFO_PATH) "$(LIBS_PATH)/bitfield-c/*" -o $(COVERAGE_INFO_PATH) + @genhtml -o $(TEST_OBJDIR)/coverage -t "isotp-c test coverage" --num-spaces 4 $(COVERAGE_INFO_PATH) + @$(BROWSER) $(TEST_OBJDIR)/coverage/index.html + @echo "$(GREEN)Coverage information generated in $(TEST_OBJDIR)/coverage/index.html.$(COLOR_RESET)" + +$(TEST_OBJDIR)/%.o: %.c + @mkdir -p $(dir $@) + $(CC) $(CFLAGS) $(CC_SYMBOLS) $(INCLUDES) -o $@ $< + +$(TEST_OBJDIR)/%.bin: $(TEST_OBJDIR)/%.o $(OBJS) $(TEST_SUPPORT_OBJS) + @mkdir -p $(dir $@) + $(CC) $(LDFLAGS) $(CC_SYMBOLS) $(INCLUDES) -o $@ $^ $(LDLIBS) + +clean: + rm -rf $(TEST_OBJDIR) diff --git a/libs/isotp-c/README.mkd b/libs/isotp-c/README.mkd new file mode 100644 index 00000000..98030483 --- /dev/null +++ b/libs/isotp-c/README.mkd @@ -0,0 +1,142 @@ +ISO-TP (ISO 15765-2) Support Library in C +================================ + +This is a platform agnostic C library that implements the ISO 15765-2 (also +known as ISO-TP) protocol, which runs over a CAN bus. Quoting Wikipedia: + +>ISO 15765-2, or ISO-TP, is an international standard for sending data packets +>over a CAN-Bus. The protocol allows for the transport of messages that exceed +>the eight byte maximum payload of CAN frames. ISO-TP segments longer messages +>into multiple frames, adding metadata that allows the interpretation of +>individual frames and reassembly into a complete message packet by the +>recipient. It can carry up to 4095 bytes of payload per message packet. + +This library doesn't assume anything about the source of the ISO-TP messages or +the underlying interface to CAN. It uses dependency injection to give you +complete control. + +The current version supports *only single frame ISO-TP messages*. This is fine +for OBD-II diagnostic messages, for example, but this library needs some +additional work before it can support sending larger messages. + +## Usage + +First, create some shim functions to let this library use your lower level +system: + + // required, this must send a single CAN message with the given arbitration + // ID (i.e. the CAN message ID) and data. The size will never be more than 8 + // bytes. + void send_can(const uint16_t arbitration_id, const uint8_t* data, + const uint8_t size) { + ... + } + + // optional, provide to receive debugging log messages + void debug(const char* format, ...) { + ... + } + + + // not used in the current version + void set_timer(uint16_t time_ms, void (*callback)) { + ... + } + +With your shims in place, create an IsoTpShims object to pass them around: + + IsoTpShims shims = isotp_init_shims(debug, send_can, set_timer); + +### API + +With your shims in hand, send an ISO-TP message: + + // Optional: This is your callback that will be called when the message is + // completely sent. If it was single frame (the only type supported right + // now), this will be called immediately. + void message_sent(const IsoTpMessage* message, const bool success) { + // You received the message! Do something with it. + } + + IsoTpSendHandle handle = isotp_send(&shims, 0x100, NULL, 0, message_sent); + + if(handle.completed) { + if(!handle.success) { + // something happened and it already failed - possibly we aren't able to + // send CAN messages + return; + } else { + // If the message fit in a single frame, it's already been sent + // and you're done + } + } else { + while(true) { + // Continue to read from CAN, passing off each message to the handle + // this will return true when the message is completely sent (which + // may take more than one call if it was multi frame and we're waiting + // on flow control responses from the receiver) + bool complete = isotp_continue_send(&shims, &handle, 0x100, data, size); + + if(complete && handle.completed) { + if(handle.success) { + // All frames of the message have now been sent, following + // whatever flow control feedback it got from the receiver + } else { + // the message was unable to be sent and we bailed - fatal + // error! + } + } + } + } + +Finally, receive an ISO-TP message: + + // Optional: This is your callback for when a complete ISO-TP message is + // received at the arbitration ID you specify. The completed message is + // also returned by isotp_continue_receive, which can sometimes be more + // useful since you have more context. + void message_received(const IsoTpMessage* message) { + } + + IsoTpReceiveHandle handle = isotp_receive(&shims, 0x100, message_received); + if(!handle.success) { + // something happened and it already failed - possibly we aren't able to + // send CAN messages + } else { + while(true) { + // Continue to read from CAN, passing off each message to the handle + IsoTpMessage message = isotp_continue_receive(&shims, &handle, 0x100, data, size); + + if(message.completed && handle.completed) { + if(handle.success) { + // A message has been received successfully + } else { + // Fatal error - we weren't able to receive a message and + // gave up trying. A message using flow control may have + // timed out. + } + } + } + } + +## Testing + +The library includes a test suite that uses the `check` C unit test library. + + $ make test + +You can also see the test coverage if you have `lcov` installed and the +`BROWSER` environment variable set to your choice of web browsers: + + $ BROWSER=google-chrome-stable make coverage + +## Authors + +* Chris Peplin cpeplin@ford.com +* David Boll dboll2@ford.com (the inspiration for the library's API is from David) + +## License + +Copyright (c) 2013 Ford Motor Company + +Licensed under the BSD license. diff --git a/libs/isotp-c/runtests.sh b/libs/isotp-c/runtests.sh new file mode 100644 index 00000000..4781636b --- /dev/null +++ b/libs/isotp-c/runtests.sh @@ -0,0 +1,17 @@ +echo "Running unit tests:" + +for i in $1/*.bin +do + if test -f $i + then + if ./$i + then + echo $i PASS + else + echo "ERROR in test $i:" + exit 1 + fi + fi +done + +echo "${txtbld}$(tput setaf 2)All unit tests passed.$(tput sgr0)" diff --git a/libs/isotp-c/src/isotp/isotp.c b/libs/isotp-c/src/isotp/isotp.c new file mode 100644 index 00000000..ce87f1bd --- /dev/null +++ b/libs/isotp-c/src/isotp/isotp.c @@ -0,0 +1,32 @@ +#include +#include +#include + +/* void isotp_set_timeout(IsoTpHandler* handler, uint16_t timeout_ms) { */ + /* handler->timeout_ms = timeout_ms; */ +/* } */ + +IsoTpShims isotp_init_shims(LogShim log, SendCanMessageShim send_can_message, + SetTimerShim set_timer) { + IsoTpShims shims = { + log: log, + send_can_message: send_can_message, + set_timer: set_timer, + frame_padding: ISO_TP_DEFAULT_FRAME_PADDING_STATUS + }; + return shims; +} + +void isotp_message_to_string(const IsoTpMessage* message, char* destination, + size_t destination_length) { + snprintf(destination, destination_length, "ID: 0x%" SCNd32 ", Payload: 0x%02x%02x%02x%02x%02x%02x%02x%02x", + message->arbitration_id, + message->payload[0], + message->payload[1], + message->payload[2], + message->payload[3], + message->payload[4], + message->payload[5], + message->payload[6], + message->payload[7]); +} diff --git a/libs/isotp-c/src/isotp/isotp.h b/libs/isotp-c/src/isotp/isotp.h new file mode 100644 index 00000000..3a3658c7 --- /dev/null +++ b/libs/isotp-c/src/isotp/isotp.h @@ -0,0 +1,41 @@ +#ifndef __ISOTP_H__ +#define __ISOTP_H__ + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public: Initialize an IsoTpShims with the given callback functions. + * + * If any callbacks are not to be used, set them to NULL. For documentation of + * the function type signatures, see isotp_types.h. This struct is a handy + * encapsulation used to pass the shims around to the various isotp_* functions. + * + * Returns a struct with the fields initailized to the callbacks. + */ +IsoTpShims isotp_init_shims(LogShim log, + SendCanMessageShim send_can_message, + SetTimerShim set_timer); + +/* Public: Render an IsoTpMessage as a string into the given buffer. + * + * message - the message to convert to a string, for debug logging. + * destination - the target string buffer. + * destination_length - the size of the destination buffer, i.e. the max size + * for the rendered string. + */ +void isotp_message_to_string(const IsoTpMessage* message, char* destination, + size_t destination_length); + +#ifdef __cplusplus +} +#endif + +#endif // __ISOTP_H__ diff --git a/libs/isotp-c/src/isotp/isotp_types.h b/libs/isotp-c/src/isotp/isotp_types.h new file mode 100644 index 00000000..3b7fd26d --- /dev/null +++ b/libs/isotp-c/src/isotp/isotp_types.h @@ -0,0 +1,144 @@ +#ifndef __ISOTP_TYPES__ +#define __ISOTP_TYPES__ + +#include +#include +#include + +#define CAN_MESSAGE_BYTE_SIZE 8 +#define MAX_ISO_TP_MESSAGE_SIZE 4096 +// TODO we want to avoid malloc, and we can't be allocated 4K on the stack for +// each IsoTpMessage, so for now we're setting an artificial max message size +// here - for most multi-frame use cases, 256 bytes is plenty. +#define OUR_MAX_ISO_TP_MESSAGE_SIZE 127 + +/* Private: IsoTp nibble specifics for PCI and Payload. + */ +#define PCI_NIBBLE_INDEX 0 +#define PAYLOAD_LENGTH_NIBBLE_INDEX 1 +#define PAYLOAD_BYTE_INDEX 1 + +/* Private: The default timeout to use when waiting for a response during a + * multi-frame send or receive. + */ +#define ISO_TP_DEFAULT_RESPONSE_TIMEOUT 100 + +/* Private: Determines if by default, padding is added to ISO-TP message frames. + */ +#define ISO_TP_DEFAULT_FRAME_PADDING_STATUS true + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public: A container for a sent or received ISO-TP message. + * + * completed - An IsoTpMessage is the return value from a few functions - this + * attribute will be true if the message is actually completely received. + * If the function returns but is only partially through receiving the + * message, this will be false, the multi_frame attribute will be true, + * and you should not consider the other data to be valid. + * multi_frame - Designates the message is being built with multi-frame. + * arbitration_id - The arbitration ID of the message. + * payload - The optional payload of the message - don't forget to check the + * size! + * size - The size of the payload. The size will be 0 if there is no payload. + */ +typedef struct { + const uint32_t arbitration_id; + uint8_t payload[OUR_MAX_ISO_TP_MESSAGE_SIZE]; + uint16_t size; + bool completed; + bool multi_frame; +} IsoTpMessage; + +/* Public: The type signature for an optional logging function, if the user + * wishes to provide one. It should print, store or otherwise display the + * message. + * + * message - A format string to log using the given parameters. + * ... (vargs) - the parameters for the format string. + */ +typedef void (*LogShim)(const char* message, ...); +/* Public: The type signature for a function to send a single CAN message. + * + * arbitration_id - The arbitration ID of the message. + * data - The data payload for the message. NULL is valid if size is also 0. + * size - The size of the data payload, in bytes. + * + * Returns true if the CAN message was sent successfully. + */ +typedef bool (*SendCanMessageShim)(const uint32_t arbitration_id, + const uint8_t* data, const uint8_t size); + +/* Public: The type signature for a... TODO, not used yet. + */ +typedef bool (*SetTimerShim)(uint16_t time_ms, void (*callback)); + +/* Public: The signature for a function to be called when an ISO-TP message has + * been completely received. + * + * message - The received message. + */ +typedef void (*IsoTpMessageReceivedHandler)(const IsoTpMessage* message); + +/* Public: the signature for a function to be called when an ISO-TP message has + * been completely sent, or had a fatal error during sending. + * + * message - The sent message. + * success - True if the message was sent successfully. + */ +typedef void (*IsoTpMessageSentHandler)(const IsoTpMessage* message, + const bool success); + +/* Public: The signature for a function to be called when a CAN frame has been + * sent as as part of sending or receive an ISO-TP message. + * + * This is really only useful for debugging the library itself. + * + * message - The ISO-TP message that generated this CAN frame. + */ +typedef void (*IsoTpCanFrameSentHandler)(const IsoTpMessage* message); + +/* Public: A container for the 3 shim functions used by the library to interact + * with the wider system. + * + * Use the isotp_init_shims(...) function to create an instance of this struct. + * + * By default, all CAN frames sent from this device in the process of an ISO-TP + * message are padded out to a complete 8 byte frame. This is often required by + * ECUs. To disable this feature, change the 'frame_padding' field to false on + * the IsoTpShims object returned from isotp_init_shims(...). + * + * frame_padding - true if outgoing CAN frames should be padded to a full 8 + * bytes. + */ +typedef struct { + LogShim log; + SendCanMessageShim send_can_message; + SetTimerShim set_timer; + bool frame_padding; +} IsoTpShims; + +/* Private: PCI types, for identifying each frame of an ISO-TP message. + */ +typedef enum { + PCI_SINGLE = 0x0, + PCI_FIRST_FRAME = 0x1, + PCI_CONSECUTIVE_FRAME = 0x2, + PCI_FLOW_CONTROL_FRAME = 0x3 +} IsoTpProtocolControlInformation; + +/* Private: PCI flow control identifiers. + */ +typedef enum { + PCI_FLOW_STATUS_CONTINUE = 0x0, + PCI_FLOW_STATUS_WAIT = 0x1, + PCI_FLOW_STATUS_OVERFLOW = 0x2 +} IsoTpFlowStatus; + +#ifdef __cplusplus +} +#endif + +#endif // __ISOTP_TYPES__ diff --git a/libs/isotp-c/src/isotp/receive.c b/libs/isotp-c/src/isotp/receive.c new file mode 100644 index 00000000..35b7a2a6 --- /dev/null +++ b/libs/isotp-c/src/isotp/receive.c @@ -0,0 +1,166 @@ +#include +#include +#include +#include +#include + +#define ARBITRATION_ID_OFFSET 0x8 + +static void isotp_complete_receive(IsoTpReceiveHandle* handle, IsoTpMessage* message) { + if(handle->message_received_callback != NULL) { + handle->message_received_callback(message); + } +} + +bool isotp_handle_single_frame(IsoTpReceiveHandle* handle, IsoTpMessage* message) { + isotp_complete_receive(handle, message); + return true; +} + +bool isotp_handle_multi_frame(IsoTpReceiveHandle* handle, IsoTpMessage* message) { + // call this once all consecutive frames have been received + isotp_complete_receive(handle, message); + return true; +} + +bool isotp_send_flow_control_frame(IsoTpShims* shims, IsoTpMessage* message) { + uint8_t can_data[CAN_MESSAGE_BYTE_SIZE] = {0}; + + if(!set_nibble(PCI_NIBBLE_INDEX, PCI_FLOW_CONTROL_FRAME, can_data, sizeof(can_data))) { + shims->log("Unable to set PCI in CAN data"); + return false; + } + + shims->send_can_message(message->arbitration_id - ARBITRATION_ID_OFFSET, can_data, + shims->frame_padding ? 8 : 1 + message->size); + return true; +} + + +IsoTpReceiveHandle isotp_receive(IsoTpShims* shims, + const uint32_t arbitration_id, IsoTpMessageReceivedHandler callback) { + IsoTpReceiveHandle handle = { + success: false, + completed: false, + arbitration_id: arbitration_id, + message_received_callback: callback + }; + + return handle; +} + +IsoTpMessage isotp_continue_receive(IsoTpShims* shims, + IsoTpReceiveHandle* handle, const uint32_t arbitration_id, + const uint8_t data[], const uint8_t size) { + IsoTpMessage message = { + arbitration_id: arbitration_id, + completed: false, + multi_frame: false, + payload: {0}, + size: 0 + }; + + if(size < 1) { + return message; + } + + if(handle->arbitration_id != arbitration_id) { + if(shims->log != NULL) { + // You may turn this on for debugging, but in normal operation it's + // very noisy if you are passing all received CAN messages to this + // handler. + /* shims->log("The arb ID 0x%x doesn't match the expected rx ID 0x%x", */ + /* arbitration_id, handle->arbitration_id); */ + } + return message; + } + + IsoTpProtocolControlInformation pci = (IsoTpProtocolControlInformation) + get_nibble(data, size, 0); + + // TODO this is set up to handle rx a response with a payload, but not to + // handle flow control responses for multi frame messages that we're in the + // process of sending + + switch(pci) { + case PCI_SINGLE: { + uint8_t payload_length = get_nibble(data, size, 1); + + if(payload_length > 0) { + memcpy(message.payload, &data[1], payload_length); + } + + message.size = payload_length; + message.completed = true; + handle->success = true; + handle->completed = true; + isotp_handle_single_frame(handle, &message); + break; + } + //If multi-frame, then the payload length is contained in the 12 + //bits following the first nibble of Byte 0. + case PCI_FIRST_FRAME: { + uint16_t payload_length = (get_nibble(data, size, 1) << 8) + get_byte(data, size, 1); + + if(payload_length > OUR_MAX_ISO_TP_MESSAGE_SIZE) { + shims->log("Multi-frame response too large for receive buffer."); + break; + } + + //Need to allocate memory for the combination of multi-frame + //messages. That way we don't have to allocate 4k of memory + //for each multi-frame response. + uint8_t* combined_payload = NULL; + combined_payload = (uint8_t*)malloc(sizeof(uint8_t)*payload_length); + + if(combined_payload == NULL) { + shims->log("Unable to allocate memory for multi-frame response."); + break; + } + + memcpy(combined_payload, &data[2], CAN_MESSAGE_BYTE_SIZE - 2); + handle->receive_buffer = combined_payload; + handle->received_buffer_size = CAN_MESSAGE_BYTE_SIZE - 2; + handle->incoming_message_size = payload_length; + + message.multi_frame = true; + handle->success = false; + handle->completed = false; + isotp_send_flow_control_frame(shims, &message); + break; + } + case PCI_CONSECUTIVE_FRAME: { + uint8_t start_index = handle->received_buffer_size; + uint8_t remaining_bytes = handle->incoming_message_size - start_index; + message.multi_frame = true; + + if(remaining_bytes > 7) { + memcpy(&handle->receive_buffer[start_index], &data[1], CAN_MESSAGE_BYTE_SIZE - 1); + handle->received_buffer_size = start_index + 7; + } else { + memcpy(&handle->receive_buffer[start_index], &data[1], remaining_bytes); + handle->received_buffer_size = start_index + remaining_bytes; + + if(handle->received_buffer_size != handle->incoming_message_size){ + free(handle->receive_buffer); + handle->success = false; + shims->log("Error capturing all bytes of multi-frame. Freeing memory."); + } else { + memcpy(message.payload,&handle->receive_buffer[0],handle->incoming_message_size); + free(handle->receive_buffer); + message.size = handle->incoming_message_size; + message.completed = true; + shims->log("Successfully captured all of multi-frame. Freeing memory."); + + handle->success = true; + handle->completed = true; + isotp_handle_multi_frame(handle, &message); + } + } + break; + } + default: + break; + } + return message; +} diff --git a/libs/isotp-c/src/isotp/receive.h b/libs/isotp-c/src/isotp/receive.h new file mode 100644 index 00000000..6788914a --- /dev/null +++ b/libs/isotp-c/src/isotp/receive.h @@ -0,0 +1,86 @@ +#ifndef __ISOTP_RECEIVE_H__ +#define __ISOTP_RECEIVE_H__ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public: A handle for beginning and continuing receiving a single ISO-TP + * message - both single and multi-frame. + * + * Since an ISO-TP message may contain multiple frames, we need to keep a handle + * around while waiting for subsequent CAN messages to complete the message. + * This struct encapsulates the local state required. + * + * completed - True if the received message request is completely finished. + * success - True if the message request was successful. The value if this field + * isn't valid if 'completed' isn't true. + */ +typedef struct { + bool completed; + bool success; + + // Private + uint32_t arbitration_id; + IsoTpMessageReceivedHandler message_received_callback; + uint16_t timeout_ms; + // timeout_ms: ISO_TP_DEFAULT_RESPONSE_TIMEOUT, + uint8_t* receive_buffer; + uint16_t received_buffer_size; + uint16_t incoming_message_size; + // TODO timer callback for multi frame +} IsoTpReceiveHandle; + +/* Public: Initiate receiving a single ISO-TP message on a particular + * arbitration ID. + * + * Note that no actual CAN data has been received at this point - this just sets + * up a handle to be used when new CAN messages to arrive, so they can be parsed + * as potential single or multi-frame ISO-TP messages. + * + * shims - Low-level shims required to send and receive CAN messages, etc. + * arbitration_id - The arbitration ID to receive the message on. + * callback - an optional function to be called when the message is completely + * received (use NULL if no callback required). + * + * Returns a handle to be used with isotp_continue_receive when a new CAN frame + * arrives. The 'completed' field in the returned IsoTpReceiveHandle will be true + * when the message is completely sent. + */ +IsoTpReceiveHandle isotp_receive(IsoTpShims* shims, + const uint32_t arbitration_id, IsoTpMessageReceivedHandler callback); + +/* Public: Continue to receive a an ISO-TP message, based on a freshly + * received CAN message. + * + * For a multi-frame ISO-TP message, this function must be called + * repeatedly whenever a new CAN message is received in order to complete + * receipt. + * + * TODO does this API work for if we wanted to receive an ISO-TP message and + * send our own flow control messages back? + * + * shims - Low-level shims required to send and receive CAN messages, etc. + * handle - An IsoTpReceiveHandle previously returned by isotp_receive(...). + * arbitration_id - The arbitration_id of the received CAN message. + * data - The data of the received CAN message. + * size - The size of the data in the received CAN message. + * + * Returns an IsoTpMessage with the 'completed' field set to true if a message + * was completely received. If 'completed' is false, more CAN frames are + * required to complete the messages, or the arbitration ID didn't match this + * handle. Keep passing the same handle to this function when CAN frames arrive. + */ +IsoTpMessage isotp_continue_receive(IsoTpShims* shims, + IsoTpReceiveHandle* handle, const uint32_t arbitration_id, + const uint8_t data[], const uint8_t size); + +#ifdef __cplusplus +} +#endif + +#endif // __ISOTP_RECEIVE_H__ diff --git a/libs/isotp-c/src/isotp/send.c b/libs/isotp-c/src/isotp/send.c new file mode 100644 index 00000000..e849bb2c --- /dev/null +++ b/libs/isotp-c/src/isotp/send.c @@ -0,0 +1,89 @@ +#include +#include +#include + +#define PCI_NIBBLE_INDEX 0 +#define PAYLOAD_LENGTH_NIBBLE_INDEX 1 +#define PAYLOAD_BYTE_INDEX 1 + +void isotp_complete_send(IsoTpShims* shims, IsoTpMessage* message, + bool status, IsoTpMessageSentHandler callback) { + if(callback != NULL) { + callback(message, status); + } +} + +IsoTpSendHandle isotp_send_single_frame(IsoTpShims* shims, IsoTpMessage* message, + IsoTpMessageSentHandler callback) { + IsoTpSendHandle handle = { + success: false, + completed: true + }; + + uint8_t can_data[CAN_MESSAGE_BYTE_SIZE] = {0}; + if(!set_nibble(PCI_NIBBLE_INDEX, PCI_SINGLE, can_data, sizeof(can_data))) { + shims->log("Unable to set PCI in CAN data"); + return handle; + } + + if(!set_nibble(PAYLOAD_LENGTH_NIBBLE_INDEX, message->size, can_data, + sizeof(can_data))) { + shims->log("Unable to set payload length in CAN data"); + return handle; + } + + if(message->size > 0) { + memcpy(&can_data[1], message->payload, message->size); + } + + shims->send_can_message(message->arbitration_id, can_data, + shims->frame_padding ? 8 : 1 + message->size); + handle.success = true; + isotp_complete_send(shims, message, true, callback); + return handle; +} + +IsoTpSendHandle isotp_send_multi_frame(IsoTpShims* shims, IsoTpMessage* message, + IsoTpMessageSentHandler callback) { + // TODO make sure to copy message into a local buffer + shims->log("Only single frame messages are supported"); + IsoTpSendHandle handle = { + success: false, + completed: true + }; + // TODO need to set sending and receiving arbitration IDs separately if we + // can't always just add 0x8 (and I think we can't) + return handle; +} + +IsoTpSendHandle isotp_send(IsoTpShims* shims, const uint16_t arbitration_id, + const uint8_t payload[], uint16_t size, + IsoTpMessageSentHandler callback) { + IsoTpMessage message = { + arbitration_id: arbitration_id, + size: size + }; + + memcpy(message.payload, payload, size); + if(size < 8) { + return isotp_send_single_frame(shims, &message, callback); + } else { + return isotp_send_multi_frame(shims, &message, callback); + } +} + +bool isotp_continue_send(IsoTpShims* shims, IsoTpSendHandle* handle, + const uint16_t arbitration_id, const uint8_t data[], + const uint8_t size) { + // TODO this will need to be tested when we add multi-frame support, + // which is when it'll be necessary to pass in CAN messages to SENDING + // handles. + if(handle->receiving_arbitration_id != arbitration_id) { + if(shims->log != NULL) { + shims->log("The arb ID 0x%x doesn't match the expected tx continuation ID 0x%x", + arbitration_id, handle->receiving_arbitration_id); + } + return false; + } + return false; +} diff --git a/libs/isotp-c/src/isotp/send.h b/libs/isotp-c/src/isotp/send.h new file mode 100644 index 00000000..1af32668 --- /dev/null +++ b/libs/isotp-c/src/isotp/send.h @@ -0,0 +1,86 @@ +#ifndef __ISOTP_SEND_H__ +#define __ISOTP_SEND_H__ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public: A handle for beginning and continuing sending a single ISO-TP + * message - both single and multi-frame. + * + * Since an ISO-TP message may contain multiple frames, we need to keep a handle + * around while waiting for flow control messages from the receiver. + * This struct encapsulates the local state required. + * + * completed - True if the message was completely sent, or the send was + * otherwise cancelled. + * success - True if the message send request was successful. The value if this + * field isn't valid if 'completed' isn't true. + */ +typedef struct { + bool completed; + bool success; + + // Private + uint16_t sending_arbitration_id; + uint16_t receiving_arbitration_id; + IsoTpMessageSentHandler message_sent_callback; + IsoTpCanFrameSentHandler can_frame_sent_callback; + // TODO going to need some state here for multi frame messages +} IsoTpSendHandle; + +/* Public: Initiate sending a single ISO-TP message. + * + * If the message fits in a single ISO-TP frame (i.e. the payload isn't more + * than 7 bytes) it will be sent immediately and the returned IsoTpSendHandle's + * 'completed' flag will be true. + * + * For multi-frame messages, see isotp_continue_send(...). + * + * shims - Low-level shims required to send CAN messages, etc. + * arbitration_id - The arbitration ID to send the message on. + * payload - The payload for the message. If no payload, NULL is valid is size + * is also 0. + * size - The size of the payload, or 0 if no payload. + * callback - an optional function to be called when the message is completely + * sent (use NULL if no callback required). + * + * Returns a handle to be used with isotp_continue_send to continue sending + * multi-frame messages. The 'completed' field in the returned IsoTpSendHandle + * will be true when the message is completely sent. + */ +IsoTpSendHandle isotp_send(IsoTpShims* shims, const uint16_t arbitration_id, + const uint8_t payload[], uint16_t size, + IsoTpMessageSentHandler callback); + +/* Public: Continue to send a multi-frame ISO-TP message, based on a freshly + * received CAN message (potentially from the receiver about flow control). + * + * For a multi-frame ISO-TP message, this function must be called + * repeatedly whenever a new CAN message is received in order to complete the + * send. The sender can't just blast everything onto the bus at once - it must + * wait for some response from the receiver to know how much to send at once. + * + * shims - Low-level shims required to send CAN messages, etc. + * handle - An IsoTpSendHandle previously returned by isotp_send(...). + * arbitration_id - The arbitration_id of the received CAN message. + * data - The data of the received CAN message. + * size - The size of the data in the received CAN message. + * + * Returns true if the message was completely sent, or the send was + * otherwise cancelled. Check the 'success' field of the handle to see if + * it was successful. + */ +bool isotp_continue_send(IsoTpShims* shims, IsoTpSendHandle* handle, + const uint16_t arbitration_id, const uint8_t data[], + const uint8_t size); + +#ifdef __cplusplus +} +#endif + +#endif // __ISOTP_SEND_H__ diff --git a/libs/isotp-c/tests/common.c b/libs/isotp-c/tests/common.c new file mode 100644 index 00000000..a9eed39e --- /dev/null +++ b/libs/isotp-c/tests/common.c @@ -0,0 +1,91 @@ +#include +#include +#include +#include +#include +#include + +IsoTpShims SHIMS; +IsoTpReceiveHandle RECEIVE_HANDLE; + +uint32_t last_can_frame_sent_arb_id; +uint8_t last_can_payload_sent[8]; +uint8_t last_can_payload_size; +bool can_frame_was_sent; + +bool message_was_received; +uint32_t last_message_received_arb_id; +uint8_t last_message_received_payload[OUR_MAX_ISO_TP_MESSAGE_SIZE]; +uint8_t last_message_received_payload_size; + +uint32_t last_message_sent_arb_id; +bool last_message_sent_status; +uint8_t last_message_sent_payload[OUR_MAX_ISO_TP_MESSAGE_SIZE]; +uint8_t last_message_sent_payload_size; + +void debug(const char* format, ...) { + va_list args; + va_start(args, format); + vprintf(format, args); + printf("\r\n"); + va_end(args); +} + +bool mock_send_can(const uint32_t arbitration_id, const uint8_t* data, + const uint8_t size) { + can_frame_was_sent = true; + last_can_frame_sent_arb_id = arbitration_id; + last_can_payload_size = size; + if(size > 0) { + memcpy(last_can_payload_sent, data, size); + } + return true; +} + +void message_received(const IsoTpMessage* message) { + debug("Received ISO-TP message:"); + message_was_received = true; + char str_message[48] = {0}; + isotp_message_to_string(message, str_message, sizeof(str_message)); + debug("%s", str_message); + last_message_received_arb_id = message->arbitration_id; + last_message_received_payload_size = message->size; + if(message->size > 0) { + memcpy(last_message_received_payload, message->payload, message->size); + } +} + +void message_sent(const IsoTpMessage* message, const bool success) { + if(success) { + debug("Sent ISO-TP message:"); + } else { + debug("Unable to send ISO-TP message:"); + } + char str_message[48] = {0}; + isotp_message_to_string(message, str_message, sizeof(str_message)); + debug("%s", str_message); + + last_message_sent_arb_id = message->arbitration_id; + last_message_sent_payload_size = message->size; + last_message_sent_status = success; + if(message->size > 0) { + memcpy(last_message_sent_payload, message->payload, message->size); + } +} + +void can_frame_sent(const uint32_t arbitration_id, const uint8_t* payload, + const uint8_t size) { + debug("Sent CAN Frame with arb ID 0x%x and %d bytes", arbitration_id, size); +} + +void setup() { + SHIMS = isotp_init_shims(debug, mock_send_can, NULL); + RECEIVE_HANDLE = isotp_receive(&SHIMS, 0x2a, message_received); + memset(last_message_sent_payload, 0, OUR_MAX_ISO_TP_MESSAGE_SIZE); + memset(last_message_received_payload, 0, OUR_MAX_ISO_TP_MESSAGE_SIZE); + memset(last_can_payload_sent, 0, sizeof(last_can_payload_sent)); + last_message_sent_status = false; + message_was_received = false; + can_frame_was_sent = false; +} + diff --git a/libs/isotp-c/tests/test_core.c b/libs/isotp-c/tests/test_core.c new file mode 100644 index 00000000..73b47af0 --- /dev/null +++ b/libs/isotp-c/tests/test_core.c @@ -0,0 +1,78 @@ +#include +#include +#include +#include +#include +#include + +extern IsoTpShims SHIMS; + +extern void message_sent(const IsoTpMessage* message, const bool success); + +extern uint16_t last_can_frame_sent_arb_id; +extern uint8_t last_can_payload_sent[8]; +extern uint8_t last_can_payload_size; +extern bool can_frame_was_sent; + +extern bool message_was_received; +extern uint16_t last_message_received_arb_id; +extern uint8_t last_message_received_payload[]; +extern uint8_t last_message_received_payload_size; + +extern uint16_t last_message_sent_arb_id; +extern bool last_message_sent_status; +extern uint8_t last_message_sent_payload[]; +extern uint8_t last_message_sent_payload_size; + +extern void setup(); + +START_TEST (test_default_frame_padding_on) +{ + ck_assert(SHIMS.frame_padding); + const uint8_t payload[] = {0x12, 0x34}; + uint32_t arbitration_id = 0x2a; + isotp_send(&SHIMS, arbitration_id, payload, sizeof(payload), message_sent); + ck_assert_int_eq(last_message_sent_arb_id, arbitration_id); + fail_unless(last_message_sent_status); + ck_assert_int_eq(last_message_sent_payload_size, 2); + ck_assert_int_eq(last_can_payload_size, 8); + +} +END_TEST + +START_TEST (test_disabled_frame_padding) +{ + SHIMS.frame_padding = false; + const uint8_t payload[] = {0x12, 0x34}; + uint32_t arbitration_id = 0x2a; + isotp_send(&SHIMS, arbitration_id, payload, sizeof(payload), message_sent); + ck_assert_int_eq(last_message_sent_arb_id, arbitration_id); + fail_unless(last_message_sent_status); + ck_assert_int_eq(last_message_sent_payload_size, 2); + ck_assert_int_eq(last_can_payload_size, 3); + +} +END_TEST + +Suite* testSuite(void) { + Suite* s = suite_create("iso15765"); + TCase *tc_core = tcase_create("core"); + tcase_add_checked_fixture(tc_core, setup, NULL); + tcase_add_test(tc_core, test_default_frame_padding_on); + tcase_add_test(tc_core, test_disabled_frame_padding); + suite_add_tcase(s, tc_core); + + return s; +} + +int main(void) { + int numberFailed; + Suite* s = testSuite(); + SRunner *sr = srunner_create(s); + // Don't fork so we can actually use gdb + srunner_set_fork_status(sr, CK_NOFORK); + srunner_run_all(sr, CK_NORMAL); + numberFailed = srunner_ntests_failed(sr); + srunner_free(sr); + return (numberFailed == 0) ? 0 : 1; +} diff --git a/libs/isotp-c/tests/test_receive.c b/libs/isotp-c/tests/test_receive.c new file mode 100644 index 00000000..607f9061 --- /dev/null +++ b/libs/isotp-c/tests/test_receive.c @@ -0,0 +1,176 @@ +#include +#include +#include +#include +#include +#include + +extern IsoTpShims SHIMS; +extern IsoTpReceiveHandle RECEIVE_HANDLE; + +extern void message_sent(const IsoTpMessage* message, const bool success); + +extern uint16_t last_can_frame_sent_arb_id; +extern uint8_t last_can_payload_sent; +extern uint8_t last_can_payload_size; +extern bool can_frame_was_sent; + +extern bool message_was_received; +extern uint16_t last_message_received_arb_id; +extern uint8_t last_message_received_payload[]; +extern uint8_t last_message_received_payload_size; + +extern uint16_t last_message_sent_arb_id; +extern bool last_message_sent_status; +extern uint8_t last_message_sent_payload[]; +extern uint8_t last_message_sent_payload_size; + +extern void setup(); + +START_TEST (test_receive_empty_can_message) +{ + const uint8_t data[CAN_MESSAGE_BYTE_SIZE] = {0}; + fail_if(RECEIVE_HANDLE.completed); + IsoTpMessage message = isotp_continue_receive(&SHIMS, &RECEIVE_HANDLE, 0x100, data, 0); + fail_if(message.completed); + fail_if(message_was_received); +} +END_TEST + +START_TEST (test_receive_wrong_id) +{ + const uint8_t data[CAN_MESSAGE_BYTE_SIZE] = {0}; + fail_if(RECEIVE_HANDLE.completed); + IsoTpMessage message = isotp_continue_receive(&SHIMS, &RECEIVE_HANDLE, 0x100, data, 1); + fail_if(message.completed); + fail_if(message_was_received); +} +END_TEST + +START_TEST (test_receive_bad_pci) +{ + // 4 is a reserved number for the PCI field - only 0-3 are allowed + const uint8_t data[CAN_MESSAGE_BYTE_SIZE] = {0x40}; + IsoTpMessage message = isotp_continue_receive(&SHIMS, &RECEIVE_HANDLE, 0x2a, data, 1); + fail_if(message.completed); + fail_if(message_was_received); +} +END_TEST + +START_TEST (test_receive_single_frame_empty_payload) +{ + const uint8_t data[CAN_MESSAGE_BYTE_SIZE] = {0x00, 0x12, 0x34}; + fail_if(RECEIVE_HANDLE.completed); + IsoTpMessage message = isotp_continue_receive(&SHIMS, &RECEIVE_HANDLE, 0x2a, data, 3); + fail_unless(RECEIVE_HANDLE.completed); + fail_unless(message.completed); + fail_unless(message_was_received); + ck_assert_int_eq(last_message_received_arb_id, 0x2a); + ck_assert_int_eq(last_message_received_payload_size, 0); +} +END_TEST + +START_TEST (test_receive_single_frame) +{ + const uint8_t data[CAN_MESSAGE_BYTE_SIZE] = {0x02, 0x12, 0x34}; + IsoTpMessage message = isotp_continue_receive(&SHIMS, &RECEIVE_HANDLE, 0x2a, data, 3); + fail_unless(message.completed); + fail_unless(message_was_received); + ck_assert_int_eq(last_message_received_arb_id, 0x2a); + ck_assert_int_eq(last_message_received_payload_size, 2); + ck_assert_int_eq(last_message_received_payload[0], 0x12); + ck_assert_int_eq(last_message_received_payload[1], 0x34); +} +END_TEST + +START_TEST (test_receive_multi_frame) +{ + const uint8_t data0[CAN_MESSAGE_BYTE_SIZE] = {0x10, 0x14, 0x49, 0x02, 0x01, 0x31, 0x46, 0x4d}; + IsoTpMessage message0 = isotp_continue_receive(&SHIMS, &RECEIVE_HANDLE, 0x2a, data0, 8); + fail_unless(!RECEIVE_HANDLE.completed); + fail_unless(!message0.completed); + fail_unless(!message_was_received); + fail_unless(message0.multi_frame); + //make sure flow control message has been sent. + ck_assert_int_eq(last_can_frame_sent_arb_id, 0x2a - 8); + ck_assert_int_eq(last_can_payload_sent, 0x30); + + const uint8_t data1[CAN_MESSAGE_BYTE_SIZE] = {0x21, 0x43, 0x55, 0x39, 0x4a, 0x39, 0x34, 0x48}; + IsoTpMessage message1 = isotp_continue_receive(&SHIMS, &RECEIVE_HANDLE, 0x2a, data1, 8); + fail_unless(!RECEIVE_HANDLE.completed); + fail_unless(!message1.completed); + fail_unless(!message_was_received); + fail_unless(message1.multi_frame); + + const uint8_t data2[CAN_MESSAGE_BYTE_SIZE] = {0x22, 0x55, 0x41, 0x30, 0x34, 0x35, 0x32, 0x34}; + IsoTpMessage message2 = isotp_continue_receive(&SHIMS, &RECEIVE_HANDLE, 0x2a, data2, 8); + fail_unless(RECEIVE_HANDLE.completed); + fail_unless(message2.completed); + fail_unless(message_was_received); + fail_unless(message2.multi_frame); + + ck_assert_int_eq(last_message_received_arb_id, 0x2a); + ck_assert_int_eq(last_message_received_payload_size, 0x14); + ck_assert_int_eq(last_message_received_payload[0], 0x49); + ck_assert_int_eq(last_message_received_payload[1], 0x02); + ck_assert_int_eq(last_message_received_payload[2], 0x01); + ck_assert_int_eq(last_message_received_payload[3], 0x31); + ck_assert_int_eq(last_message_received_payload[4], 0x46); + ck_assert_int_eq(last_message_received_payload[5], 0x4d); + ck_assert_int_eq(last_message_received_payload[6], 0x43); + ck_assert_int_eq(last_message_received_payload[7], 0x55); + ck_assert_int_eq(last_message_received_payload[8], 0x39); + ck_assert_int_eq(last_message_received_payload[9], 0x4a); + ck_assert_int_eq(last_message_received_payload[10], 0x39); + ck_assert_int_eq(last_message_received_payload[11], 0x34); + ck_assert_int_eq(last_message_received_payload[12], 0x48); + ck_assert_int_eq(last_message_received_payload[13], 0x55); + ck_assert_int_eq(last_message_received_payload[14], 0x41); + ck_assert_int_eq(last_message_received_payload[15], 0x30); + ck_assert_int_eq(last_message_received_payload[16], 0x34); + ck_assert_int_eq(last_message_received_payload[17], 0x35); + ck_assert_int_eq(last_message_received_payload[18], 0x32); + ck_assert_int_eq(last_message_received_payload[19], 0x34); +} +END_TEST + +START_TEST (test_receive_large_multi_frame) +{ + const uint8_t data0[CAN_MESSAGE_BYTE_SIZE] = {0x10, 0x80, 0x49, 0x02, 0x01, 0x31, 0x46, 0x4d}; + IsoTpMessage message = isotp_continue_receive(&SHIMS, &RECEIVE_HANDLE, 0x2a, data0, 8); + //Make sure we don't try to receive messages that are too large and don't send flow control. + fail_unless(!can_frame_was_sent); + fail_unless(!RECEIVE_HANDLE.completed); + fail_unless(!message.completed); + fail_unless(!message_was_received); + fail_unless(!message.multi_frame); +} +END_TEST + +Suite* testSuite(void) { + Suite* s = suite_create("iso15765"); + TCase *tc_core = tcase_create("receive"); + tcase_add_checked_fixture(tc_core, setup, NULL); + tcase_add_test(tc_core, test_receive_wrong_id); + tcase_add_test(tc_core, test_receive_bad_pci); + tcase_add_test(tc_core, test_receive_single_frame); + tcase_add_test(tc_core, test_receive_single_frame_empty_payload); + tcase_add_test(tc_core, test_receive_empty_can_message); + tcase_add_test(tc_core, test_receive_multi_frame); + tcase_add_test(tc_core, test_receive_large_multi_frame); + suite_add_tcase(s, tc_core); + + return s; +} + +int main(void) { + int numberFailed; + Suite* s = testSuite(); + SRunner *sr = srunner_create(s); + // Don't fork so we can actually use gdb + srunner_set_fork_status(sr, CK_NOFORK); + srunner_run_all(sr, CK_NORMAL); + numberFailed = srunner_ntests_failed(sr); + srunner_free(sr); + return (numberFailed == 0) ? 0 : 1; +} diff --git a/libs/isotp-c/tests/test_send.c b/libs/isotp-c/tests/test_send.c new file mode 100644 index 00000000..29cf5dec --- /dev/null +++ b/libs/isotp-c/tests/test_send.c @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include +#include + +extern IsoTpShims SHIMS; + +extern void message_sent(const IsoTpMessage* message, const bool success); + +extern uint16_t last_can_frame_sent_arb_id; +extern uint8_t last_can_payload_sent[8]; +extern uint8_t last_can_payload_size; +extern bool can_frame_was_sent; + +extern bool message_was_received; +extern uint16_t last_message_received_arb_id; +extern uint8_t last_message_received_payload[]; +extern uint8_t last_message_received_payload_size; + +extern uint16_t last_message_sent_arb_id; +extern bool last_message_sent_status; +extern uint8_t last_message_sent_payload[]; +extern uint8_t last_message_sent_payload_size; + +extern void setup(); + +START_TEST (test_send_empty_payload) +{ + SHIMS.frame_padding = false; + uint16_t arbitration_id = 0x2a; + IsoTpSendHandle handle = isotp_send(&SHIMS, arbitration_id, NULL, 0, message_sent); + fail_unless(handle.success); + fail_unless(handle.completed); + ck_assert_int_eq(last_message_sent_arb_id, arbitration_id); + fail_unless(last_message_sent_status); + ck_assert_int_eq(last_message_sent_payload[0], '\0'); + ck_assert_int_eq(last_message_sent_payload_size, 0); + + ck_assert_int_eq(last_can_frame_sent_arb_id, arbitration_id); + fail_unless(can_frame_was_sent); + ck_assert_int_eq(last_can_payload_sent[0], 0x0); + ck_assert_int_eq(last_can_payload_size, 1); +} +END_TEST + +START_TEST (test_send_single_frame) +{ + SHIMS.frame_padding = false; + const uint8_t payload[] = {0x12, 0x34}; + uint16_t arbitration_id = 0x2a; + isotp_send(&SHIMS, arbitration_id, payload, sizeof(payload), message_sent); + ck_assert_int_eq(last_message_sent_arb_id, arbitration_id); + fail_unless(last_message_sent_status); + ck_assert_int_eq(last_message_sent_payload[0], 0x12); + ck_assert_int_eq(last_message_sent_payload[1], 0x34); + ck_assert_int_eq(last_message_sent_payload_size, 2); + + ck_assert_int_eq(last_can_frame_sent_arb_id, arbitration_id); + fail_unless(can_frame_was_sent); + ck_assert_int_eq(last_can_payload_sent[0], 0x2); + ck_assert_int_eq(last_can_payload_sent[1], 0x12); + ck_assert_int_eq(last_can_payload_sent[2], 0x34); + ck_assert_int_eq(last_can_payload_size, 3); +} +END_TEST + +START_TEST (test_send_multi_frame) +{ + const uint8_t payload[] = {0x12, 0x34, 0x56, 0x78, 0x90, 0x01, 0x23, + 0x45, 0x67, 0x89}; + uint16_t arbitration_id = 0x2a; + IsoTpSendHandle handle = isotp_send(&SHIMS, arbitration_id, payload, sizeof(payload), + message_sent); + fail_unless(handle.completed); + fail_if(handle.success); +} +END_TEST + +Suite* testSuite(void) { + Suite* s = suite_create("iso15765"); + TCase *tc_core = tcase_create("send"); + tcase_add_checked_fixture(tc_core, setup, NULL); + tcase_add_test(tc_core, test_send_empty_payload); + tcase_add_test(tc_core, test_send_single_frame); + tcase_add_test(tc_core, test_send_multi_frame); + suite_add_tcase(s, tc_core); + + return s; +} + +int main(void) { + int numberFailed; + Suite* s = testSuite(); + SRunner *sr = srunner_create(s); + // Don't fork so we can actually use gdb + srunner_set_fork_status(sr, CK_NOFORK); + srunner_run_all(sr, CK_NORMAL); + numberFailed = srunner_ntests_failed(sr); + srunner_free(sr); + return (numberFailed == 0) ? 0 : 1; +} diff --git a/libs/nanopb/.gitignore b/libs/nanopb/.gitignore new file mode 100644 index 00000000..3bb09db1 --- /dev/null +++ b/libs/nanopb/.gitignore @@ -0,0 +1,28 @@ +*.gcda +*.gcno +*.gcov +*.o +*.pb.c +*.pb.h +*.pb +*.pyc +*_pb2.py +*~ +*.tar.gz +.sconsign.dblite +config.log +.sconf_temp +tests/build +julkaisu.txt +dist +docs/*.html +docs/generator_flow.png +examples/simple/simple +examples/network_server/client +examples/network_server/server +examples/using_double_on_avr/decode_double +examples/using_double_on_avr/encode_double +examples/using_double_on_avr/test_conversions +examples/using_union_messages/decode +examples/using_union_messages/encode +generator/nanopb_pb2.pyc diff --git a/libs/nanopb/.travis.yml b/libs/nanopb/.travis.yml new file mode 100644 index 00000000..2e77e7c0 --- /dev/null +++ b/libs/nanopb/.travis.yml @@ -0,0 +1,54 @@ +# Travis CI has no ability to handle 3 langauges (c, c++, python) +# and it overrides $CC/$CXX if language is set to c/c++ (only one, not both). +# +# Set language to python since at least the result of that is something useful. +language: python + +python: + - "2.7" + - "3.4" + +# Manage the C/C++ compiler manually +env: + - CC=gcc CXX=g++ + - CC=gcc-4.8 CXX=g++-4.8 + - CC=gcc-4.9 CXX=g++-4.9 + - CC=gcc-5 CXX=g++-5 + - CC=clang CXX=clang++ + +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - gcc-4.8 + - g++-4.8 + - gcc-4.9 + - g++-4.9 + - gcc-5 + - g++-5 + + +before_install: + - export PATH=$HOME/.local/bin:$HOME/protobuf/bin:$PATH + - export MAKEFLAGS=-j$(grep processor /proc/cpuinfo | wc -l) + - $CC --version + - $CXX --version + - python --version + - lsb_release -a + +# Seems to be issues with concurrent builds +#cache: +# directories: +# - $HOME/protobuf + +install: + - curl -L https://github.com/google/protobuf/releases/download/v3.0.0-beta-1/protobuf-python-3.0.0-alpha-4.tar.gz | tar xzf - + && pushd protobuf-3.0.0-alpha-4 + && ./configure --prefix=$HOME/protobuf && make && make install + && pushd python && python setup.py build && python setup.py install && popd + && popd + +script: + - pushd generator/proto && make && popd + - pushd tests && python2 $(which scons) CC=$CC CXX=$CXX && popd diff --git a/libs/nanopb/AUTHORS b/libs/nanopb/AUTHORS new file mode 100644 index 00000000..7618ff77 --- /dev/null +++ b/libs/nanopb/AUTHORS @@ -0,0 +1,31 @@ +Petteri Aimonen +Michael Poole +Daniel Kan +Stan Hu +David Hotham +Steffen Siering +Jens Steinhauser +Pavel Ilin +Kent Ryhorchuk +Martin Donath +Oliver Lee +Michael Haberler +Nicolas Colomer +Ivan Kravets +Kyle Manna +Benjamin Kamath +Andrew Ruder +Kenshi Kawaguchi +isotes +Maxim Khitrov +Yaniv Mordekhay +Ming Zhao +Google, Inc. +Tom Roeder +Piotr Sikora +Bernhard Krämer +Konstantin Podsvirov +William A. Kennington III +Guillaume Lager +Tobias Haegermarck +Justin DeMartino diff --git a/libs/nanopb/BUILD b/libs/nanopb/BUILD new file mode 100644 index 00000000..f9fc57f5 --- /dev/null +++ b/libs/nanopb/BUILD @@ -0,0 +1,21 @@ +licenses(["notice"]) + +exports_files(["LICENSE.txt"]) + +package(default_visibility = ["//visibility:public"]) + +cc_library( + name = "nanopb", + visibility = ["//visibility:public"], + hdrs = [ + "pb.h", + "pb_common.h", + "pb_decode.h", + "pb_encode.h", + ], + srcs = [ + "pb_common.c", + "pb_decode.c", + "pb_encode.c", + ], +) diff --git a/libs/nanopb/CHANGELOG.txt b/libs/nanopb/CHANGELOG.txt new file mode 100644 index 00000000..194d6136 --- /dev/null +++ b/libs/nanopb/CHANGELOG.txt @@ -0,0 +1,272 @@ +nanopb-0.3.8 (2017-03-05) + Fix problems with multiple oneofs in same message (#229) + Zero-valued extension fields were mistakenly ignored by encoder (#242) + Multiple fixes related to proto3 mode (#242, #245, #247, #249) + Fix potential unaligned access (#226, #227) + Fix documentation for protoc --plugin argument (#239) + Extend inline / fixed length bytes array support (#244) + Add new option max_length for strings (#107) + Make string substream API more robust (#230) + Make pb_decode_varint32 public API (#231) + Allow overriding proto3 mode (#228) + Add optional enum->string mapping function (#223) + Add transitional options.proto file (#241) + Add better error message on Python library version imcompatibility (#240) + Include version number in PlatformIO library.json (#222) + CMake build script changes (#236, #237) + Change download links to https + Improvements to test cases. + +nanopb-0.3.7 (2016-10-30) + Add support for proto3-style singular fields (#182, #206, #216) + Updated binary package protoc to version 3.1.0 + Add FT_INLINE allocation of bytes fields (#211) + Include package name in include guard (#207) + Fix missing warning with large bytes fields (issue #220) + Added CMake project (#208) + Add bazel BUILD file for nanopb (#209) + Added an AUTHORS file (#211) + Documentation updates + Improvements to test cases. + +nanopb-0.3.6 (2016-06-19) + Protect against corrupted _count fields in pb_release (#205) + Fix error in STATIC_ASSERT with multiple files (#203) + Add -D option to specify output directory (#193) + Generate MIN/MAX/ARRAYSIZE defines for enums (#194) + Generate comments about uncalculable message sizes (#195) + Documentation updates (#196, #201) + Improvements to test cases. + +nanopb-0.3.5 (2016-02-13) + NOTE: If you are using pb_syshdr.h, you will need to add uint_least8_t + definition. See docs/migration.rst for details. + + Fix generator crash with Enum inside Oneof (#188) + Fix some generator regressions related to .options file path (#172) + Add support for platforms without uint8_t (#191) + Allow const parameter to pb_istream_from_buffer (#152) + Ignore null pointers in pb_release() (#183) + Add support for anonymous unions (#184) + Add Python3 support to the generator (#169) + Add code generator insertion points to generated files (#178) + Improvements to CMake script (#181) + Improvements to test cases. + +nanopb-0.3.4 (2015-09-26) + Fix handling of unsigned 8- and 16-bit enums (issue 164) + Fix generator on systems where python = python3. (issue 155) + Fix compiler warning on GCC 5.x (issue 171) + Make the generator better handle imported .protos (issue 165) + Add packed_enum option to generator. + Add syntax= line to .proto files (issue 167) + Add PlatformIO registry manifest file. (pr 156) + +nanopb-0.3.3 (2015-04-10) + Fix missing files in Linux binary package (issue 146) + Fix generator bug when oneof is first field in a message. (issue 142) + Fix generator error when long_names:false is combined with Oneofs. (issue 147) + Fix oneof submessage initialization bug. (issue 149) + Fix problem with plugin options on Python 2.7.2 and older. (issue 153) + Fix crash when callback is inside oneof field. (issue 148) + Switch to .tar.gz format for Mac OS X packages. (issue 154) + Always define enum long names so that cross-file references work. (issue 118) + Add msgid generator option. (issue 151) + Improve comment support in .options files. (issue 145) + Updates for the CMake rule file, add cmake example. + Better error messages for syntax errors in .options file + +nanopb-0.3.2 (2015-01-24) + Fix memory leaks with PB_ENABLE_MALLOC with some submessage hierarchies (issue 138) + Implement support for oneofs (C unions). (issues 131, 141) + Add int_size option for generator (issue 139) + Add compilation option to disable struct packing. (issue 136) + Change PB_RETURN_ERROR() macro to avoid compiler warnings (issue 140) + Fix build problems with protoc 3.0.0 + Add support for POINTER type in extensions + Initialize also extension fields to defaults in pb_decode(). + Detect too large varint values when decoding. + +nanopb-0.3.1 (2014-09-11) + Fix security issue due to size_t overflows. (issue 132) + Fix memory leak with duplicated fields and PB_ENABLE_MALLOC + Fix crash if pb_release() is called twice. + Fix cyclic message support (issue 130) + Fix error in generated initializers for repeated pointer fields. + Improve tests (issues 113, 126) + +nanopb-0.3.0 (2014-08-26) + NOTE: See docs/migration.html or online at + http://koti.kapsi.fi/~jpa/nanopb/docs/migration.html + for changes in this version. Most importantly, you need to add + pb_common.c to the list of files to compile. + + Separated field iterator logic to pb_common.c (issue 128) + Change the _count fields to use pb_size_t datatype (issue 82) + Added PB_ prefix to macro names (issue 106) + Added #if version guard to generated files (issue 129) + Added migration document + +nanopb-0.2.9 (2014-08-09) + NOTE: If you are using the -e option with the generator, you have + to prepend . to the argument to get the same behaviour as before. + + Do not automatically add a dot with generator -e option. (issue 122) + Fix problem with .options file and extension fields. (issue 125) + Don't use SIZE_MAX macro, as it is not in C89. (issue 120) + Generate #defines for initializing message structures. (issue 79) + Add skip_message option to generator. (issue 121) + Add PB_PACKED_STRUCT support for Keil MDK-ARM toolchain (issue 119) + Give better messages about the .options file path. (issue 124) + Improved tests + +nanopb-0.2.8 (2014-05-20) + Fix security issue with PB_ENABLE_MALLOC. (issue 117) + Add option to not add timestamps to .pb.h and .pb.c preambles. (issue 115) + Documentation updates + Improved tests + +nanopb-0.2.7 (2014-04-07) + Fix bug with default values for extension fields (issue 111) + Fix some MISRA-C warnings (issue 91) + Implemented optional malloc() support (issue 80) + Changed pointer-type bytes field datatype + Add a "found" field to pb_extension_t (issue 112) + Add convenience function pb_get_encoded_size() (issue 16) + +nanopb-0.2.6 (2014-02-15) + Fix generator error with bytes callback fields (issue 99) + Fix warnings about large integer constants (issue 102) + Add comments to where STATIC_ASSERT is used (issue 96) + Add warning about unknown field names on .options (issue 105) + Move descriptor.proto to google/protobuf subdirectory (issue 104) + Improved tests + +nanopb-0.2.5 (2014-01-01) + Fix a bug with encoding negative values in int32 fields (issue 97) + Create binary packages of the generator + dependencies (issue 47) + Add support for pointer-type fields to the encoder (part of issue 80) + Fixed path in FindNanopb.cmake (issue 94) + Improved tests + +nanopb-0.2.4 (2013-11-07) + Remove the deprecated NANOPB_INTERNALS functions from public API. + Document the security model. + Check array and bytes max sizes when encoding (issue 90) + Add #defines for maximum encoded message size (issue 89) + Add #define tags for extension fields (issue 93) + Fix MISRA C violations (issue 91) + Clean up pb_field_t definition with typedefs. + +nanopb-0.2.3 (2013-09-18) + Improve compatibility by removing ternary operator from initializations (issue 88) + Fix build error on Visual C++ (issue 84, patch by Markus Schwarzenberg) + Don't stop on unsupported extension fields (issue 83) + Add an example pb_syshdr.h file for non-C99 compilers + Reorganize tests and examples into subfolders (issue 63) + Switch from Makefiles to scons for building the tests + Make the tests buildable on Windows + +nanopb-0.2.2 (2013-08-18) + Add support for extension fields (issue 17) + Fix unknown fields in empty message (issue 78) + Include the field tags in the generated .pb.h file. + Add pb_decode_delimited and pb_encode_delimited wrapper functions (issue 74) + Add a section in top of pb.h for changing compilation settings (issue 76) + Documentation improvements (issues 12, 77 and others) + Improved tests + +nanopb-0.2.1 (2013-04-14) + NOTE: The default callback function signature has changed. + If you don't want to update your code, define PB_OLD_CALLBACK_STYLE. + + Change the callback function to use void** (issue 69) + Add support for defining the nanopb options in a separate file (issue 12) + Add support for packed structs in IAR and MSVC (in addition to GCC) (issue 66) + Implement error message support for the encoder side (issue 7) + Handle unterminated strings when encoding (issue 68) + Fix bug with empty strings in repeated string callbacks (issue 73) + Fix regression in 0.2.0 with optional callback fields (issue 70) + Fix bugs with empty message types (issues 64, 65) + Fix some compiler warnings on clang (issue 67) + Some portability improvements (issues 60, 62) + Various new generator options + Improved tests + +nanopb-0.2.0 (2013-03-02) + NOTE: This release requires you to regenerate all .pb.c + files. Files generated by older versions will not + compile anymore. + + Reformat generated .pb.c files using macros (issue 58) + Rename PB_HTYPE_ARRAY -> PB_HTYPE_REPEATED + Separate PB_HTYPE to PB_ATYPE and PB_HTYPE + Move STATIC_ASSERTs to .pb.c file + Added CMake file (by Pavel Ilin) + Add option to give file extension to generator (by Michael Haberler) + Documentation updates + +nanopb-0.1.9 (2013-02-13) + Fixed error message bugs (issues 52, 56) + Sanitize #ifndef filename (issue 50) + Performance improvements + Add compile-time option PB_BUFFER_ONLY + Add Java package name to nanopb.proto + Check for sizeof(double) == 8 (issue 54) + Added generator option to ignore some fields. (issue 51) + Added generator option to make message structs packed. (issue 49) + Add more test cases. + +nanopb-0.1.8 (2012-12-13) + Fix bugs in the enum short names introduced in 0.1.7 (issues 42, 43) + Fix STATIC_ASSERT macro when using multiple .proto files. (issue 41) + Fix missing initialization of istream.errmsg + Make tests/Makefile work for non-gcc compilers (issue 40) + +nanopb-0.1.7 (2012-11-11) + Remove "skip" mode from pb_istream_t callbacks. Example implementation had a bug. (issue 37) + Add option to use shorter names for enum values (issue 38) + Improve options support in generator (issues 12, 30) + Add nanopb version number to generated files (issue 36) + Add extern "C" to generated headers (issue 35) + Add names for structs to allow forward declaration (issue 39) + Add buffer size check in example (issue 34) + Fix build warnings on MS compilers (issue 33) + +nanopb-0.1.6 (2012-09-02) + Reorganize the field decoder interface (issue 2) + Improve performance in submessage decoding (issue 28) + Implement error messages in the decoder side (issue 7) + Extended testcases (alltypes test is now complete). + Fix some compiler warnings (issues 25, 26, 27, 32). + +nanopb-0.1.5 (2012-08-04) + Fix bug in decoder with packed arrays (issue 23). + Extended testcases. + Fix some compiler warnings. + +nanopb-0.1.4 (2012-07-05) + Add compile-time options for easy-to-use >255 field support. + Improve the detection of missing required fields. + Added example on how to handle union messages. + Fix generator error with .proto without messages. + Fix problems that stopped the code from compiling with some compilers. + Fix some compiler warnings. + +nanopb-0.1.3 (2012-06-12) + Refactor the field encoder interface. + Improve generator error messages (issue 5) + Add descriptor.proto into the #include exclusion list + Fix some compiler warnings. + +nanopb-0.1.2 (2012-02-15) + Make the generator to generate include for other .proto files (issue 4). + Fixed generator not working on Windows (issue 3) + +nanopb-0.1.1 (2012-01-14) + Fixed bug in encoder with 'bytes' fields (issue 1). + Fixed a bug in the generator that caused a compiler error on sfixed32 and sfixed64 fields. + Extended testcases. + +nanopb-0.1.0 (2012-01-06) + First stable release. diff --git a/libs/nanopb/CONTRIBUTING.md b/libs/nanopb/CONTRIBUTING.md new file mode 100644 index 00000000..4041bc3c --- /dev/null +++ b/libs/nanopb/CONTRIBUTING.md @@ -0,0 +1,32 @@ +Contributing to Nanopb development +================================== + +Reporting issues and requesting features +---------------------------------------- + +Feel free to report any issues you see or features you would like +to see in the future to the Github issue tracker. Using the templates +below is preferred: + +* [Report a bug](https://github.com/nanopb/nanopb/issues/new?body=**Steps%20to%20reproduce%20the%20issue**%0a%0a1.%0a2.%0a3.%0a%0a**What%20happens?**%0A%0A**What%20should%20happen?**&labels=Type-Defect) +* [Request a feature](https://github.com/nanopb/nanopb/issues/new?body=**What%20should%20the%20feature%20do?**%0A%0A**In%20what%20situation%20would%20the%20feature%20be%20useful?**&labels=Type-Enhancement) + +Requesting help +--------------- + +If there is something strange going on, but you do not know if +it is actually a bug in nanopb, try asking first on the +[discussion forum](https://groups.google.com/forum/#!forum/nanopb). + +Pull requests +------------- + +Pull requests are welcome! + +If it is not obvious from the commit message, please indicate the +same information as you would for an issue report: + +* What functionality it fixes/adds. +* How can the problem be reproduced / when would the feature be useful. + + diff --git a/libs/nanopb/LICENSE.txt b/libs/nanopb/LICENSE.txt new file mode 100644 index 00000000..d11c9af1 --- /dev/null +++ b/libs/nanopb/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2011 Petteri Aimonen + +This software is provided 'as-is', without any express or +implied warranty. In no event will the authors be held liable +for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any +purpose, including commercial applications, and to alter it and +redistribute it freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you + must not claim that you wrote the original software. If you use + this software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and + must not be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source + distribution. diff --git a/libs/nanopb/README.md b/libs/nanopb/README.md new file mode 100644 index 00000000..07860f06 --- /dev/null +++ b/libs/nanopb/README.md @@ -0,0 +1,71 @@ +Nanopb - Protocol Buffers for Embedded Systems +============================================== + +[![Build Status](https://travis-ci.org/nanopb/nanopb.svg?branch=master)](https://travis-ci.org/nanopb/nanopb) + +Nanopb is a small code-size Protocol Buffers implementation in ansi C. It is +especially suitable for use in microcontrollers, but fits any memory +restricted system. + +* **Homepage:** https://jpa.kapsi.fi/nanopb/ +* **Documentation:** https://jpa.kapsi.fi/nanopb/docs/ +* **Downloads:** https://jpa.kapsi.fi/nanopb/download/ +* **Forum:** https://groups.google.com/forum/#!forum/nanopb + + + +Using the nanopb library +------------------------ +To use the nanopb library, you need to do two things: + +1. Compile your .proto files for nanopb, using protoc. +2. Include pb_encode.c, pb_decode.c and pb_common.c in your project. + +The easiest way to get started is to study the project in "examples/simple". +It contains a Makefile, which should work directly under most Linux systems. +However, for any other kind of build system, see the manual steps in +README.txt in that folder. + + + +Using the Protocol Buffers compiler (protoc) +-------------------------------------------- +The nanopb generator is implemented as a plugin for the Google's own protoc +compiler. This has the advantage that there is no need to reimplement the +basic parsing of .proto files. However, it does mean that you need the +Google's protobuf library in order to run the generator. + +If you have downloaded a binary package for nanopb (either Windows, Linux or +Mac OS X version), the 'protoc' binary is included in the 'generator-bin' +folder. In this case, you are ready to go. Simply run this command: + + generator-bin/protoc --nanopb_out=. myprotocol.proto + +However, if you are using a git checkout or a plain source distribution, you +need to provide your own version of protoc and the Google's protobuf library. +On Linux, the necessary packages are protobuf-compiler and python-protobuf. +On Windows, you can either build Google's protobuf library from source or use +one of the binary distributions of it. In either case, if you use a separate +protoc, you need to manually give the path to nanopb generator: + + protoc --plugin=protoc-gen-nanopb=nanopb/generator/protoc-gen-nanopb ... + + + +Running the tests +----------------- +If you want to perform further development of the nanopb core, or to verify +its functionality using your compiler and platform, you'll want to run the +test suite. The build rules for the test suite are implemented using Scons, +so you need to have that installed. To run the tests: + + cd tests + scons + +This will show the progress of various test cases. If the output does not +end in an error, the test cases were successful. + +Note: Mac OS X by default aliases 'clang' as 'gcc', while not actually +supporting the same command line options as gcc does. To run tests on +Mac OS X, use: "scons CC=clang CXX=clang". Same way can be used to run +tests with different compilers on any platform. diff --git a/libs/nanopb/docs/Makefile b/libs/nanopb/docs/Makefile new file mode 100644 index 00000000..0dbd97cf --- /dev/null +++ b/libs/nanopb/docs/Makefile @@ -0,0 +1,9 @@ +all: index.html concepts.html reference.html security.html migration.html \ + generator_flow.png + +%.png: %.svg + rsvg $< $@ + +%.html: %.rst + rst2html --stylesheet=lsr.css --link-stylesheet $< $@ + sed -i 's!!\n!' $@ diff --git a/libs/nanopb/docs/concepts.rst b/libs/nanopb/docs/concepts.rst new file mode 100644 index 00000000..2e0d3f9b --- /dev/null +++ b/libs/nanopb/docs/concepts.rst @@ -0,0 +1,392 @@ +====================== +Nanopb: Basic concepts +====================== + +.. include :: menu.rst + +The things outlined here are the underlying concepts of the nanopb design. + +.. contents:: + +Proto files +=========== +All Protocol Buffers implementations use .proto files to describe the message +format. The point of these files is to be a portable interface description +language. + +Compiling .proto files for nanopb +--------------------------------- +Nanopb uses the Google's protoc compiler to parse the .proto file, and then a +python script to generate the C header and source code from it:: + + user@host:~$ protoc -omessage.pb message.proto + user@host:~$ python ../generator/nanopb_generator.py message.pb + Writing to message.h and message.c + user@host:~$ + +Modifying generator behaviour +----------------------------- +Using generator options, you can set maximum sizes for fields in order to +allocate them statically. The preferred way to do this is to create an .options +file with the same name as your .proto file:: + + # Foo.proto + message Foo { + required string name = 1; + } + +:: + + # Foo.options + Foo.name max_size:16 + +For more information on this, see the `Proto file options`_ section in the +reference manual. + +.. _`Proto file options`: reference.html#proto-file-options + +Streams +======= + +Nanopb uses streams for accessing the data in encoded format. +The stream abstraction is very lightweight, and consists of a structure (*pb_ostream_t* or *pb_istream_t*) which contains a pointer to a callback function. + +There are a few generic rules for callback functions: + +#) Return false on IO errors. The encoding or decoding process will abort immediately. +#) Use state to store your own data, such as a file descriptor. +#) *bytes_written* and *bytes_left* are updated by pb_write and pb_read. +#) Your callback may be used with substreams. In this case *bytes_left*, *bytes_written* and *max_size* have smaller values than the original stream. Don't use these values to calculate pointers. +#) Always read or write the full requested length of data. For example, POSIX *recv()* needs the *MSG_WAITALL* parameter to accomplish this. + +Output streams +-------------- + +:: + + struct _pb_ostream_t + { + bool (*callback)(pb_ostream_t *stream, const uint8_t *buf, size_t count); + void *state; + size_t max_size; + size_t bytes_written; + }; + +The *callback* for output stream may be NULL, in which case the stream simply counts the number of bytes written. In this case, *max_size* is ignored. + +Otherwise, if *bytes_written* + bytes_to_be_written is larger than *max_size*, pb_write returns false before doing anything else. If you don't want to limit the size of the stream, pass SIZE_MAX. + +**Example 1:** + +This is the way to get the size of the message without storing it anywhere:: + + Person myperson = ...; + pb_ostream_t sizestream = {0}; + pb_encode(&sizestream, Person_fields, &myperson); + printf("Encoded size is %d\n", sizestream.bytes_written); + +**Example 2:** + +Writing to stdout:: + + bool callback(pb_ostream_t *stream, const uint8_t *buf, size_t count) + { + FILE *file = (FILE*) stream->state; + return fwrite(buf, 1, count, file) == count; + } + + pb_ostream_t stdoutstream = {&callback, stdout, SIZE_MAX, 0}; + +Input streams +------------- +For input streams, there is one extra rule: + +#) You don't need to know the length of the message in advance. After getting EOF error when reading, set bytes_left to 0 and return false. Pb_decode will detect this and if the EOF was in a proper position, it will return true. + +Here is the structure:: + + struct _pb_istream_t + { + bool (*callback)(pb_istream_t *stream, uint8_t *buf, size_t count); + void *state; + size_t bytes_left; + }; + +The *callback* must always be a function pointer. *Bytes_left* is an upper limit on the number of bytes that will be read. You can use SIZE_MAX if your callback handles EOF as described above. + +**Example:** + +This function binds an input stream to stdin: + +:: + + bool callback(pb_istream_t *stream, uint8_t *buf, size_t count) + { + FILE *file = (FILE*)stream->state; + bool status; + + if (buf == NULL) + { + while (count-- && fgetc(file) != EOF); + return count == 0; + } + + status = (fread(buf, 1, count, file) == count); + + if (feof(file)) + stream->bytes_left = 0; + + return status; + } + + pb_istream_t stdinstream = {&callback, stdin, SIZE_MAX}; + +Data types +========== + +Most Protocol Buffers datatypes have directly corresponding C datatypes, such as int32 is int32_t, float is float and bool is bool. However, the variable-length datatypes are more complex: + +1) Strings, bytes and repeated fields of any type map to callback functions by default. +2) If there is a special option *(nanopb).max_size* specified in the .proto file, string maps to null-terminated char array and bytes map to a structure containing a char array and a size field. +3) If *(nanopb).fixed_length* is set to *true* and *(nanopb).max_size* is also set, then bytes map to an inline byte array of fixed size. +4) If there is a special option *(nanopb).max_count* specified on a repeated field, it maps to an array of whatever type is being repeated. Another field will be created for the actual number of entries stored. + +=============================================================================== ======================= + field in .proto autogenerated in .h +=============================================================================== ======================= +required string name = 1; pb_callback_t name; +required string name = 1 [(nanopb).max_size = 40]; char name[40]; +repeated string name = 1 [(nanopb).max_size = 40]; pb_callback_t name; +repeated string name = 1 [(nanopb).max_size = 40, (nanopb).max_count = 5]; | size_t name_count; + | char name[5][40]; +required bytes data = 1 [(nanopb).max_size = 40]; | typedef struct { + | size_t size; + | pb_byte_t bytes[40]; + | } Person_data_t; + | Person_data_t data; +required bytes data = 1 [(nanopb).max_size = 40, (nanopb).fixed_length = true]; | pb_byte_t data[40]; +=============================================================================== ======================= + +The maximum lengths are checked in runtime. If string/bytes/array exceeds the allocated length, *pb_decode* will return false. + +Note: for the *bytes* datatype, the field length checking may not be exact. +The compiler may add some padding to the *pb_bytes_t* structure, and the nanopb runtime doesn't know how much of the structure size is padding. Therefore it uses the whole length of the structure for storing data, which is not very smart but shouldn't cause problems. In practise, this means that if you specify *(nanopb).max_size=5* on a *bytes* field, you may be able to store 6 bytes there. For the *string* field type, the length limit is exact. + +Field callbacks +=============== +When a field has dynamic length, nanopb cannot statically allocate storage for it. Instead, it allows you to handle the field in whatever way you want, using a callback function. + +The `pb_callback_t`_ structure contains a function pointer and a *void* pointer called *arg* you can use for passing data to the callback. If the function pointer is NULL, the field will be skipped. A pointer to the *arg* is passed to the function, so that it can modify it and retrieve the value. + +The actual behavior of the callback function is different in encoding and decoding modes. In encoding mode, the callback is called once and should write out everything, including field tags. In decoding mode, the callback is called repeatedly for every data item. + +.. _`pb_callback_t`: reference.html#pb-callback-t + +Encoding callbacks +------------------ +:: + + bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, void * const *arg); + +When encoding, the callback should write out complete fields, including the wire type and field number tag. It can write as many or as few fields as it likes. For example, if you want to write out an array as *repeated* field, you should do it all in a single call. + +Usually you can use `pb_encode_tag_for_field`_ to encode the wire type and tag number of the field. However, if you want to encode a repeated field as a packed array, you must call `pb_encode_tag`_ instead to specify a wire type of *PB_WT_STRING*. + +If the callback is used in a submessage, it will be called multiple times during a single call to `pb_encode`_. In this case, it must produce the same amount of data every time. If the callback is directly in the main message, it is called only once. + +.. _`pb_encode`: reference.html#pb-encode +.. _`pb_encode_tag_for_field`: reference.html#pb-encode-tag-for-field +.. _`pb_encode_tag`: reference.html#pb-encode-tag + +This callback writes out a dynamically sized string:: + + bool write_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) + { + char *str = get_string_from_somewhere(); + if (!pb_encode_tag_for_field(stream, field)) + return false; + + return pb_encode_string(stream, (uint8_t*)str, strlen(str)); + } + +Decoding callbacks +------------------ +:: + + bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void **arg); + +When decoding, the callback receives a length-limited substring that reads the contents of a single field. The field tag has already been read. For *string* and *bytes*, the length value has already been parsed, and is available at *stream->bytes_left*. + +The callback will be called multiple times for repeated fields. For packed fields, you can either read multiple values until the stream ends, or leave it to `pb_decode`_ to call your function over and over until all values have been read. + +.. _`pb_decode`: reference.html#pb-decode + +This callback reads multiple integers and prints them:: + + bool read_ints(pb_istream_t *stream, const pb_field_t *field, void **arg) + { + while (stream->bytes_left) + { + uint64_t value; + if (!pb_decode_varint(stream, &value)) + return false; + printf("%lld\n", value); + } + return true; + } + +Field description array +======================= + +For using the *pb_encode* and *pb_decode* functions, you need an array of pb_field_t constants describing the structure you wish to encode. This description is usually autogenerated from .proto file. + +For example this submessage in the Person.proto file:: + + message Person { + message PhoneNumber { + required string number = 1 [(nanopb).max_size = 40]; + optional PhoneType type = 2 [default = HOME]; + } + } + +generates this field description array for the structure *Person_PhoneNumber*:: + + const pb_field_t Person_PhoneNumber_fields[3] = { + PB_FIELD( 1, STRING , REQUIRED, STATIC, Person_PhoneNumber, number, number, 0), + PB_FIELD( 2, ENUM , OPTIONAL, STATIC, Person_PhoneNumber, type, number, &Person_PhoneNumber_type_default), + PB_LAST_FIELD + }; + +Oneof +===== +Protocol Buffers supports `oneof`_ sections. Here is an example of ``oneof`` usage:: + + message MsgType1 { + required int32 value = 1; + } + + message MsgType2 { + required bool value = 1; + } + + message MsgType3 { + required int32 value1 = 1; + required int32 value2 = 2; + } + + message MyMessage { + required uint32 uid = 1; + required uint32 pid = 2; + required uint32 utime = 3; + + oneof payload { + MsgType1 msg1 = 4; + MsgType2 msg2 = 5; + MsgType3 msg3 = 6; + } + } + +Nanopb will generate ``payload`` as a C union and add an additional field ``which_payload``:: + + typedef struct _MyMessage { + uint32_t uid; + uint32_t pid; + uint32_t utime; + pb_size_t which_payload; + union { + MsgType1 msg1; + MsgType2 msg2; + MsgType3 msg3; + } payload; + /* @@protoc_insertion_point(struct:MyMessage) */ + } MyMessage; + +``which_payload`` indicates which of the ``oneof`` fields is actually set. +The user is expected to set the filed manually using the correct field tag:: + + MyMessage msg = MyMessage_init_zero; + msg.payload.msg2.value = true; + msg.which_payload = MyMessage_msg2_tag; + +Notice that neither ``which_payload`` field nor the unused fileds in ``payload`` +will consume any space in the resulting encoded message. + +.. _`oneof`: https://developers.google.com/protocol-buffers/docs/reference/proto2-spec#oneof_and_oneof_field + +Extension fields +================ +Protocol Buffers supports a concept of `extension fields`_, which are +additional fields to a message, but defined outside the actual message. +The definition can even be in a completely separate .proto file. + +The base message is declared as extensible by keyword *extensions* in +the .proto file:: + + message MyMessage { + .. fields .. + extensions 100 to 199; + } + +For each extensible message, *nanopb_generator.py* declares an additional +callback field called *extensions*. The field and associated datatype +*pb_extension_t* forms a linked list of handlers. When an unknown field is +encountered, the decoder calls each handler in turn until either one of them +handles the field, or the list is exhausted. + +The actual extensions are declared using the *extend* keyword in the .proto, +and are in the global namespace:: + + extend MyMessage { + optional int32 myextension = 100; + } + +For each extension, *nanopb_generator.py* creates a constant of type +*pb_extension_type_t*. To link together the base message and the extension, +you have to: + +1. Allocate storage for your field, matching the datatype in the .proto. + For example, for a *int32* field, you need a *int32_t* variable to store + the value. +2. Create a *pb_extension_t* constant, with pointers to your variable and + to the generated *pb_extension_type_t*. +3. Set the *message.extensions* pointer to point to the *pb_extension_t*. + +An example of this is available in *tests/test_encode_extensions.c* and +*tests/test_decode_extensions.c*. + +.. _`extension fields`: https://developers.google.com/protocol-buffers/docs/proto#extensions + +Message framing +=============== +Protocol Buffers does not specify a method of framing the messages for transmission. +This is something that must be provided by the library user, as there is no one-size-fits-all +solution. Typical needs for a framing format are to: + +1. Encode the message length. +2. Encode the message type. +3. Perform any synchronization and error checking that may be needed depending on application. + +For example UDP packets already fullfill all the requirements, and TCP streams typically only +need a way to identify the message length and type. Lower level interfaces such as serial ports +may need a more robust frame format, such as HDLC (high-level data link control). + +Nanopb provides a few helpers to facilitate implementing framing formats: + +1. Functions *pb_encode_delimited* and *pb_decode_delimited* prefix the message data with a varint-encoded length. +2. Union messages and oneofs are supported in order to implement top-level container messages. +3. Message IDs can be specified using the *(nanopb_msgopt).msgid* option and can then be accessed from the header. + +Return values and error handling +================================ + +Most functions in nanopb return bool: *true* means success, *false* means failure. There is also some support for error messages for debugging purposes: the error messages go in *stream->errmsg*. + +The error messages help in guessing what is the underlying cause of the error. The most common error conditions are: + +1) Running out of memory, i.e. stack overflow. +2) Invalid field descriptors (would usually mean a bug in the generator). +3) IO errors in your own stream callbacks. +4) Errors that happen in your callback functions. +5) Exceeding the max_size or bytes_left of a stream. +6) Exceeding the max_size of a string or array field +7) Invalid protocol buffers binary message. diff --git a/libs/nanopb/docs/generator_flow.svg b/libs/nanopb/docs/generator_flow.svg new file mode 100644 index 00000000..e30277a7 --- /dev/null +++ b/libs/nanopb/docs/generator_flow.svg @@ -0,0 +1,2869 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + MyMessage.proto + + + pb_encode( ); + pb_decode( ); + + + nanopb_generator.py + + + + + + + + + + + + + + + + + + MyMessage.pb.c + MyMessage.pb.h + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + c + + Nanopb library + + + + Protocol Buffersmessages + + + + + + + + + + + + + + + + + + + + + Data structures + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + User application + + + diff --git a/libs/nanopb/docs/index.rst b/libs/nanopb/docs/index.rst new file mode 100644 index 00000000..afc7ee4f --- /dev/null +++ b/libs/nanopb/docs/index.rst @@ -0,0 +1,127 @@ +============================================= +Nanopb: Protocol Buffers with small code size +============================================= + +.. include :: menu.rst + +Nanopb is an ANSI-C library for encoding and decoding messages in Google's `Protocol Buffers`__ format with minimal requirements for RAM and code space. +It is primarily suitable for 32-bit microcontrollers. + +__ https://developers.google.com/protocol-buffers/docs/reference/overview + +Overall structure +================= + +For the runtime program, you always need *pb.h* for type declarations. +Depending on whether you want to encode, decode, or both, you also need *pb_encode.h/c* or *pb_decode.h/c*. + +The high-level encoding and decoding functions take an array of *pb_field_t* structures, which describes the fields of a message structure. Usually you want these autogenerated from a *.proto* file. The tool script *nanopb_generator.py* accomplishes this. + +.. image:: generator_flow.png + +So a typical project might include these files: + +1) Nanopb runtime library: + - pb.h + - pb_common.h and pb_common.c (always needed) + - pb_decode.h and pb_decode.c (needed for decoding messages) + - pb_encode.h and pb_encode.c (needed for encoding messages) +2) Protocol description (you can have many): + - person.proto (just an example) + - person.pb.c (autogenerated, contains initializers for const arrays) + - person.pb.h (autogenerated, contains type declarations) + +Features and limitations +======================== + +**Features** + +#) Pure C runtime +#) Small code size (2–10 kB depending on processor, plus any message definitions) +#) Small ram usage (typically ~300 bytes, plus any message structs) +#) Allows specifying maximum size for strings and arrays, so that they can be allocated statically. +#) No malloc needed: everything can be allocated statically or on the stack. Optional malloc support available. +#) You can use either encoder or decoder alone to cut the code size in half. +#) Support for most protobuf features, including: all data types, nested submessages, default values, repeated and optional fields, oneofs, packed arrays, extension fields. +#) Callback mechanism for handling messages larger than can fit in available RAM. +#) Extensive set of tests. + +**Limitations** + +#) Some speed has been sacrificed for code size. +#) Encoding is focused on writing to streams. For memory buffers only it could be made more efficient. +#) The deprecated Protocol Buffers feature called "groups" is not supported. +#) Fields in the generated structs are ordered by the tag number, instead of the natural ordering in .proto file. +#) Unknown fields are not preserved when decoding and re-encoding a message. +#) Reflection (runtime introspection) is not supported. E.g. you can't request a field by giving its name in a string. +#) Numeric arrays are always encoded as packed, even if not marked as packed in .proto. +#) Cyclic references between messages are supported only in callback and malloc mode. + +Getting started +=============== + +For starters, consider this simple message:: + + message Example { + required int32 value = 1; + } + +Save this in *message.proto* and compile it:: + + user@host:~$ protoc -omessage.pb message.proto + user@host:~$ python nanopb/generator/nanopb_generator.py message.pb + +You should now have in *message.pb.h*:: + + typedef struct { + int32_t value; + } Example; + + extern const pb_field_t Example_fields[2]; + +Now in your main program do this to encode a message:: + + Example mymessage = {42}; + uint8_t buffer[10]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + pb_encode(&stream, Example_fields, &mymessage); + +After that, buffer will contain the encoded message. +The number of bytes in the message is stored in *stream.bytes_written*. +You can feed the message to *protoc --decode=Example message.proto* to verify its validity. + +For a complete example of the simple case, see *example/simple.c*. +For a more complex example with network interface, see the *example/network_server* subdirectory. + +Compiler requirements +===================== +Nanopb should compile with most ansi-C compatible compilers. It however +requires a few header files to be available: + +#) *string.h*, with these functions: *strlen*, *memcpy*, *memset* +#) *stdint.h*, for definitions of *int32_t* etc. +#) *stddef.h*, for definition of *size_t* +#) *stdbool.h*, for definition of *bool* + +If these header files do not come with your compiler, you can use the +file *extra/pb_syshdr.h* instead. It contains an example of how to provide +the dependencies. You may have to edit it a bit to suit your custom platform. + +To use the pb_syshdr.h, define *PB_SYSTEM_HEADER* as *"pb_syshdr.h"* (including the quotes). +Similarly, you can provide a custom include file, which should provide all the dependencies +listed above. + +Running the test cases +====================== +Extensive unittests and test cases are included under the *tests* folder. + +To build the tests, you will need the `scons`__ build system. The tests should +be runnable on most platforms. Windows and Linux builds are regularly tested. + +__ http://www.scons.org/ + +In addition to the build system, you will also need a working Google Protocol +Buffers *protoc* compiler, and the Python bindings for Protocol Buffers. On +Debian-based systems, install the following packages: *protobuf-compiler*, +*python-protobuf* and *libprotobuf-dev*. + diff --git a/libs/nanopb/docs/logo/logo.png b/libs/nanopb/docs/logo/logo.png new file mode 100644 index 00000000..0d9534fa Binary files /dev/null and b/libs/nanopb/docs/logo/logo.png differ diff --git a/libs/nanopb/docs/logo/logo.svg b/libs/nanopb/docs/logo/logo.svg new file mode 100644 index 00000000..91ab28b6 --- /dev/null +++ b/libs/nanopb/docs/logo/logo.svg @@ -0,0 +1,1470 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + Pb + Pb + + + + + + + + + + + + + + + + + + nano + nano + + + + + diff --git a/libs/nanopb/docs/logo/logo16px.png b/libs/nanopb/docs/logo/logo16px.png new file mode 100644 index 00000000..8db0e2ef Binary files /dev/null and b/libs/nanopb/docs/logo/logo16px.png differ diff --git a/libs/nanopb/docs/logo/logo48px.png b/libs/nanopb/docs/logo/logo48px.png new file mode 100644 index 00000000..b598c011 Binary files /dev/null and b/libs/nanopb/docs/logo/logo48px.png differ diff --git a/libs/nanopb/docs/lsr.css b/libs/nanopb/docs/lsr.css new file mode 100644 index 00000000..429bce51 --- /dev/null +++ b/libs/nanopb/docs/lsr.css @@ -0,0 +1,240 @@ +/* +Author: Peter Parente +Date: 2008/01/22 +Version: 1.0 (modified) +Copyright: This stylesheet has been placed in the public domain - free to edit and use for all uses. +*/ + +body { + font: 100% sans-serif; + background: #ffffff; + color: black; + margin: 2em; + padding: 0em 2em; +} + +p.topic-title { + font-weight: bold; +} + +table.docinfo { + text-align: left; + margin: 2em 0em; +} + +a[href] { + color: #436976; + background-color: transparent; +} + +a.toc-backref { + text-decoration: none; +} + +h1 a[href] { + color: #003a6b; + text-decoration: none; + background-color: transparent; +} + +a.strong { + font-weight: bold; +} + +img { + margin: 0; + border: 0; +} + +p { + margin: 0.5em 0 1em 0; + line-height: 1.5em; +} + +p a:visited { + color: purple; + background-color: transparent; +} + +p a:active { + color: red; + background-color: transparent; +} + +a:hover { + text-decoration: none; +} + +p img { + border: 0; + margin: 0; +} + +p.rubric { + font-weight: bold; + font-style: italic; +} + +em { + font-style: normal; + font-family: monospace; + font-weight: bold; +} + +pre { + border-left: 3px double #aaa; + padding: 5px 10px; + background-color: #f6f6f6; +} + +h1.title { + color: #003a6b; + font-size: 180%; + margin-bottom: 0em; +} + +h2.subtitle { + color: #003a6b; + border-bottom: 0px; +} + +h1, h2, h3, h4, h5, h6 { + color: #555; + background-color: transparent; + margin: 0em; + padding-top: 0.5em; +} + +h1 { + font-size: 150%; + margin-bottom: 0.5em; + border-bottom: 2px solid #aaa; +} + +h2 { + font-size: 130%; + margin-bottom: 0.5em; + border-bottom: 1px solid #aaa; +} + +h3 { + font-size: 120%; + margin-bottom: 0.5em; +} + +h4 { + font-size: 110%; + font-weight: bold; + margin-bottom: 0.5em; +} + +h5 { + font-size: 105%; + font-weight: bold; + margin-bottom: 0.5em; +} + +h6 { + font-size: 100%; + font-weight: bold; + margin-bottom: 0.5em; +} + +dt { + font-style: italic; +} + +dd { + margin-bottom: 1.5em; +} + +div.admonition, div.note, div.tip, div.caution, div.important { + margin: 2em 2em; + padding: 0em 1em; + border-top: 1px solid #aaa; + border-left: 1px solid #aaa; + border-bottom: 2px solid #555; + border-right: 2px solid #555; +} + +div.important { + background: transparent url('../images/important.png') 10px 2px no-repeat; +} + +div.caution { + background: transparent url('../images/caution.png') 10px 2px no-repeat; +} + +div.note { + background: transparent url('../images/note.png') 10px 2px no-repeat; +} + +div.tip { + background: transparent url('../images/tip.png') 10px 2px no-repeat; +} + +div.admonition-example { + background: transparent url('../images/tip.png') 10px 2px no-repeat; +} + +div.admonition-critical-example { + background: transparent url('../images/important.png') 10px 2px no-repeat; +} + +p.admonition-title { + font-weight: bold; + border-bottom: 1px solid #aaa; + padding-left: 30px; +} + +table.docutils { + text-align: left; + border: 1px solid gray; + border-collapse: collapse; + margin: 1.5em 0em; +} + +table.docutils caption { + font-style: italic; +} + +table.docutils td, table.docutils th { + padding: 0.25em 0.5em; +} + +th.field-name { + text-align: right; + width: 15em; +} + +table.docutils th { + font-family: monospace; + background-color: #f6f6f6; + vertical-align: middle; +} + +table.field-list { + border: none; +} + +div.sidebar { + margin: 2em 2em 2em 0em; + padding: 0em 1em; + border-top: 1px solid #aaa; + border-left: 1px solid #aaa; + border-bottom: 2px solid #555; + border-right: 2px solid #555; +} + +p.sidebar-title { + margin-bottom: 0em; + color: #003a6b; + border-bottom: 1px solid #aaa; + font-weight: bold; +} + +p.sidebar-subtitle { + margin-top: 0em; + font-style: italic; + color: #003a6b; +} diff --git a/libs/nanopb/docs/menu.rst b/libs/nanopb/docs/menu.rst new file mode 100644 index 00000000..2c110def --- /dev/null +++ b/libs/nanopb/docs/menu.rst @@ -0,0 +1,13 @@ +.. sidebar :: Documentation index + + 1) `Overview`_ + 2) `Concepts`_ + 3) `API reference`_ + 4) `Security model`_ + 5) `Migration from older versions`_ + +.. _`Overview`: index.html +.. _`Concepts`: concepts.html +.. _`API reference`: reference.html +.. _`Security model`: security.html +.. _`Migration from older versions`: migration.html diff --git a/libs/nanopb/docs/migration.rst b/libs/nanopb/docs/migration.rst new file mode 100644 index 00000000..d6b32b53 --- /dev/null +++ b/libs/nanopb/docs/migration.rst @@ -0,0 +1,289 @@ +===================================== +Nanopb: Migration from older versions +===================================== + +.. include :: menu.rst + +This document details all the breaking changes that have been made to nanopb +since its initial release. For each change, the rationale and required +modifications of user applications are explained. Also any error indications +are included, in order to make it easier to find this document. + +.. contents :: + +Nanopb-0.3.8 (2017-03-05) +========================= +Fully drain substreams before closing + +**Rationale:** If the substream functions were called directly and the caller +did not completely empty the substring before closing it, the parent stream +would be put into an incorrect state. + +**Changes:** *pb_close_string_substream* can now error and returns a boolean. + +**Required actions:** Add error checking onto any call to +*pb_close_string_substream*. + +Nanopb-0.3.5 (2016-02-13) +========================= + +Add support for platforms without uint8_t +----------------------------------------- +**Rationale:** Some platforms cannot access 8-bit sized values directly, and +do not define *uint8_t*. Nanopb previously didn't support these platforms. + +**Changes:** References to *uint8_t* were replaced with several alternatives, +one of them being a new *pb_byte_t* typedef. This in turn uses *uint_least8_t* +which means the smallest available type. + +**Required actions:** If your platform does not have a standards-compliant +*stdint.h*, it may lack the definition for *[u]int_least8_t*. This must be +added manually, example can be found in *extra/pb_syshdr.h*. + +**Error indications:** Compiler error: "unknown type name 'uint_least8_t'". + +Nanopb-0.3.2 (2015-01-24) +========================= + +Add support for OneOfs +---------------------- +**Rationale:** Previously nanopb did not support the *oneof* construct in +*.proto* files. Those fields were generated as regular *optional* fields. + +**Changes:** OneOfs are now generated as C unions. Callback fields are not +supported inside oneof and generator gives an error. + +**Required actions:** The generator option *no_unions* can be used to restore old +behaviour and to allow callbacks to be used. To use unions, one change is +needed: use *which_xxxx* field to detect which field is present, instead +of *has_xxxx*. Compare the value against *MyStruct_myfield_tag*. + +**Error indications:** Generator error: "Callback fields inside of oneof are +not supported". Compiler error: "Message" has no member named "has_xxxx". + +Nanopb-0.3.0 (2014-08-26) +========================= + +Separate field iterator logic to pb_common.c +-------------------------------------------- +**Rationale:** Originally, the field iteration logic was simple enough to be +duplicated in *pb_decode.c* and *pb_encode.c*. New field types have made the +logic more complex, which required the creation of a new file to contain the +common functionality. + +**Changes:** There is a new file, *pb_common.c*, which must be included in +builds. + +**Required actions:** Add *pb_common.c* to build rules. This file is always +required. Either *pb_decode.c* or *pb_encode.c* can still be left out if some +functionality is not needed. + +**Error indications:** Linker error: undefined reference to +*pb_field_iter_begin*, *pb_field_iter_next* or similar. + +Change data type of field counts to pb_size_t +--------------------------------------------- +**Rationale:** Often nanopb is used with small arrays, such as 255 items or +less. Using a full *size_t* field to store the array count wastes memory if +there are many arrays. There already exists parameters *PB_FIELD_16BIT* and +*PB_FIELD_32BIT* which tell nanopb what is the maximum size of arrays in use. + +**Changes:** Generator will now use *pb_size_t* for the array *_count* fields. +The size of the type will be controlled by the *PB_FIELD_16BIT* and +*PB_FIELD_32BIT* compilation time options. + +**Required actions:** Regenerate all *.pb.h* files. In some cases casts to the +*pb_size_t* type may need to be added in the user code when accessing the +*_count* fields. + +**Error indications:** Incorrect data at runtime, crashes. But note that other +changes in the same version already require regenerating the files and have +better indications of errors, so this is only an issue for development +versions. + +Renamed some macros and identifiers +----------------------------------- +**Rationale:** Some names in nanopb core were badly chosen and conflicted with +ISO C99 reserved names or lacked a prefix. While they haven't caused trouble +so far, it is reasonable to switch to non-conflicting names as these are rarely +used from user code. + +**Changes:** The following identifier names have changed: + + * Macros: + + * STATIC_ASSERT(x) -> PB_STATIC_ASSERT(x) + * UNUSED(x) -> PB_UNUSED(x) + + * Include guards: + + * _PB_filename_ -> PB_filename_INCLUDED + + * Structure forward declaration tags: + + * _pb_field_t -> pb_field_s + * _pb_bytes_array_t -> pb_bytes_array_s + * _pb_callback_t -> pb_callback_s + * _pb_extension_type_t -> pb_extension_type_s + * _pb_extension_t -> pb_extension_s + * _pb_istream_t -> pb_istream_s + * _pb_ostream_t -> pb_ostream_s + +**Required actions:** Regenerate all *.pb.c* files. If you use any of the above +identifiers in your application code, perform search-replace to the new name. + +**Error indications:** Compiler errors on lines with the macro/type names. + +Nanopb-0.2.9 (2014-08-09) +========================= + +Change semantics of generator -e option +--------------------------------------- +**Rationale:** Some compilers do not accept filenames with two dots (like +in default extension .pb.c). The *-e* option to the generator allowed changing +the extension, but not skipping the extra dot. + +**Changes:** The *-e* option in generator will no longer add the prepending +dot. The default value has been adjusted accordingly to *.pb.c* to keep the +default behaviour the same as before. + +**Required actions:** Only if using the generator -e option. Add dot before +the parameter value on the command line. + +**Error indications:** File not found when trying to compile generated files. + +Nanopb-0.2.7 (2014-04-07) +========================= + +Changed pointer-type bytes field datatype +----------------------------------------- +**Rationale:** In the initial pointer encoding support since nanopb-0.2.5, +the bytes type used a separate *pb_bytes_ptr_t* type to represent *bytes* +fields. This made it easy to encode data from a separate, user-allocated +buffer. However, it made the internal logic more complex and was inconsistent +with the other types. + +**Changes:** Dynamically allocated bytes fields now have the *pb_bytes_array_t* +type, just like statically allocated ones. + +**Required actions:** Only if using pointer-type fields with the bytes datatype. +Change any access to *msg->field.size* to *msg->field->size*. Change any +allocation to reserve space of amount *PB_BYTES_ARRAY_T_ALLOCSIZE(n)*. If the +data pointer was begin assigned from external source, implement the field using +a callback function instead. + +**Error indications:** Compiler error: unknown type name *pb_bytes_ptr_t*. + +Nanopb-0.2.4 (2013-11-07) +========================= + +Remove the NANOPB_INTERNALS compilation option +---------------------------------------------- +**Rationale:** Having the option in the headers required the functions to +be non-static, even if the option is not used. This caused errors on some +static analysis tools. + +**Changes:** The *#ifdef* and associated functions were removed from the +header. + +**Required actions:** Only if the *NANOPB_INTERNALS* option was previously +used. Actions are as listed under nanopb-0.1.3 and nanopb-0.1.6. + +**Error indications:** Compiler warning: implicit declaration of function +*pb_dec_string*, *pb_enc_string*, or similar. + +Nanopb-0.2.1 (2013-04-14) +========================= + +Callback function signature +--------------------------- +**Rationale:** Previously the auxilary data to field callbacks was passed +as *void\**. This allowed passing of any data, but made it unnecessarily +complex to return a pointer from callback. + +**Changes:** The callback function parameter was changed to *void\*\**. + +**Required actions:** You can continue using the old callback style by +defining *PB_OLD_CALLBACK_STYLE*. Recommended action is to: + + * Change the callback signatures to contain *void\*\** for decoders and + *void \* const \** for encoders. + * Change the callback function body to use *\*arg* instead of *arg*. + +**Error indications:** Compiler warning: assignment from incompatible +pointer type, when initializing *funcs.encode* or *funcs.decode*. + +Nanopb-0.2.0 (2013-03-02) +========================= + +Reformatted generated .pb.c file using macros +--------------------------------------------- +**Rationale:** Previously the generator made a list of C *pb_field_t* +initializers in the .pb.c file. This led to a need to regenerate all .pb.c +files after even small changes to the *pb_field_t* definition. + +**Changes:** Macros were added to pb.h which allow for cleaner definition +of the .pb.c contents. By changing the macro definitions, changes to the +field structure are possible without breaking compatibility with old .pb.c +files. + +**Required actions:** Regenerate all .pb.c files from the .proto sources. + +**Error indications:** Compiler warning: implicit declaration of function +*pb_delta_end*. + +Changed pb_type_t definitions +----------------------------- +**Rationale:** The *pb_type_t* was previously an enumeration type. This +caused warnings on some compilers when using bitwise operations to set flags +inside the values. + +**Changes:** The *pb_type_t* was changed to *typedef uint8_t*. The values +were changed to *#define*. Some value names were changed for consistency. + +**Required actions:** Only if you directly access the `pb_field_t` contents +in your own code, something which is not usually done. Needed changes: + + * Change *PB_HTYPE_ARRAY* to *PB_HTYPE_REPEATED*. + * Change *PB_HTYPE_CALLBACK* to *PB_ATYPE()* and *PB_ATYPE_CALLBACK*. + +**Error indications:** Compiler error: *PB_HTYPE_ARRAY* or *PB_HTYPE_CALLBACK* +undeclared. + +Nanopb-0.1.6 (2012-09-02) +========================= + +Refactored field decoder interface +---------------------------------- +**Rationale:** Similarly to field encoders in nanopb-0.1.3. + +**Changes:** New functions with names *pb_decode_\** were added. + +**Required actions:** By defining NANOPB_INTERNALS, you can still keep using +the old functions. Recommended action is to replace any calls with the newer +*pb_decode_\** equivalents. + +**Error indications:** Compiler warning: implicit declaration of function +*pb_dec_string*, *pb_dec_varint*, *pb_dec_submessage* or similar. + +Nanopb-0.1.3 (2012-06-12) +========================= + +Refactored field encoder interface +---------------------------------- +**Rationale:** The old *pb_enc_\** functions were designed mostly for the +internal use by the core. Because they are internally accessed through +function pointers, their signatures had to be common. This led to a confusing +interface for external users. + +**Changes:** New functions with names *pb_encode_\** were added. These have +easier to use interfaces. The old functions are now only thin wrappers for +the new interface. + +**Required actions:** By defining NANOPB_INTERNALS, you can still keep using +the old functions. Recommended action is to replace any calls with the newer +*pb_encode_\** equivalents. + +**Error indications:** Compiler warning: implicit declaration of function +*pb_enc_string*, *pb_enc_varint, *pb_enc_submessage* or similar. + diff --git a/libs/nanopb/docs/reference.rst b/libs/nanopb/docs/reference.rst new file mode 100644 index 00000000..e59a0c94 --- /dev/null +++ b/libs/nanopb/docs/reference.rst @@ -0,0 +1,770 @@ +===================== +Nanopb: API reference +===================== + +.. include :: menu.rst + +.. contents :: + + + + +Compilation options +=================== +The following options can be specified in one of two ways: + +1. Using the -D switch on the C compiler command line. +2. By #defining them at the top of pb.h. + +You must have the same settings for the nanopb library and all code that +includes pb.h. + +============================ ================================================ +PB_NO_PACKED_STRUCTS Disable packed structs. Increases RAM usage but + is necessary on some platforms that do not + support unaligned memory access. +PB_ENABLE_MALLOC Set this to enable dynamic allocation support + in the decoder. +PB_MAX_REQUIRED_FIELDS Maximum number of required fields to check for + presence. Default value is 64. Increases stack + usage 1 byte per every 8 fields. Compiler + warning will tell if you need this. +PB_FIELD_16BIT Add support for tag numbers > 255 and fields + larger than 255 bytes or 255 array entries. + Increases code size 3 bytes per each field. + Compiler error will tell if you need this. +PB_FIELD_32BIT Add support for tag numbers > 65535 and fields + larger than 65535 bytes or 65535 array entries. + Increases code size 9 bytes per each field. + Compiler error will tell if you need this. +PB_NO_ERRMSG Disables the support for error messages; only + error information is the true/false return + value. Decreases the code size by a few hundred + bytes. +PB_BUFFER_ONLY Disables the support for custom streams. Only + supports encoding and decoding with memory + buffers. Speeds up execution and decreases code + size slightly. +PB_OLD_CALLBACK_STYLE Use the old function signature (void\* instead + of void\*\*) for callback fields. This was the + default until nanopb-0.2.1. +PB_SYSTEM_HEADER Replace the standard header files with a single + header file. It should define all the required + functions and typedefs listed on the + `overview page`_. Value must include quotes, + for example *#define PB_SYSTEM_HEADER "foo.h"*. +============================ ================================================ + +The PB_MAX_REQUIRED_FIELDS, PB_FIELD_16BIT and PB_FIELD_32BIT settings allow +raising some datatype limits to suit larger messages. Their need is recognized +automatically by C-preprocessor #if-directives in the generated .pb.h files. +The default setting is to use the smallest datatypes (least resources used). + +.. _`overview page`: index.html#compiler-requirements + + +Proto file options +================== +The generator behaviour can be adjusted using these options, defined in the +'nanopb.proto' file in the generator folder: + +============================ ================================================ +max_size Allocated size for *bytes* and *string* fields. +max_count Allocated number of entries in arrays + (*repeated* fields). +int_size Override the integer type of a field. + (To use e.g. uint8_t to save RAM.) +type Type of the generated field. Default value + is *FT_DEFAULT*, which selects automatically. + You can use *FT_CALLBACK*, *FT_POINTER*, + *FT_STATIC* or *FT_IGNORE* to + force a callback field, a dynamically + allocated field, a static field or to + completely ignore the field. +long_names Prefix the enum name to the enum value in + definitions, i.e. *EnumName_EnumValue*. Enabled + by default. +packed_struct Make the generated structures packed. + NOTE: This cannot be used on CPUs that break + on unaligned accesses to variables. +skip_message Skip the whole message from generation. +no_unions Generate 'oneof' fields as optional fields + instead of C unions. +msgid Specifies a unique id for this message type. + Can be used by user code as an identifier. +anonymous_oneof Generate 'oneof' fields as anonymous unions. +fixed_length Generate 'bytes' fields with constant length. +============================ ================================================ + +These options can be defined for the .proto files before they are converted +using the nanopb-generatory.py. There are three ways to define the options: + +1. Using a separate .options file. + This is the preferred way as of nanopb-0.2.1, because it has the best + compatibility with other protobuf libraries. +2. Defining the options on the command line of nanopb_generator.py. + This only makes sense for settings that apply to a whole file. +3. Defining the options in the .proto file using the nanopb extensions. + This is the way used in nanopb-0.1, and will remain supported in the + future. It however sometimes causes trouble when using the .proto file + with other protobuf libraries. + +The effect of the options is the same no matter how they are given. The most +common purpose is to define maximum size for string fields in order to +statically allocate them. + +Defining the options in a .options file +--------------------------------------- +The preferred way to define options is to have a separate file +'myproto.options' in the same directory as the 'myproto.proto'. :: + + # myproto.proto + message MyMessage { + required string name = 1; + repeated int32 ids = 4; + } + +:: + + # myproto.options + MyMessage.name max_size:40 + MyMessage.ids max_count:5 + +The generator will automatically search for this file and read the +options from it. The file format is as follows: + +* Lines starting with '#' or '//' are regarded as comments. +* Blank lines are ignored. +* All other lines should start with a field name pattern, followed by one or + more options. For example: *"MyMessage.myfield max_size:5 max_count:10"*. +* The field name pattern is matched against a string of form *'Message.field'*. + For nested messages, the string is *'Message.SubMessage.field'*. +* The field name pattern may use the notation recognized by Python fnmatch(): + + - *\** matches any part of string, like 'Message.\*' for all fields + - *\?* matches any single character + - *[seq]* matches any of characters 's', 'e' and 'q' + - *[!seq]* matches any other character + +* The options are written as *'option_name:option_value'* and several options + can be defined on same line, separated by whitespace. +* Options defined later in the file override the ones specified earlier, so + it makes sense to define wildcard options first in the file and more specific + ones later. + +If preferred, the name of the options file can be set using the command line +switch *-f* to nanopb_generator.py. + +Defining the options on command line +------------------------------------ +The nanopb_generator.py has a simple command line option *-s OPTION:VALUE*. +The setting applies to the whole file that is being processed. + +Defining the options in the .proto file +--------------------------------------- +The .proto file format allows defining custom options for the fields. +The nanopb library comes with *nanopb.proto* which does exactly that, allowing +you do define the options directly in the .proto file:: + + import "nanopb.proto"; + + message MyMessage { + required string name = 1 [(nanopb).max_size = 40]; + repeated int32 ids = 4 [(nanopb).max_count = 5]; + } + +A small complication is that you have to set the include path of protoc so that +nanopb.proto can be found. This file, in turn, requires the file +*google/protobuf/descriptor.proto*. This is usually installed under +*/usr/include*. Therefore, to compile a .proto file which uses options, use a +protoc command similar to:: + + protoc -I/usr/include -Inanopb/generator -I. -omessage.pb message.proto + +The options can be defined in file, message and field scopes:: + + option (nanopb_fileopt).max_size = 20; // File scope + message Message + { + option (nanopb_msgopt).max_size = 30; // Message scope + required string fieldsize = 1 [(nanopb).max_size = 40]; // Field scope + } + + + + + + + + + +pb.h +==== + +pb_byte_t +--------- +Type used for storing byte-sized data, such as raw binary input and bytes-type fields. :: + + typedef uint_least8_t pb_byte_t; + +For most platforms this is equivalent to `uint8_t`. Some platforms however do not support +8-bit variables, and on those platforms 16 or 32 bits need to be used for each byte. + +pb_type_t +--------- +Type used to store the type of each field, to control the encoder/decoder behaviour. :: + + typedef uint_least8_t pb_type_t; + +The low-order nibble of the enumeration values defines the function that can be used for encoding and decoding the field data: + +=========================== ===== ================================================ +LTYPE identifier Value Storage format +=========================== ===== ================================================ +PB_LTYPE_VARINT 0x00 Integer. +PB_LTYPE_UVARINT 0x01 Unsigned integer. +PB_LTYPE_SVARINT 0x02 Integer, zigzag encoded. +PB_LTYPE_FIXED32 0x03 32-bit integer or floating point. +PB_LTYPE_FIXED64 0x04 64-bit integer or floating point. +PB_LTYPE_BYTES 0x05 Structure with *size_t* field and byte array. +PB_LTYPE_STRING 0x06 Null-terminated string. +PB_LTYPE_SUBMESSAGE 0x07 Submessage structure. +PB_LTYPE_EXTENSION 0x08 Point to *pb_extension_t*. +PB_LTYPE_FIXED_LENGTH_BYTES 0x09 Inline *pb_byte_t* array of fixed size. +=========================== ===== ================================================ + +The bits 4-5 define whether the field is required, optional or repeated: + +==================== ===== ================================================ +HTYPE identifier Value Field handling +==================== ===== ================================================ +PB_HTYPE_REQUIRED 0x00 Verify that field exists in decoded message. +PB_HTYPE_OPTIONAL 0x10 Use separate *has_* boolean to specify + whether the field is present. + (Unless it is a callback) +PB_HTYPE_REPEATED 0x20 A repeated field with preallocated array. + Separate *_count* for number of items. + (Unless it is a callback) +==================== ===== ================================================ + +The bits 6-7 define the how the storage for the field is allocated: + +==================== ===== ================================================ +ATYPE identifier Value Allocation method +==================== ===== ================================================ +PB_ATYPE_STATIC 0x00 Statically allocated storage in the structure. +PB_ATYPE_CALLBACK 0x40 A field with dynamic storage size. Struct field + actually contains a pointer to a callback + function. +==================== ===== ================================================ + + +pb_field_t +---------- +Describes a single structure field with memory position in relation to others. The descriptions are usually autogenerated. :: + + typedef struct pb_field_s pb_field_t; + struct pb_field_s { + pb_size_t tag; + pb_type_t type; + pb_size_t data_offset; + pb_ssize_t size_offset; + pb_size_t data_size; + pb_size_t array_size; + const void *ptr; + } pb_packed; + +:tag: Tag number of the field or 0 to terminate a list of fields. +:type: LTYPE, HTYPE and ATYPE of the field. +:data_offset: Offset of field data, relative to the end of the previous field. +:size_offset: Offset of *bool* flag for optional fields or *size_t* count for arrays, relative to field data. +:data_size: Size of a single data entry, in bytes. For PB_LTYPE_BYTES, the size of the byte array inside the containing structure. For PB_HTYPE_CALLBACK, size of the C data type if known. +:array_size: Maximum number of entries in an array, if it is an array type. +:ptr: Pointer to default value for optional fields, or to submessage description for PB_LTYPE_SUBMESSAGE. + +The *uint8_t* datatypes limit the maximum size of a single item to 255 bytes and arrays to 255 items. Compiler will give error if the values are too large. The types can be changed to larger ones by defining *PB_FIELD_16BIT*. + +pb_bytes_array_t +---------------- +An byte array with a field for storing the length:: + + typedef struct { + pb_size_t size; + pb_byte_t bytes[1]; + } pb_bytes_array_t; + +In an actual array, the length of *bytes* may be different. + +pb_callback_t +------------- +Part of a message structure, for fields with type PB_HTYPE_CALLBACK:: + + typedef struct _pb_callback_t pb_callback_t; + struct _pb_callback_t { + union { + bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void **arg); + bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, void * const *arg); + } funcs; + + void *arg; + }; + +A pointer to the *arg* is passed to the callback when calling. It can be used to store any information that the callback might need. + +Previously the function received just the value of *arg* instead of a pointer to it. This old behaviour can be enabled by defining *PB_OLD_CALLBACK_STYLE*. + +When calling `pb_encode`_, *funcs.encode* is used, and similarly when calling `pb_decode`_, *funcs.decode* is used. The function pointers are stored in the same memory location but are of incompatible types. You can set the function pointer to NULL to skip the field. + +pb_wire_type_t +-------------- +Protocol Buffers wire types. These are used with `pb_encode_tag`_. :: + + typedef enum { + PB_WT_VARINT = 0, + PB_WT_64BIT = 1, + PB_WT_STRING = 2, + PB_WT_32BIT = 5 + } pb_wire_type_t; + +pb_extension_type_t +------------------- +Defines the handler functions and auxiliary data for a field that extends +another message. Usually autogenerated by *nanopb_generator.py*:: + + typedef struct { + bool (*decode)(pb_istream_t *stream, pb_extension_t *extension, + uint32_t tag, pb_wire_type_t wire_type); + bool (*encode)(pb_ostream_t *stream, const pb_extension_t *extension); + const void *arg; + } pb_extension_type_t; + +In the normal case, the function pointers are *NULL* and the decoder and +encoder use their internal implementations. The internal implementations +assume that *arg* points to a *pb_field_t* that describes the field in question. + +To implement custom processing of unknown fields, you can provide pointers +to your own functions. Their functionality is mostly the same as for normal +callback fields, except that they get called for any unknown field when decoding. + +pb_extension_t +-------------- +Ties together the extension field type and the storage for the field value:: + + typedef struct { + const pb_extension_type_t *type; + void *dest; + pb_extension_t *next; + bool found; + } pb_extension_t; + +:type: Pointer to the structure that defines the callback functions. +:dest: Pointer to the variable that stores the field value + (as used by the default extension callback functions.) +:next: Pointer to the next extension handler, or *NULL*. +:found: Decoder sets this to true if the extension was found. + +PB_GET_ERROR +------------ +Get the current error message from a stream, or a placeholder string if +there is no error message:: + + #define PB_GET_ERROR(stream) (string expression) + +This should be used for printing errors, for example:: + + if (!pb_decode(...)) + { + printf("Decode failed: %s\n", PB_GET_ERROR(stream)); + } + +The macro only returns pointers to constant strings (in code memory), +so that there is no need to release the returned pointer. + +PB_RETURN_ERROR +--------------- +Set the error message and return false:: + + #define PB_RETURN_ERROR(stream,msg) (sets error and returns false) + +This should be used to handle error conditions inside nanopb functions +and user callback functions:: + + if (error_condition) + { + PB_RETURN_ERROR(stream, "something went wrong"); + } + +The *msg* parameter must be a constant string. + + + +pb_encode.h +=========== + +pb_ostream_from_buffer +---------------------- +Constructs an output stream for writing into a memory buffer. This is just a helper function, it doesn't do anything you couldn't do yourself in a callback function. It uses an internal callback that stores the pointer in stream *state* field. :: + + pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize); + +:buf: Memory buffer to write into. +:bufsize: Maximum number of bytes to write. +:returns: An output stream. + +After writing, you can check *stream.bytes_written* to find out how much valid data there is in the buffer. + +pb_write +-------- +Writes data to an output stream. Always use this function, instead of trying to call stream callback manually. :: + + bool pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count); + +:stream: Output stream to write to. +:buf: Pointer to buffer with the data to be written. +:count: Number of bytes to write. +:returns: True on success, false if maximum length is exceeded or an IO error happens. + +If an error happens, *bytes_written* is not incremented. Depending on the callback used, calling pb_write again after it has failed once may be dangerous. Nanopb itself never does this, instead it returns the error to user application. The builtin pb_ostream_from_buffer is safe to call again after failed write. + +pb_encode +--------- +Encodes the contents of a structure as a protocol buffers message and writes it to output stream. :: + + bool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); + +:stream: Output stream to write to. +:fields: A field description array, usually autogenerated. +:src_struct: Pointer to the data that will be serialized. +:returns: True on success, false on IO error, on detectable errors in field description, or if a field encoder returns false. + +Normally pb_encode simply walks through the fields description array and serializes each field in turn. However, submessages must be serialized twice: first to calculate their size and then to actually write them to output. This causes some constraints for callback fields, which must return the same data on every call. + +pb_encode_delimited +------------------- +Calculates the length of the message, encodes it as varint and then encodes the message. :: + + bool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); + +(parameters are the same as for `pb_encode`_.) + +A common way to indicate the message length in Protocol Buffers is to prefix it with a varint. +This function does this, and it is compatible with *parseDelimitedFrom* in Google's protobuf library. + +.. sidebar:: Encoding fields manually + + The functions with names *pb_encode_\** are used when dealing with callback fields. The typical reason for using callbacks is to have an array of unlimited size. In that case, `pb_encode`_ will call your callback function, which in turn will call *pb_encode_\** functions repeatedly to write out values. + + The tag of a field must be encoded separately with `pb_encode_tag_for_field`_. After that, you can call exactly one of the content-writing functions to encode the payload of the field. For repeated fields, you can repeat this process multiple times. + + Writing packed arrays is a little bit more involved: you need to use `pb_encode_tag` and specify `PB_WT_STRING` as the wire type. Then you need to know exactly how much data you are going to write, and use `pb_encode_varint`_ to write out the number of bytes before writing the actual data. Substreams can be used to determine the number of bytes beforehand; see `pb_encode_submessage`_ source code for an example. + +pb_get_encoded_size +------------------- +Calculates the length of the encoded message. :: + + bool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct); + +:size: Calculated size of the encoded message. +:fields: A field description array, usually autogenerated. +:src_struct: Pointer to the data that will be serialized. +:returns: True on success, false on detectable errors in field description or if a field encoder returns false. + +pb_encode_tag +------------- +Starts a field in the Protocol Buffers binary format: encodes the field number and the wire type of the data. :: + + bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number); + +:stream: Output stream to write to. 1-5 bytes will be written. +:wiretype: PB_WT_VARINT, PB_WT_64BIT, PB_WT_STRING or PB_WT_32BIT +:field_number: Identifier for the field, defined in the .proto file. You can get it from field->tag. +:returns: True on success, false on IO error. + +pb_encode_tag_for_field +----------------------- +Same as `pb_encode_tag`_, except takes the parameters from a *pb_field_t* structure. :: + + bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field); + +:stream: Output stream to write to. 1-5 bytes will be written. +:field: Field description structure. Usually autogenerated. +:returns: True on success, false on IO error or unknown field type. + +This function only considers the LTYPE of the field. You can use it from your field callbacks, because the source generator writes correct LTYPE also for callback type fields. + +Wire type mapping is as follows: + +============================================= ============ +LTYPEs Wire type +============================================= ============ +VARINT, UVARINT, SVARINT PB_WT_VARINT +FIXED64 PB_WT_64BIT +STRING, BYTES, SUBMESSAGE, FIXED_LENGTH_BYTES PB_WT_STRING +FIXED32 PB_WT_32BIT +============================================= ============ + +pb_encode_varint +---------------- +Encodes a signed or unsigned integer in the varint_ format. Works for fields of type `bool`, `enum`, `int32`, `int64`, `uint32` and `uint64`:: + + bool pb_encode_varint(pb_ostream_t *stream, uint64_t value); + +:stream: Output stream to write to. 1-10 bytes will be written. +:value: Value to encode. Just cast e.g. int32_t directly to uint64_t. +:returns: True on success, false on IO error. + +.. _varint: http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints + +pb_encode_svarint +----------------- +Encodes a signed integer in the 'zig-zagged' format. Works for fields of type `sint32` and `sint64`:: + + bool pb_encode_svarint(pb_ostream_t *stream, int64_t value); + +(parameters are the same as for `pb_encode_varint`_ + +pb_encode_string +---------------- +Writes the length of a string as varint and then contents of the string. Works for fields of type `bytes` and `string`:: + + bool pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size); + +:stream: Output stream to write to. +:buffer: Pointer to string data. +:size: Number of bytes in the string. Pass `strlen(s)` for strings. +:returns: True on success, false on IO error. + +pb_encode_fixed32 +----------------- +Writes 4 bytes to stream and swaps bytes on big-endian architectures. Works for fields of type `fixed32`, `sfixed32` and `float`:: + + bool pb_encode_fixed32(pb_ostream_t *stream, const void *value); + +:stream: Output stream to write to. +:value: Pointer to a 4-bytes large C variable, for example `uint32_t foo;`. +:returns: True on success, false on IO error. + +pb_encode_fixed64 +----------------- +Writes 8 bytes to stream and swaps bytes on big-endian architecture. Works for fields of type `fixed64`, `sfixed64` and `double`:: + + bool pb_encode_fixed64(pb_ostream_t *stream, const void *value); + +:stream: Output stream to write to. +:value: Pointer to a 8-bytes large C variable, for example `uint64_t foo;`. +:returns: True on success, false on IO error. + +pb_encode_submessage +-------------------- +Encodes a submessage field, including the size header for it. Works for fields of any message type:: + + bool pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); + +:stream: Output stream to write to. +:fields: Pointer to the autogenerated field description array for the submessage type, e.g. `MyMessage_fields`. +:src: Pointer to the structure where submessage data is. +:returns: True on success, false on IO errors, pb_encode errors or if submessage size changes between calls. + +In Protocol Buffers format, the submessage size must be written before the submessage contents. Therefore, this function has to encode the submessage twice in order to know the size beforehand. + +If the submessage contains callback fields, the callback function might misbehave and write out a different amount of data on the second call. This situation is recognized and *false* is returned, but garbage will be written to the output before the problem is detected. + + + + + + + + + + + + +pb_decode.h +=========== + +pb_istream_from_buffer +---------------------- +Helper function for creating an input stream that reads data from a memory buffer. :: + + pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize); + +:buf: Pointer to byte array to read from. +:bufsize: Size of the byte array. +:returns: An input stream ready to use. + +pb_read +------- +Read data from input stream. Always use this function, don't try to call the stream callback directly. :: + + bool pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count); + +:stream: Input stream to read from. +:buf: Buffer to store the data to, or NULL to just read data without storing it anywhere. +:count: Number of bytes to read. +:returns: True on success, false if *stream->bytes_left* is less than *count* or if an IO error occurs. + +End of file is signalled by *stream->bytes_left* being zero after pb_read returns false. + +pb_decode +--------- +Read and decode all fields of a structure. Reads until EOF on input stream. :: + + bool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +:stream: Input stream to read from. +:fields: A field description array. Usually autogenerated. +:dest_struct: Pointer to structure where data will be stored. +:returns: True on success, false on IO error, on detectable errors in field description, if a field encoder returns false or if a required field is missing. + +In Protocol Buffers binary format, EOF is only allowed between fields. If it happens anywhere else, pb_decode will return *false*. If pb_decode returns false, you cannot trust any of the data in the structure. + +In addition to EOF, the pb_decode implementation supports terminating a message with a 0 byte. This is compatible with the official Protocol Buffers because 0 is never a valid field tag. + +For optional fields, this function applies the default value and sets *has_* to false if the field is not present. + +If *PB_ENABLE_MALLOC* is defined, this function may allocate storage for any pointer type fields. +In this case, you have to call `pb_release`_ to release the memory after you are done with the message. +On error return `pb_decode` will release the memory itself. + +pb_decode_noinit +---------------- +Same as `pb_decode`_, except does not apply the default values to fields. :: + + bool pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +(parameters are the same as for `pb_decode`_.) + +The destination structure should be filled with zeros before calling this function. Doing a *memset* manually can be slightly faster than using `pb_decode`_ if you don't need any default values. + +In addition to decoding a single message, this function can be used to merge two messages, so that +values from previous message will remain if the new message does not contain a field. + +This function *will not* release the message even on error return. If you use *PB_ENABLE_MALLOC*, +you will need to call `pb_release`_ yourself. + +pb_decode_delimited +------------------- +Same as `pb_decode`_, except that it first reads a varint with the length of the message. :: + + bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +(parameters are the same as for `pb_decode`_.) + +A common method to indicate message size in Protocol Buffers is to prefix it with a varint. +This function is compatible with *writeDelimitedTo* in the Google's Protocol Buffers library. + +pb_release +---------- +Releases any dynamically allocated fields:: + + void pb_release(const pb_field_t fields[], void *dest_struct); + +:fields: A field description array. Usually autogenerated. +:dest_struct: Pointer to structure where data is stored. If NULL, function does nothing. + +This function is only available if *PB_ENABLE_MALLOC* is defined. It will release any +pointer type fields in the structure and set the pointers to NULL. + +pb_decode_tag +------------- +Decode the tag that comes before field in the protobuf encoding:: + + bool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof); + +:stream: Input stream to read from. +:wire_type: Pointer to variable where to store the wire type of the field. +:tag: Pointer to variable where to store the tag of the field. +:eof: Pointer to variable where to store end-of-file status. +:returns: True on success, false on error or EOF. + +When the message (stream) ends, this function will return false and set *eof* to true. On other +errors, *eof* will be set to false. + +pb_skip_field +------------- +Remove the data for a field from the stream, without actually decoding it:: + + bool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type); + +:stream: Input stream to read from. +:wire_type: Type of field to skip. +:returns: True on success, false on IO error. + +.. sidebar:: Decoding fields manually + + The functions with names beginning with *pb_decode_* are used when dealing with callback fields. The typical reason for using callbacks is to have an array of unlimited size. In that case, `pb_decode`_ will call your callback function repeatedly, which can then store the values into e.g. filesystem in the order received in. + + For decoding numeric (including enumerated and boolean) values, use `pb_decode_varint`_, `pb_decode_svarint`_, `pb_decode_fixed32`_ and `pb_decode_fixed64`_. They take a pointer to a 32- or 64-bit C variable, which you may then cast to smaller datatype for storage. + + For decoding strings and bytes fields, the length has already been decoded. You can therefore check the total length in *stream->bytes_left* and read the data using `pb_read`_. + + Finally, for decoding submessages in a callback, simply use `pb_decode`_ and pass it the *SubMessage_fields* descriptor array. + +pb_decode_varint +---------------- +Read and decode a varint_ encoded integer. :: + + bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest); + +:stream: Input stream to read from. 1-10 bytes will be read. +:dest: Storage for the decoded integer. Value is undefined on error. +:returns: True on success, false if value exceeds uint64_t range or an IO error happens. + +pb_decode_svarint +----------------- +Similar to `pb_decode_varint`_, except that it performs zigzag-decoding on the value. This corresponds to the Protocol Buffers *sint32* and *sint64* datatypes. :: + + bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest); + +(parameters are the same as `pb_decode_varint`_) + +pb_decode_fixed32 +----------------- +Decode a *fixed32*, *sfixed32* or *float* value. :: + + bool pb_decode_fixed32(pb_istream_t *stream, void *dest); + +:stream: Input stream to read from. 4 bytes will be read. +:dest: Pointer to destination *int32_t*, *uint32_t* or *float*. +:returns: True on success, false on IO errors. + +This function reads 4 bytes from the input stream. +On big endian architectures, it then reverses the order of the bytes. +Finally, it writes the bytes to *dest*. + +pb_decode_fixed64 +----------------- +Decode a *fixed64*, *sfixed64* or *double* value. :: + + bool pb_decode_fixed64(pb_istream_t *stream, void *dest); + +:stream: Input stream to read from. 8 bytes will be read. +:dest: Pointer to destination *int64_t*, *uint64_t* or *double*. +:returns: True on success, false on IO errors. + +Same as `pb_decode_fixed32`_, except this reads 8 bytes. + +pb_make_string_substream +------------------------ +Decode the length for a field with wire type *PB_WT_STRING* and create a substream for reading the data. :: + + bool pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream); + +:stream: Original input stream to read the length and data from. +:substream: New substream that has limited length. Filled in by the function. +:returns: True on success, false if reading the length fails. + +This function uses `pb_decode_varint`_ to read an integer from the stream. This is interpreted as a number of bytes, and the substream is set up so that its `bytes_left` is initially the same as the length, and its callback function and state the same as the parent stream. + +pb_close_string_substream +------------------------- +Close the substream created with `pb_make_string_substream`_. :: + + void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream); + +:stream: Original input stream to read the length and data from. +:substream: Substream to close + +This function copies back the state from the substream to the parent stream. +It must be called after done with the substream. diff --git a/libs/nanopb/docs/security.rst b/libs/nanopb/docs/security.rst new file mode 100644 index 00000000..d8546122 --- /dev/null +++ b/libs/nanopb/docs/security.rst @@ -0,0 +1,84 @@ +====================== +Nanopb: Security model +====================== + +.. include :: menu.rst + +.. contents :: + + + +Importance of security in a Protocol Buffers library +==================================================== +In the context of protocol buffers, security comes into play when decoding +untrusted data. Naturally, if the attacker can modify the contents of a +protocol buffers message, he can feed the application any values possible. +Therefore the application itself must be prepared to receive untrusted values. + +Where nanopb plays a part is preventing the attacker from running arbitrary +code on the target system. Mostly this means that there must not be any +possibility to cause buffer overruns, memory corruption or invalid pointers +by the means of crafting a malicious message. + +Division of trusted and untrusted data +====================================== +The following data is regarded as **trusted**. It must be under the control of +the application writer. Malicious data in these structures could cause +security issues, such as execution of arbitrary code: + +1. Callback, pointer and extension fields in message structures given to + pb_encode() and pb_decode(). These fields are memory pointers, and are + generated depending on the message definition in the .proto file. +2. The automatically generated field definitions, i.e. *pb_field_t* lists. +3. Contents of the *pb_istream_t* and *pb_ostream_t* structures (this does not + mean the contents of the stream itself, just the stream definition). + +The following data is regarded as **untrusted**. Invalid/malicious data in +these will cause "garbage in, garbage out" behaviour. It will not cause +buffer overflows, information disclosure or other security problems: + +1. All data read from *pb_istream_t*. +2. All fields in message structures, except: + + - callbacks (*pb_callback_t* structures) + - pointer fields (malloc support) and *_count* fields for pointers + - extensions (*pb_extension_t* structures) + +Invariants +========== +The following invariants are maintained during operation, even if the +untrusted data has been maliciously crafted: + +1. Nanopb will never read more than *bytes_left* bytes from *pb_istream_t*. +2. Nanopb will never write more than *max_size* bytes to *pb_ostream_t*. +3. Nanopb will never access memory out of bounds of the message structure. +4. After pb_decode() returns successfully, the message structure will be + internally consistent: + + - The *count* fields of arrays will not exceed the array size. + - The *size* field of bytes will not exceed the allocated size. + - All string fields will have null terminator. + +5. After pb_encode() returns successfully, the resulting message is a valid + protocol buffers message. (Except if user-defined callbacks write incorrect + data.) + +Further considerations +====================== +Even if the nanopb library is free of any security issues, there are still +several possible attack vectors that the application author must consider. +The following list is not comprehensive: + +1. Stack usage may depend on the contents of the message. The message + definition places an upper bound on how much stack will be used. Tests + should be run with all fields present, to record the maximum possible + stack usage. +2. Callbacks can do anything. The code for the callbacks must be carefully + checked if they are used with untrusted data. +3. If using stream input, a maximum size should be set in *pb_istream_t* to + stop a denial of service attack from using an infinite message. +4. If using network sockets as streams, a timeout should be set to stop + denial of service attacks. +5. If using *malloc()* support, some method of limiting memory use should be + employed. This can be done by defining custom *pb_realloc()* function. + Nanopb will properly detect and handle failed memory allocations. diff --git a/libs/nanopb/examples/cmake_simple/CMakeLists.txt b/libs/nanopb/examples/cmake_simple/CMakeLists.txt new file mode 100644 index 00000000..e5f33a02 --- /dev/null +++ b/libs/nanopb/examples/cmake_simple/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 2.8) +project(NANOPB_CMAKE_SIMPLE C) + +set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../extra) +find_package(Nanopb REQUIRED) +include_directories(${NANOPB_INCLUDE_DIRS}) + +nanopb_generate_cpp(PROTO_SRCS PROTO_HDRS simple.proto) +include_directories(${CMAKE_CURRENT_BINARY_DIR}) +#add_custom_target(generate_proto_sources DEPENDS ${PROTO_SRCS} ${PROTO_HDRS}) +set_source_files_properties(${PROTO_SRCS} ${PROTO_HDRS} + PROPERTIES GENERATED TRUE) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Werror -g -O0") + +add_executable(simple simple.c ${PROTO_SRCS} ${PROTO_HDRS}) diff --git a/libs/nanopb/examples/cmake_simple/README.txt b/libs/nanopb/examples/cmake_simple/README.txt new file mode 100644 index 00000000..aa0f3f3a --- /dev/null +++ b/libs/nanopb/examples/cmake_simple/README.txt @@ -0,0 +1,18 @@ +Nanopb example "simple" using CMake +======================= + +This example is the same as the simple nanopb example but built using CMake. + +Example usage +------------- + +On Linux, create a build directory and then call cmake: + + nanopb/examples/cmake_simple$ mkdir build + nanopb/examples/cmake_simple$ cd build/ + nanopb/examples/cmake_simple/build$ cmake .. + nanopb/examples/cmake_simple/build$ make + +After that, you can run it with the command: ./simple + +On other platforms supported by CMake, refer to CMake instructions. diff --git a/libs/nanopb/examples/cmake_simple/simple.c b/libs/nanopb/examples/cmake_simple/simple.c new file mode 100644 index 00000000..1f6b1373 --- /dev/null +++ b/libs/nanopb/examples/cmake_simple/simple.c @@ -0,0 +1,71 @@ +#include +#include +#include +#include "simple.pb.h" + +int main() +{ + /* This is the buffer where we will store our message. */ + uint8_t buffer[128]; + size_t message_length; + bool status; + + /* Encode our message */ + { + /* Allocate space on the stack to store the message data. + * + * Nanopb generates simple struct definitions for all the messages. + * - check out the contents of simple.pb.h! + * It is a good idea to always initialize your structures + * so that you do not have garbage data from RAM in there. + */ + SimpleMessage message = SimpleMessage_init_zero; + + /* Create a stream that will write to our buffer. */ + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Fill in the lucky number */ + message.lucky_number = 13; + + /* Now we are ready to encode the message! */ + status = pb_encode(&stream, SimpleMessage_fields, &message); + message_length = stream.bytes_written; + + /* Then just check for any errors.. */ + if (!status) + { + printf("Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } + } + + /* Now we could transmit the message over network, store it in a file or + * wrap it to a pigeon's leg. + */ + + /* But because we are lazy, we will just decode it immediately. */ + + { + /* Allocate space for the decoded message. */ + SimpleMessage message = SimpleMessage_init_zero; + + /* Create a stream that reads from the buffer. */ + pb_istream_t stream = pb_istream_from_buffer(buffer, message_length); + + /* Now we are ready to decode the message. */ + status = pb_decode(&stream, SimpleMessage_fields, &message); + + /* Check for errors... */ + if (!status) + { + printf("Decoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } + + /* Print the data contained in the message. */ + printf("Your lucky number was %d!\n", message.lucky_number); + } + + return 0; +} + diff --git a/libs/nanopb/examples/cmake_simple/simple.proto b/libs/nanopb/examples/cmake_simple/simple.proto new file mode 100644 index 00000000..5c73a3b2 --- /dev/null +++ b/libs/nanopb/examples/cmake_simple/simple.proto @@ -0,0 +1,9 @@ +// A very simple protocol definition, consisting of only +// one message. + +syntax = "proto2"; + +message SimpleMessage { + required int32 lucky_number = 1; +} + diff --git a/libs/nanopb/examples/network_server/Makefile b/libs/nanopb/examples/network_server/Makefile new file mode 100644 index 00000000..2c7639a1 --- /dev/null +++ b/libs/nanopb/examples/network_server/Makefile @@ -0,0 +1,17 @@ +# Include the nanopb provided Makefile rules +include ../../extra/nanopb.mk + +# Compiler flags to enable all warnings & debug info +CFLAGS = -ansi -Wall -Werror -g -O0 +CFLAGS += -I$(NANOPB_DIR) + +all: server client + +.SUFFIXES: + +clean: + rm -f server client fileproto.pb.c fileproto.pb.h + +%: %.c common.c fileproto.pb.c + $(CC) $(CFLAGS) -o $@ $^ $(NANOPB_CORE) + diff --git a/libs/nanopb/examples/network_server/README.txt b/libs/nanopb/examples/network_server/README.txt new file mode 100644 index 00000000..7bdcbed5 --- /dev/null +++ b/libs/nanopb/examples/network_server/README.txt @@ -0,0 +1,60 @@ +Nanopb example "network_server" +=============================== + +This example demonstrates the use of nanopb to communicate over network +connections. It consists of a server that sends file listings, and of +a client that requests the file list from the server. + +Example usage +------------- + +user@host:~/nanopb/examples/network_server$ make # Build the example +protoc -ofileproto.pb fileproto.proto +python ../../generator/nanopb_generator.py fileproto.pb +Writing to fileproto.pb.h and fileproto.pb.c +cc -ansi -Wall -Werror -I .. -g -O0 -I../.. -o server server.c + ../../pb_decode.c ../../pb_encode.c fileproto.pb.c common.c +cc -ansi -Wall -Werror -I .. -g -O0 -I../.. -o client client.c + ../../pb_decode.c ../../pb_encode.c fileproto.pb.c common.c + +user@host:~/nanopb/examples/network_server$ ./server & # Start the server on background +[1] 24462 + +petteri@oddish:~/nanopb/examples/network_server$ ./client /bin # Request the server to list /bin +Got connection. +Listing directory: /bin +1327119 bzdiff +1327126 bzless +1327147 ps +1327178 ntfsmove +1327271 mv +1327187 mount +1327259 false +1327266 tempfile +1327285 zfgrep +1327165 gzexe +1327204 nc.openbsd +1327260 uname + + +Details of implementation +------------------------- +fileproto.proto contains the portable Google Protocol Buffers protocol definition. +It could be used as-is to implement a server or a client in any other language, for +example Python or Java. + +fileproto.options contains the nanopb-specific options for the protocol file. This +sets the amount of space allocated for file names when decoding messages. + +common.c/h contains functions that allow nanopb to read and write directly from +network socket. This way there is no need to allocate a separate buffer to store +the message. + +server.c contains the code to open a listening socket, to respond to clients and +to list directory contents. + +client.c contains the code to connect to a server, to send a request and to print +the response message. + +The code is implemented using the POSIX socket api, but it should be easy enough +to port into any other socket api, such as lwip. diff --git a/libs/nanopb/examples/network_server/client.c b/libs/nanopb/examples/network_server/client.c new file mode 100644 index 00000000..00f6dab8 --- /dev/null +++ b/libs/nanopb/examples/network_server/client.c @@ -0,0 +1,142 @@ +/* This is a simple TCP client that connects to port 1234 and prints a list + * of files in a given directory. + * + * It directly deserializes and serializes messages from network, minimizing + * memory use. + * + * For flexibility, this example is implemented using posix api. + * In a real embedded system you would typically use some other kind of + * a communication and filesystem layer. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "fileproto.pb.h" +#include "common.h" + +/* This callback function will be called once for each filename received + * from the server. The filenames will be printed out immediately, so that + * no memory has to be allocated for them. + */ +bool printfile_callback(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + FileInfo fileinfo = {}; + + if (!pb_decode(stream, FileInfo_fields, &fileinfo)) + return false; + + printf("%-10lld %s\n", (long long)fileinfo.inode, fileinfo.name); + + return true; +} + +/* This function sends a request to socket 'fd' to list the files in + * directory given in 'path'. The results received from server will + * be printed to stdout. + */ +bool listdir(int fd, char *path) +{ + /* Construct and send the request to server */ + { + ListFilesRequest request = {}; + pb_ostream_t output = pb_ostream_from_socket(fd); + uint8_t zero = 0; + + /* In our protocol, path is optional. If it is not given, + * the server will list the root directory. */ + if (path == NULL) + { + request.has_path = false; + } + else + { + request.has_path = true; + if (strlen(path) + 1 > sizeof(request.path)) + { + fprintf(stderr, "Too long path.\n"); + return false; + } + + strcpy(request.path, path); + } + + /* Encode the request. It is written to the socket immediately + * through our custom stream. */ + if (!pb_encode(&output, ListFilesRequest_fields, &request)) + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&output)); + return false; + } + + /* We signal the end of request with a 0 tag. */ + pb_write(&output, &zero, 1); + } + + /* Read back the response from server */ + { + ListFilesResponse response = {}; + pb_istream_t input = pb_istream_from_socket(fd); + + /* Give a pointer to our callback function, which will handle the + * filenames as they arrive. */ + response.file.funcs.decode = &printfile_callback; + + if (!pb_decode(&input, ListFilesResponse_fields, &response)) + { + fprintf(stderr, "Decode failed: %s\n", PB_GET_ERROR(&input)); + return false; + } + + /* If the message from server decodes properly, but directory was + * not found on server side, we get path_error == true. */ + if (response.path_error) + { + fprintf(stderr, "Server reported error.\n"); + return false; + } + } + + return true; +} + +int main(int argc, char **argv) +{ + int sockfd; + struct sockaddr_in servaddr; + char *path = NULL; + + if (argc > 1) + path = argv[1]; + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + + /* Connect to server running on localhost:1234 */ + memset(&servaddr, 0, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + servaddr.sin_port = htons(1234); + + if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0) + { + perror("connect"); + return 1; + } + + /* Send the directory listing request */ + if (!listdir(sockfd, path)) + return 2; + + /* Close connection */ + close(sockfd); + + return 0; +} diff --git a/libs/nanopb/examples/network_server/common.c b/libs/nanopb/examples/network_server/common.c new file mode 100644 index 00000000..04a5aa85 --- /dev/null +++ b/libs/nanopb/examples/network_server/common.c @@ -0,0 +1,40 @@ +/* Simple binding of nanopb streams to TCP sockets. + */ + +#include +#include +#include +#include + +#include "common.h" + +static bool write_callback(pb_ostream_t *stream, const uint8_t *buf, size_t count) +{ + int fd = (intptr_t)stream->state; + return send(fd, buf, count, 0) == count; +} + +static bool read_callback(pb_istream_t *stream, uint8_t *buf, size_t count) +{ + int fd = (intptr_t)stream->state; + int result; + + result = recv(fd, buf, count, MSG_WAITALL); + + if (result == 0) + stream->bytes_left = 0; /* EOF */ + + return result == count; +} + +pb_ostream_t pb_ostream_from_socket(int fd) +{ + pb_ostream_t stream = {&write_callback, (void*)(intptr_t)fd, SIZE_MAX, 0}; + return stream; +} + +pb_istream_t pb_istream_from_socket(int fd) +{ + pb_istream_t stream = {&read_callback, (void*)(intptr_t)fd, SIZE_MAX}; + return stream; +} diff --git a/libs/nanopb/examples/network_server/common.h b/libs/nanopb/examples/network_server/common.h new file mode 100644 index 00000000..8dab3b7c --- /dev/null +++ b/libs/nanopb/examples/network_server/common.h @@ -0,0 +1,9 @@ +#ifndef _PB_EXAMPLE_COMMON_H_ +#define _PB_EXAMPLE_COMMON_H_ + +#include + +pb_ostream_t pb_ostream_from_socket(int fd); +pb_istream_t pb_istream_from_socket(int fd); + +#endif \ No newline at end of file diff --git a/libs/nanopb/examples/network_server/fileproto.options b/libs/nanopb/examples/network_server/fileproto.options new file mode 100644 index 00000000..29a2ab0e --- /dev/null +++ b/libs/nanopb/examples/network_server/fileproto.options @@ -0,0 +1,13 @@ +# This file defines the nanopb-specific options for the messages defined +# in fileproto.proto. +# +# If you come from high-level programming background, the hardcoded +# maximum lengths may disgust you. However, if your microcontroller only +# has a few kB of ram to begin with, setting reasonable limits for +# filenames is ok. +# +# On the other hand, using the callback interface, it is not necessary +# to set a limit on the number of files in the response. + +ListFilesRequest.path max_size:128 +FileInfo.name max_size:128 diff --git a/libs/nanopb/examples/network_server/fileproto.proto b/libs/nanopb/examples/network_server/fileproto.proto new file mode 100644 index 00000000..5640b8d5 --- /dev/null +++ b/libs/nanopb/examples/network_server/fileproto.proto @@ -0,0 +1,20 @@ +// This defines protocol for a simple server that lists files. +// +// See also the nanopb-specific options in fileproto.options. + +syntax = "proto2"; + +message ListFilesRequest { + optional string path = 1 [default = "/"]; +} + +message FileInfo { + required uint64 inode = 1; + required string name = 2; +} + +message ListFilesResponse { + optional bool path_error = 1 [default = false]; + repeated FileInfo file = 2; +} + diff --git a/libs/nanopb/examples/network_server/server.c b/libs/nanopb/examples/network_server/server.c new file mode 100644 index 00000000..46a5f38d --- /dev/null +++ b/libs/nanopb/examples/network_server/server.c @@ -0,0 +1,158 @@ +/* This is a simple TCP server that listens on port 1234 and provides lists + * of files to clients, using a protocol defined in file_server.proto. + * + * It directly deserializes and serializes messages from network, minimizing + * memory use. + * + * For flexibility, this example is implemented using posix api. + * In a real embedded system you would typically use some other kind of + * a communication and filesystem layer. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "fileproto.pb.h" +#include "common.h" + +/* This callback function will be called once during the encoding. + * It will write out any number of FileInfo entries, without consuming unnecessary memory. + * This is accomplished by fetching the filenames one at a time and encoding them + * immediately. + */ +bool listdir_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + DIR *dir = (DIR*) *arg; + struct dirent *file; + FileInfo fileinfo = {}; + + while ((file = readdir(dir)) != NULL) + { + fileinfo.inode = file->d_ino; + strncpy(fileinfo.name, file->d_name, sizeof(fileinfo.name)); + fileinfo.name[sizeof(fileinfo.name) - 1] = '\0'; + + /* This encodes the header for the field, based on the constant info + * from pb_field_t. */ + if (!pb_encode_tag_for_field(stream, field)) + return false; + + /* This encodes the data for the field, based on our FileInfo structure. */ + if (!pb_encode_submessage(stream, FileInfo_fields, &fileinfo)) + return false; + } + + return true; +} + +/* Handle one arriving client connection. + * Clients are expected to send a ListFilesRequest, terminated by a '0'. + * Server will respond with a ListFilesResponse message. + */ +void handle_connection(int connfd) +{ + DIR *directory = NULL; + + /* Decode the message from the client and open the requested directory. */ + { + ListFilesRequest request = {}; + pb_istream_t input = pb_istream_from_socket(connfd); + + if (!pb_decode(&input, ListFilesRequest_fields, &request)) + { + printf("Decode failed: %s\n", PB_GET_ERROR(&input)); + return; + } + + directory = opendir(request.path); + printf("Listing directory: %s\n", request.path); + } + + /* List the files in the directory and transmit the response to client */ + { + ListFilesResponse response = {}; + pb_ostream_t output = pb_ostream_from_socket(connfd); + + if (directory == NULL) + { + perror("opendir"); + + /* Directory was not found, transmit error status */ + response.has_path_error = true; + response.path_error = true; + response.file.funcs.encode = NULL; + } + else + { + /* Directory was found, transmit filenames */ + response.has_path_error = false; + response.file.funcs.encode = &listdir_callback; + response.file.arg = directory; + } + + if (!pb_encode(&output, ListFilesResponse_fields, &response)) + { + printf("Encoding failed: %s\n", PB_GET_ERROR(&output)); + } + } + + if (directory != NULL) + closedir(directory); +} + +int main(int argc, char **argv) +{ + int listenfd, connfd; + struct sockaddr_in servaddr; + int reuse = 1; + + /* Listen on localhost:1234 for TCP connections */ + listenfd = socket(AF_INET, SOCK_STREAM, 0); + setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); + + memset(&servaddr, 0, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + servaddr.sin_port = htons(1234); + if (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0) + { + perror("bind"); + return 1; + } + + if (listen(listenfd, 5) != 0) + { + perror("listen"); + return 1; + } + + for(;;) + { + /* Wait for a client */ + connfd = accept(listenfd, NULL, NULL); + + if (connfd < 0) + { + perror("accept"); + return 1; + } + + printf("Got connection.\n"); + + handle_connection(connfd); + + printf("Closing connection.\n"); + + close(connfd); + } + + return 0; +} diff --git a/libs/nanopb/examples/simple/Makefile b/libs/nanopb/examples/simple/Makefile new file mode 100644 index 00000000..970a8650 --- /dev/null +++ b/libs/nanopb/examples/simple/Makefile @@ -0,0 +1,22 @@ +# Include the nanopb provided Makefile rules +include ../../extra/nanopb.mk + +# Compiler flags to enable all warnings & debug info +CFLAGS = -Wall -Werror -g -O0 +CFLAGS += -I$(NANOPB_DIR) + +# C source code files that are required +CSRC = simple.c # The main program +CSRC += simple.pb.c # The compiled protocol definition +CSRC += $(NANOPB_DIR)/pb_encode.c # The nanopb encoder +CSRC += $(NANOPB_DIR)/pb_decode.c # The nanopb decoder +CSRC += $(NANOPB_DIR)/pb_common.c # The nanopb common parts + +# Build rule for the main program +simple: $(CSRC) + $(CC) $(CFLAGS) -osimple $(CSRC) + +# Build rule for the protocol +simple.pb.c: simple.proto + $(PROTOC) $(PROTOC_OPTS) --nanopb_out=. simple.proto + diff --git a/libs/nanopb/examples/simple/README.txt b/libs/nanopb/examples/simple/README.txt new file mode 100644 index 00000000..ee77bfc7 --- /dev/null +++ b/libs/nanopb/examples/simple/README.txt @@ -0,0 +1,29 @@ +Nanopb example "simple" +======================= + +This example demonstrates the very basic use of nanopb. It encodes and +decodes a simple message. + +The code uses four different API functions: + + * pb_ostream_from_buffer() to declare the output buffer that is to be used + * pb_encode() to encode a message + * pb_istream_from_buffer() to declare the input buffer that is to be used + * pb_decode() to decode a message + +Example usage +------------- + +On Linux, simply type "make" to build the example. After that, you can +run it with the command: ./simple + +On other platforms, you first have to compile the protocol definition using +the following command:: + + ../../generator-bin/protoc --nanopb_out=. simple.proto + +After that, add the following four files to your project and compile: + + simple.c simple.pb.c pb_encode.c pb_decode.c + + diff --git a/libs/nanopb/examples/simple/simple.c b/libs/nanopb/examples/simple/simple.c new file mode 100644 index 00000000..1f6b1373 --- /dev/null +++ b/libs/nanopb/examples/simple/simple.c @@ -0,0 +1,71 @@ +#include +#include +#include +#include "simple.pb.h" + +int main() +{ + /* This is the buffer where we will store our message. */ + uint8_t buffer[128]; + size_t message_length; + bool status; + + /* Encode our message */ + { + /* Allocate space on the stack to store the message data. + * + * Nanopb generates simple struct definitions for all the messages. + * - check out the contents of simple.pb.h! + * It is a good idea to always initialize your structures + * so that you do not have garbage data from RAM in there. + */ + SimpleMessage message = SimpleMessage_init_zero; + + /* Create a stream that will write to our buffer. */ + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Fill in the lucky number */ + message.lucky_number = 13; + + /* Now we are ready to encode the message! */ + status = pb_encode(&stream, SimpleMessage_fields, &message); + message_length = stream.bytes_written; + + /* Then just check for any errors.. */ + if (!status) + { + printf("Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } + } + + /* Now we could transmit the message over network, store it in a file or + * wrap it to a pigeon's leg. + */ + + /* But because we are lazy, we will just decode it immediately. */ + + { + /* Allocate space for the decoded message. */ + SimpleMessage message = SimpleMessage_init_zero; + + /* Create a stream that reads from the buffer. */ + pb_istream_t stream = pb_istream_from_buffer(buffer, message_length); + + /* Now we are ready to decode the message. */ + status = pb_decode(&stream, SimpleMessage_fields, &message); + + /* Check for errors... */ + if (!status) + { + printf("Decoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } + + /* Print the data contained in the message. */ + printf("Your lucky number was %d!\n", message.lucky_number); + } + + return 0; +} + diff --git a/libs/nanopb/examples/simple/simple.proto b/libs/nanopb/examples/simple/simple.proto new file mode 100644 index 00000000..5c73a3b2 --- /dev/null +++ b/libs/nanopb/examples/simple/simple.proto @@ -0,0 +1,9 @@ +// A very simple protocol definition, consisting of only +// one message. + +syntax = "proto2"; + +message SimpleMessage { + required int32 lucky_number = 1; +} + diff --git a/libs/nanopb/examples/using_double_on_avr/Makefile b/libs/nanopb/examples/using_double_on_avr/Makefile new file mode 100644 index 00000000..874a64bd --- /dev/null +++ b/libs/nanopb/examples/using_double_on_avr/Makefile @@ -0,0 +1,24 @@ +# Include the nanopb provided Makefile rules +include ../../extra/nanopb.mk + +# Compiler flags to enable all warnings & debug info +CFLAGS = -Wall -Werror -g -O0 +CFLAGS += -I$(NANOPB_DIR) + +all: run_tests + +.SUFFIXES: + +clean: + rm -f test_conversions encode_double decode_double doubleproto.pb.c doubleproto.pb.h + +test_conversions: test_conversions.c double_conversion.c + $(CC) $(CFLAGS) -o $@ $^ + +%: %.c double_conversion.c doubleproto.pb.c + $(CC) $(CFLAGS) -o $@ $^ $(NANOPB_CORE) + +run_tests: test_conversions encode_double decode_double + ./test_conversions + ./encode_double | ./decode_double + diff --git a/libs/nanopb/examples/using_double_on_avr/README.txt b/libs/nanopb/examples/using_double_on_avr/README.txt new file mode 100644 index 00000000..d9fcdfc6 --- /dev/null +++ b/libs/nanopb/examples/using_double_on_avr/README.txt @@ -0,0 +1,25 @@ +Nanopb example "using_double_on_avr" +==================================== + +Some processors/compilers, such as AVR-GCC, do not support the double +datatype. Instead, they have sizeof(double) == 4. Because protocol +binary format uses the double encoding directly, this causes trouble +if the protocol in .proto requires double fields. + +This directory contains a solution to this problem. It uses uint64_t +to store the raw wire values, because its size is correct on all +platforms. The file double_conversion.c provides functions that +convert these values to/from floats, without relying on compiler +support. + +To use this method, you need to make some modifications to your code: + +1) Change all 'double' fields into 'fixed64' in the .proto. + +2) Whenever writing to a 'double' field, use float_to_double(). + +3) Whenever reading a 'double' field, use double_to_float(). + +The conversion routines are as accurate as the float datatype can +be. Furthermore, they should handle all special values (NaN, inf, denormalized +numbers) correctly. There are testcases in test_conversions.c. diff --git a/libs/nanopb/examples/using_double_on_avr/decode_double.c b/libs/nanopb/examples/using_double_on_avr/decode_double.c new file mode 100644 index 00000000..5802eca7 --- /dev/null +++ b/libs/nanopb/examples/using_double_on_avr/decode_double.c @@ -0,0 +1,33 @@ +/* Decodes a double value into a float variable. + * Used to read double values with AVR code, which doesn't support double directly. + */ + +#include +#include +#include "double_conversion.h" +#include "doubleproto.pb.h" + +int main() +{ + uint8_t buffer[32]; + size_t count = fread(buffer, 1, sizeof(buffer), stdin); + pb_istream_t stream = pb_istream_from_buffer(buffer, count); + + AVRDoubleMessage message; + pb_decode(&stream, AVRDoubleMessage_fields, &message); + + float v1 = double_to_float(message.field1); + float v2 = double_to_float(message.field2); + + printf("Values: %f %f\n", v1, v2); + + if (v1 == 1234.5678f && + v2 == 0.00001f) + { + return 0; + } + else + { + return 1; + } +} diff --git a/libs/nanopb/examples/using_double_on_avr/double_conversion.c b/libs/nanopb/examples/using_double_on_avr/double_conversion.c new file mode 100644 index 00000000..cf79b9a0 --- /dev/null +++ b/libs/nanopb/examples/using_double_on_avr/double_conversion.c @@ -0,0 +1,123 @@ +/* Conversion routines for platforms that do not support 'double' directly. */ + +#include "double_conversion.h" +#include + +typedef union { + float f; + uint32_t i; +} conversion_t; + +/* Note: IEE 754 standard specifies float formats as follows: + * Single precision: sign, 8-bit exp, 23-bit frac. + * Double precision: sign, 11-bit exp, 52-bit frac. + */ + +uint64_t float_to_double(float value) +{ + conversion_t in; + in.f = value; + uint8_t sign; + int16_t exponent; + uint64_t mantissa; + + /* Decompose input value */ + sign = (in.i >> 31) & 1; + exponent = ((in.i >> 23) & 0xFF) - 127; + mantissa = in.i & 0x7FFFFF; + + if (exponent == 128) + { + /* Special value (NaN etc.) */ + exponent = 1024; + } + else if (exponent == -127) + { + if (!mantissa) + { + /* Zero */ + exponent = -1023; + } + else + { + /* Denormalized */ + mantissa <<= 1; + while (!(mantissa & 0x800000)) + { + mantissa <<= 1; + exponent--; + } + mantissa &= 0x7FFFFF; + } + } + + /* Combine fields */ + mantissa <<= 29; + mantissa |= (uint64_t)(exponent + 1023) << 52; + mantissa |= (uint64_t)sign << 63; + + return mantissa; +} + +float double_to_float(uint64_t value) +{ + uint8_t sign; + int16_t exponent; + uint32_t mantissa; + conversion_t out; + + /* Decompose input value */ + sign = (value >> 63) & 1; + exponent = ((value >> 52) & 0x7FF) - 1023; + mantissa = (value >> 28) & 0xFFFFFF; /* Highest 24 bits */ + + /* Figure if value is in range representable by floats. */ + if (exponent == 1024) + { + /* Special value */ + exponent = 128; + } + else if (exponent > 127) + { + /* Too large */ + if (sign) + return -INFINITY; + else + return INFINITY; + } + else if (exponent < -150) + { + /* Too small */ + if (sign) + return -0.0f; + else + return 0.0f; + } + else if (exponent < -126) + { + /* Denormalized */ + mantissa |= 0x1000000; + mantissa >>= (-126 - exponent); + exponent = -127; + } + + /* Round off mantissa */ + mantissa = (mantissa + 1) >> 1; + + /* Check if mantissa went over 2.0 */ + if (mantissa & 0x800000) + { + exponent += 1; + mantissa &= 0x7FFFFF; + mantissa >>= 1; + } + + /* Combine fields */ + out.i = mantissa; + out.i |= (uint32_t)(exponent + 127) << 23; + out.i |= (uint32_t)sign << 31; + + return out.f; +} + + diff --git a/libs/nanopb/examples/using_double_on_avr/double_conversion.h b/libs/nanopb/examples/using_double_on_avr/double_conversion.h new file mode 100644 index 00000000..62b6a8ae --- /dev/null +++ b/libs/nanopb/examples/using_double_on_avr/double_conversion.h @@ -0,0 +1,26 @@ +/* AVR-GCC does not have real double datatype. Instead its double + * is equal to float, i.e. 32 bit value. If you need to communicate + * with other systems that use double in their .proto files, you + * need to do some conversion. + * + * These functions use bitwise operations to mangle floats into doubles + * and then store them in uint64_t datatype. + */ + +#ifndef DOUBLE_CONVERSION +#define DOUBLE_CONVERSION + +#include + +/* Convert native 4-byte float into a 8-byte double. */ +extern uint64_t float_to_double(float value); + +/* Convert 8-byte double into native 4-byte float. + * Values are rounded to nearest, 0.5 away from zero. + * Overflowing values are converted to Inf or -Inf. + */ +extern float double_to_float(uint64_t value); + + +#endif + diff --git a/libs/nanopb/examples/using_double_on_avr/doubleproto.proto b/libs/nanopb/examples/using_double_on_avr/doubleproto.proto new file mode 100644 index 00000000..72d3f9c1 --- /dev/null +++ b/libs/nanopb/examples/using_double_on_avr/doubleproto.proto @@ -0,0 +1,15 @@ +// A message containing doubles, as used by other applications. +syntax = "proto2"; + +message DoubleMessage { + required double field1 = 1; + required double field2 = 2; +} + +// A message containing doubles, but redefined using uint64_t. +// For use in AVR code. +message AVRDoubleMessage { + required fixed64 field1 = 1; + required fixed64 field2 = 2; +} + diff --git a/libs/nanopb/examples/using_double_on_avr/encode_double.c b/libs/nanopb/examples/using_double_on_avr/encode_double.c new file mode 100644 index 00000000..cd532d46 --- /dev/null +++ b/libs/nanopb/examples/using_double_on_avr/encode_double.c @@ -0,0 +1,25 @@ +/* Encodes a float value into a double on the wire. + * Used to emit doubles from AVR code, which doesn't support double directly. + */ + +#include +#include +#include "double_conversion.h" +#include "doubleproto.pb.h" + +int main() +{ + AVRDoubleMessage message = { + float_to_double(1234.5678f), + float_to_double(0.00001f) + }; + + uint8_t buffer[32]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + pb_encode(&stream, AVRDoubleMessage_fields, &message); + fwrite(buffer, 1, stream.bytes_written, stdout); + + return 0; +} + diff --git a/libs/nanopb/examples/using_double_on_avr/test_conversions.c b/libs/nanopb/examples/using_double_on_avr/test_conversions.c new file mode 100644 index 00000000..22620a6a --- /dev/null +++ b/libs/nanopb/examples/using_double_on_avr/test_conversions.c @@ -0,0 +1,56 @@ +#include "double_conversion.h" +#include +#include + +static const double testvalues[] = { + 0.0, -0.0, 0.1, -0.1, + M_PI, -M_PI, 123456.789, -123456.789, + INFINITY, -INFINITY, NAN, INFINITY - INFINITY, + 1e38, -1e38, 1e39, -1e39, + 1e-38, -1e-38, 1e-39, -1e-39, + 3.14159e-37,-3.14159e-37, 3.14159e-43, -3.14159e-43, + 1e-60, -1e-60, 1e-45, -1e-45, + 0.99999999999999, -0.99999999999999, 127.999999999999, -127.999999999999 +}; + +#define TESTVALUES_COUNT (sizeof(testvalues)/sizeof(testvalues[0])) + +int main() +{ + int status = 0; + int i; + for (i = 0; i < TESTVALUES_COUNT; i++) + { + double orig = testvalues[i]; + float expected_float = (float)orig; + double expected_double = (double)expected_float; + + float got_float = double_to_float(*(uint64_t*)&orig); + uint64_t got_double = float_to_double(got_float); + + uint32_t e1 = *(uint32_t*)&expected_float; + uint32_t g1 = *(uint32_t*)&got_float; + uint64_t e2 = *(uint64_t*)&expected_double; + uint64_t g2 = got_double; + + if (g1 != e1) + { + printf("%3d double_to_float fail: %08x != %08x\n", i, g1, e1); + status = 1; + } + + if (g2 != e2) + { + printf("%3d float_to_double fail: %016llx != %016llx\n", i, + (unsigned long long)g2, + (unsigned long long)e2); + status = 1; + } + } + + return status; +} + + + + diff --git a/libs/nanopb/examples/using_union_messages/Makefile b/libs/nanopb/examples/using_union_messages/Makefile new file mode 100644 index 00000000..66396a02 --- /dev/null +++ b/libs/nanopb/examples/using_union_messages/Makefile @@ -0,0 +1,20 @@ +# Include the nanopb provided Makefile rules +include ../../extra/nanopb.mk + +# Compiler flags to enable all warnings & debug info +CFLAGS = -ansi -Wall -Werror -g -O0 +CFLAGS += -I$(NANOPB_DIR) + +all: encode decode + ./encode 1 | ./decode + ./encode 2 | ./decode + ./encode 3 | ./decode + +.SUFFIXES: + +clean: + rm -f encode unionproto.pb.h unionproto.pb.c + +%: %.c unionproto.pb.c + $(CC) $(CFLAGS) -o $@ $^ $(NANOPB_CORE) + diff --git a/libs/nanopb/examples/using_union_messages/README.txt b/libs/nanopb/examples/using_union_messages/README.txt new file mode 100644 index 00000000..7a1e75d4 --- /dev/null +++ b/libs/nanopb/examples/using_union_messages/README.txt @@ -0,0 +1,52 @@ +Nanopb example "using_union_messages" +===================================== + +Union messages is a common technique in Google Protocol Buffers used to +represent a group of messages, only one of which is passed at a time. +It is described in Google's documentation: +https://developers.google.com/protocol-buffers/docs/techniques#union + +This directory contains an example on how to encode and decode union messages +with minimal memory usage. Usually, nanopb would allocate space to store +all of the possible messages at the same time, even though at most one of +them will be used at a time. + +By using some of the lower level nanopb APIs, we can manually generate the +top level message, so that we only need to allocate the one submessage that +we actually want. Similarly when decoding, we can manually read the tag of +the top level message, and only then allocate the memory for the submessage +after we already know its type. + + +Example usage +------------- + +Type `make` to run the example. It will build it and run commands like +following: + +./encode 1 | ./decode +Got MsgType1: 42 +./encode 2 | ./decode +Got MsgType2: true +./encode 3 | ./decode +Got MsgType3: 3 1415 + +This simply demonstrates that the "decode" program has correctly identified +the type of the received message, and managed to decode it. + + +Details of implementation +------------------------- + +unionproto.proto contains the protocol used in the example. It consists of +three messages: MsgType1, MsgType2 and MsgType3, which are collected together +into UnionMessage. + +encode.c takes one command line argument, which should be a number 1-3. It +then fills in and encodes the corresponding message, and writes it to stdout. + +decode.c reads a UnionMessage from stdin. Then it calls the function +decode_unionmessage_type() to determine the type of the message. After that, +the corresponding message is decoded and the contents of it printed to the +screen. + diff --git a/libs/nanopb/examples/using_union_messages/decode.c b/libs/nanopb/examples/using_union_messages/decode.c new file mode 100644 index 00000000..b9f4af55 --- /dev/null +++ b/libs/nanopb/examples/using_union_messages/decode.c @@ -0,0 +1,96 @@ +/* This program reads a message from stdin, detects its type and decodes it. + */ + +#include +#include +#include + +#include +#include "unionproto.pb.h" + +/* This function reads manually the first tag from the stream and finds the + * corresponding message type. It doesn't yet decode the actual message. + * + * Returns a pointer to the MsgType_fields array, as an identifier for the + * message type. Returns null if the tag is of unknown type or an error occurs. + */ +const pb_field_t* decode_unionmessage_type(pb_istream_t *stream) +{ + pb_wire_type_t wire_type; + uint32_t tag; + bool eof; + + while (pb_decode_tag(stream, &wire_type, &tag, &eof)) + { + if (wire_type == PB_WT_STRING) + { + const pb_field_t *field; + for (field = UnionMessage_fields; field->tag != 0; field++) + { + if (field->tag == tag && (field->type & PB_LTYPE_SUBMESSAGE)) + { + /* Found our field. */ + return field->ptr; + } + } + } + + /* Wasn't our field.. */ + pb_skip_field(stream, wire_type); + } + + return NULL; +} + +bool decode_unionmessage_contents(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) +{ + pb_istream_t substream; + bool status; + if (!pb_make_string_substream(stream, &substream)) + return false; + + status = pb_decode(&substream, fields, dest_struct); + pb_close_string_substream(stream, &substream); + return status; +} + +int main() +{ + /* Read the data into buffer */ + uint8_t buffer[512]; + size_t count = fread(buffer, 1, sizeof(buffer), stdin); + pb_istream_t stream = pb_istream_from_buffer(buffer, count); + + const pb_field_t *type = decode_unionmessage_type(&stream); + bool status = false; + + if (type == MsgType1_fields) + { + MsgType1 msg = {}; + status = decode_unionmessage_contents(&stream, MsgType1_fields, &msg); + printf("Got MsgType1: %d\n", msg.value); + } + else if (type == MsgType2_fields) + { + MsgType2 msg = {}; + status = decode_unionmessage_contents(&stream, MsgType2_fields, &msg); + printf("Got MsgType2: %s\n", msg.value ? "true" : "false"); + } + else if (type == MsgType3_fields) + { + MsgType3 msg = {}; + status = decode_unionmessage_contents(&stream, MsgType3_fields, &msg); + printf("Got MsgType3: %d %d\n", msg.value1, msg.value2); + } + + if (!status) + { + printf("Decode failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } + + return 0; +} + + + diff --git a/libs/nanopb/examples/using_union_messages/encode.c b/libs/nanopb/examples/using_union_messages/encode.c new file mode 100644 index 00000000..e124bf91 --- /dev/null +++ b/libs/nanopb/examples/using_union_messages/encode.c @@ -0,0 +1,85 @@ +/* This program takes a command line argument and encodes a message in + * one of MsgType1, MsgType2 or MsgType3. + */ + +#include +#include +#include + +#include +#include "unionproto.pb.h" + +/* This function is the core of the union encoding process. It handles + * the top-level pb_field_t array manually, in order to encode a correct + * field tag before the message. The pointer to MsgType_fields array is + * used as an unique identifier for the message type. + */ +bool encode_unionmessage(pb_ostream_t *stream, const pb_field_t messagetype[], const void *message) +{ + const pb_field_t *field; + for (field = UnionMessage_fields; field->tag != 0; field++) + { + if (field->ptr == messagetype) + { + /* This is our field, encode the message using it. */ + if (!pb_encode_tag_for_field(stream, field)) + return false; + + return pb_encode_submessage(stream, messagetype, message); + } + } + + /* Didn't find the field for messagetype */ + return false; +} + +int main(int argc, char **argv) +{ + if (argc != 2) + { + fprintf(stderr, "Usage: %s (1|2|3)\n", argv[0]); + return 1; + } + + uint8_t buffer[512]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + bool status = false; + int msgtype = atoi(argv[1]); + if (msgtype == 1) + { + /* Send message of type 1 */ + MsgType1 msg = {42}; + status = encode_unionmessage(&stream, MsgType1_fields, &msg); + } + else if (msgtype == 2) + { + /* Send message of type 2 */ + MsgType2 msg = {true}; + status = encode_unionmessage(&stream, MsgType2_fields, &msg); + } + else if (msgtype == 3) + { + /* Send message of type 3 */ + MsgType3 msg = {3, 1415}; + status = encode_unionmessage(&stream, MsgType3_fields, &msg); + } + else + { + fprintf(stderr, "Unknown message type: %d\n", msgtype); + return 2; + } + + if (!status) + { + fprintf(stderr, "Encoding failed!\n"); + return 3; + } + else + { + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; /* Success */ + } +} + + diff --git a/libs/nanopb/examples/using_union_messages/unionproto.proto b/libs/nanopb/examples/using_union_messages/unionproto.proto new file mode 100644 index 00000000..209df0d2 --- /dev/null +++ b/libs/nanopb/examples/using_union_messages/unionproto.proto @@ -0,0 +1,32 @@ +// This is an example of how to handle 'union' style messages +// with nanopb, without allocating memory for all the message types. +// +// There is no official type in Protocol Buffers for describing unions, +// but they are commonly implemented by filling out exactly one of +// several optional fields. + +syntax = "proto2"; + +message MsgType1 +{ + required int32 value = 1; +} + +message MsgType2 +{ + required bool value = 1; +} + +message MsgType3 +{ + required int32 value1 = 1; + required int32 value2 = 2; +} + +message UnionMessage +{ + optional MsgType1 msg1 = 1; + optional MsgType2 msg2 = 2; + optional MsgType3 msg3 = 3; +} + diff --git a/libs/nanopb/extra/FindNanopb.cmake b/libs/nanopb/extra/FindNanopb.cmake new file mode 100644 index 00000000..9afb21d0 --- /dev/null +++ b/libs/nanopb/extra/FindNanopb.cmake @@ -0,0 +1,274 @@ +# This is an example script for use with CMake projects for locating and configuring +# the nanopb library. +# +# The following variables can be set and are optional: +# +# +# PROTOBUF_SRC_ROOT_FOLDER - When compiling with MSVC, if this cache variable is set +# the protobuf-default VS project build locations +# (vsprojects/Debug & vsprojects/Release) will be searched +# for libraries and binaries. +# +# NANOPB_IMPORT_DIRS - List of additional directories to be searched for +# imported .proto files. +# +# NANOPB_GENERATE_CPP_APPEND_PATH - By default -I will be passed to protoc +# for each directory where a proto file is referenced. +# Set to FALSE if you want to disable this behaviour. +# +# Defines the following variables: +# +# NANOPB_FOUND - Found the nanopb library (source&header files, generator tool, protoc compiler tool) +# NANOPB_INCLUDE_DIRS - Include directories for Google Protocol Buffers +# +# The following cache variables are also available to set or use: +# PROTOBUF_PROTOC_EXECUTABLE - The protoc compiler +# NANOPB_GENERATOR_SOURCE_DIR - The nanopb generator source +# +# ==================================================================== +# +# NANOPB_GENERATE_CPP (public function) +# SRCS = Variable to define with autogenerated +# source files +# HDRS = Variable to define with autogenerated +# header files +# ARGN = proto files +# +# ==================================================================== +# Example: +# +# set(NANOPB_SRC_ROOT_FOLDER "/path/to/nanopb") +# set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${NANOPB_SRC_ROOT_FOLDER}/cmake) +# find_package( Nanopb REQUIRED ) +# include_directories(${NANOPB_INCLUDE_DIRS}) +# +# NANOPB_GENERATE_CPP(PROTO_SRCS PROTO_HDRS foo.proto) +# +# include_directories(${CMAKE_CURRENT_BINARY_DIR}) +# add_executable(bar bar.cc ${PROTO_SRCS} ${PROTO_HDRS}) +# +# ==================================================================== + +#============================================================================= +# Copyright 2009 Kitware, Inc. +# Copyright 2009-2011 Philip Lowman +# Copyright 2008 Esben Mose Hansen, Ange Optimization ApS +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the names of Kitware, Inc., the Insight Software Consortium, +# nor the names of their contributors may be used to endorse or promote +# products derived from this software without specific prior written +# permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#============================================================================= +# +# Changes +# 2013.01.31 - Pavlo Ilin - used Modules/FindProtobuf.cmake from cmake 2.8.10 to +# write FindNanopb.cmake +# +#============================================================================= + + +function(NANOPB_GENERATE_CPP SRCS HDRS) + if(NOT ARGN) + return() + endif() + + if(NANOPB_GENERATE_CPP_APPEND_PATH) + # Create an include path for each file specified + foreach(FIL ${ARGN}) + get_filename_component(ABS_FIL ${FIL} ABSOLUTE) + get_filename_component(ABS_PATH ${ABS_FIL} PATH) + + list(FIND _nanobp_include_path ${ABS_PATH} _contains_already) + if(${_contains_already} EQUAL -1) + list(APPEND _nanobp_include_path -I ${ABS_PATH}) + endif() + endforeach() + else() + set(_nanobp_include_path -I ${CMAKE_CURRENT_SOURCE_DIR}) + endif() + + if(DEFINED NANOPB_IMPORT_DIRS) + foreach(DIR ${NANOPB_IMPORT_DIRS}) + get_filename_component(ABS_PATH ${DIR} ABSOLUTE) + list(FIND _nanobp_include_path ${ABS_PATH} _contains_already) + if(${_contains_already} EQUAL -1) + list(APPEND _nanobp_include_path -I ${ABS_PATH}) + endif() + endforeach() + endif() + + set(${SRCS}) + set(${HDRS}) + + set(GENERATOR_PATH ${CMAKE_BINARY_DIR}/nanopb/generator) + + set(NANOPB_GENERATOR_EXECUTABLE ${GENERATOR_PATH}/nanopb_generator.py) + + set(GENERATOR_CORE_DIR ${GENERATOR_PATH}/proto) + set(GENERATOR_CORE_SRC + ${GENERATOR_CORE_DIR}/nanopb.proto + ${GENERATOR_CORE_DIR}/plugin.proto) + + # Treat the source diretory as immutable. + # + # Copy the generator directory to the build directory before + # compiling python and proto files. Fixes issues when using the + # same build directory with different python/protobuf versions + # as the binary build directory is discarded across builds. + # + add_custom_command( + OUTPUT ${NANOPB_GENERATOR_EXECUTABLE} ${GENERATOR_CORE_SRC} + COMMAND ${CMAKE_COMMAND} -E copy_directory + ARGS ${NANOPB_GENERATOR_SOURCE_DIR} ${GENERATOR_PATH} + VERBATIM) + + set(GENERATOR_CORE_PYTHON_SRC) + foreach(FIL ${GENERATOR_CORE_SRC}) + get_filename_component(ABS_FIL ${FIL} ABSOLUTE) + get_filename_component(FIL_WE ${FIL} NAME_WE) + + set(output "${GENERATOR_CORE_DIR}/${FIL_WE}_pb2.py") + set(GENERATOR_CORE_PYTHON_SRC ${GENERATOR_CORE_PYTHON_SRC} ${output}) + add_custom_command( + OUTPUT ${output} + COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} + ARGS -I${GENERATOR_PATH}/proto + --python_out=${GENERATOR_CORE_DIR} ${ABS_FIL} + DEPENDS ${ABS_FIL} + VERBATIM) + endforeach() + + foreach(FIL ${ARGN}) + get_filename_component(ABS_FIL ${FIL} ABSOLUTE) + get_filename_component(FIL_WE ${FIL} NAME_WE) + get_filename_component(FIL_DIR ${FIL} PATH) + set(NANOPB_OPTIONS_FILE ${FIL_DIR}/${FIL_WE}.options) + set(NANOPB_OPTIONS) + if(EXISTS ${NANOPB_OPTIONS_FILE}) + set(NANOPB_OPTIONS -f ${NANOPB_OPTIONS_FILE}) + endif() + + list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.c") + list(APPEND ${HDRS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h") + + add_custom_command( + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb" + COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} + ARGS -I${GENERATOR_PATH} -I${GENERATOR_CORE_DIR} + -I${CMAKE_CURRENT_BINARY_DIR} ${_nanobp_include_path} + -o${FIL_WE}.pb ${ABS_FIL} + DEPENDS ${ABS_FIL} ${GENERATOR_CORE_PYTHON_SRC} + COMMENT "Running C++ protocol buffer compiler on ${FIL}" + VERBATIM ) + + add_custom_command( + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.c" + "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h" + COMMAND ${PYTHON_EXECUTABLE} + ARGS ${NANOPB_GENERATOR_EXECUTABLE} ${FIL_WE}.pb ${NANOPB_OPTIONS} + DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb" + COMMENT "Running nanopb generator on ${FIL_WE}.pb" + VERBATIM ) + endforeach() + + set_source_files_properties(${${SRCS}} ${${HDRS}} PROPERTIES GENERATED TRUE) + set(${SRCS} ${${SRCS}} ${NANOPB_SRCS} PARENT_SCOPE) + set(${HDRS} ${${HDRS}} ${NANOPB_HDRS} PARENT_SCOPE) + +endfunction() + + + +# +# Main. +# + +# By default have NANOPB_GENERATE_CPP macro pass -I to protoc +# for each directory where a proto file is referenced. +if(NOT DEFINED NANOPB_GENERATE_CPP_APPEND_PATH) + set(NANOPB_GENERATE_CPP_APPEND_PATH TRUE) +endif() + +# Make a really good guess regarding location of NANOPB_SRC_ROOT_FOLDER +if(NOT DEFINED NANOPB_SRC_ROOT_FOLDER) + get_filename_component(NANOPB_SRC_ROOT_FOLDER + ${CMAKE_CURRENT_LIST_DIR}/.. ABSOLUTE) +endif() + +# Find the include directory +find_path(NANOPB_INCLUDE_DIRS + pb.h + PATHS ${NANOPB_SRC_ROOT_FOLDER} +) +mark_as_advanced(NANOPB_INCLUDE_DIRS) + +# Find nanopb source files +set(NANOPB_SRCS) +set(NANOPB_HDRS) +list(APPEND _nanopb_srcs pb_decode.c pb_encode.c pb_common.c) +list(APPEND _nanopb_hdrs pb_decode.h pb_encode.h pb_common.h pb.h) + +foreach(FIL ${_nanopb_srcs}) + find_file(${FIL}__nano_pb_file NAMES ${FIL} PATHS ${NANOPB_SRC_ROOT_FOLDER} ${NANOPB_INCLUDE_DIRS}) + list(APPEND NANOPB_SRCS "${${FIL}__nano_pb_file}") + mark_as_advanced(${FIL}__nano_pb_file) +endforeach() + +foreach(FIL ${_nanopb_hdrs}) + find_file(${FIL}__nano_pb_file NAMES ${FIL} PATHS ${NANOPB_INCLUDE_DIRS}) + mark_as_advanced(${FIL}__nano_pb_file) + list(APPEND NANOPB_HDRS "${${FIL}__nano_pb_file}") +endforeach() + +# Find the protoc Executable +find_program(PROTOBUF_PROTOC_EXECUTABLE + NAMES protoc + DOC "The Google Protocol Buffers Compiler" + PATHS + ${PROTOBUF_SRC_ROOT_FOLDER}/vsprojects/Release + ${PROTOBUF_SRC_ROOT_FOLDER}/vsprojects/Debug +) +mark_as_advanced(PROTOBUF_PROTOC_EXECUTABLE) + +# Find nanopb generator source dir +find_path(NANOPB_GENERATOR_SOURCE_DIR + NAMES nanopb_generator.py + DOC "nanopb generator source" + PATHS + ${NANOPB_SRC_ROOT_FOLDER}/generator +) +mark_as_advanced(NANOPB_GENERATOR_SOURCE_DIR) + +find_package(PythonInterp REQUIRED) + +include(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(NANOPB DEFAULT_MSG + NANOPB_INCLUDE_DIRS + NANOPB_SRCS NANOPB_HDRS + NANOPB_GENERATOR_SOURCE_DIR + PROTOBUF_PROTOC_EXECUTABLE + ) diff --git a/libs/nanopb/extra/nanopb-config-version.cmake.in b/libs/nanopb/extra/nanopb-config-version.cmake.in new file mode 100644 index 00000000..f9292a83 --- /dev/null +++ b/libs/nanopb/extra/nanopb-config-version.cmake.in @@ -0,0 +1,11 @@ +set(PACKAGE_VERSION "@nanopb_VERSION@") + +# Check whether the requested PACKAGE_FIND_VERSION is compatible +if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}") + set(PACKAGE_VERSION_COMPATIBLE FALSE) +else() + set(PACKAGE_VERSION_COMPATIBLE TRUE) + if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}") + set(PACKAGE_VERSION_EXACT TRUE) + endif() +endif() diff --git a/libs/nanopb/extra/nanopb-config.cmake b/libs/nanopb/extra/nanopb-config.cmake new file mode 100644 index 00000000..4f726a68 --- /dev/null +++ b/libs/nanopb/extra/nanopb-config.cmake @@ -0,0 +1 @@ +include(${CMAKE_CURRENT_LIST_DIR}/nanopb-targets.cmake) diff --git a/libs/nanopb/extra/nanopb.mk b/libs/nanopb/extra/nanopb.mk new file mode 100644 index 00000000..5c2cff56 --- /dev/null +++ b/libs/nanopb/extra/nanopb.mk @@ -0,0 +1,37 @@ +# This is an include file for Makefiles. It provides rules for building +# .pb.c and .pb.h files out of .proto, as well the path to nanopb core. + +# Path to the nanopb root directory +NANOPB_DIR := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))../) + +# Files for the nanopb core +NANOPB_CORE = $(NANOPB_DIR)/pb_encode.c $(NANOPB_DIR)/pb_decode.c $(NANOPB_DIR)/pb_common.c + +# Check if we are running on Windows +ifdef windir +WINDOWS = 1 +endif +ifdef WINDIR +WINDOWS = 1 +endif + +# Check whether to use binary version of nanopb_generator or the +# system-supplied python interpreter. +ifneq "$(wildcard $(NANOPB_DIR)/generator-bin)" "" + # Binary package + PROTOC = $(NANOPB_DIR)/generator-bin/protoc + PROTOC_OPTS = +else + # Source only or git checkout + PROTOC = protoc + ifdef WINDOWS + PROTOC_OPTS = --plugin=protoc-gen-nanopb=$(NANOPB_DIR)/generator/protoc-gen-nanopb.bat + else + PROTOC_OPTS = --plugin=protoc-gen-nanopb=$(NANOPB_DIR)/generator/protoc-gen-nanopb + endif +endif + +# Rule for building .pb.c and .pb.h +%.pb.c %.pb.h: %.proto $(wildcard %.options) + $(PROTOC) $(PROTOC_OPTS) --nanopb_out=. $< + diff --git a/libs/nanopb/extra/pb_syshdr.h b/libs/nanopb/extra/pb_syshdr.h new file mode 100644 index 00000000..55d06a3a --- /dev/null +++ b/libs/nanopb/extra/pb_syshdr.h @@ -0,0 +1,112 @@ +/* This is an example of a header file for platforms/compilers that do + * not come with stdint.h/stddef.h/stdbool.h/string.h. To use it, define + * PB_SYSTEM_HEADER as "pb_syshdr.h", including the quotes, and add the + * extra folder to your include path. + * + * It is very likely that you will need to customize this file to suit + * your platform. For any compiler that supports C99, this file should + * not be necessary. + */ + +#ifndef _PB_SYSHDR_H_ +#define _PB_SYSHDR_H_ + +/* stdint.h subset */ +#ifdef HAVE_STDINT_H +#include +#else +/* You will need to modify these to match the word size of your platform. */ +typedef signed char int8_t; +typedef unsigned char uint8_t; +typedef signed short int16_t; +typedef unsigned short uint16_t; +typedef signed int int32_t; +typedef unsigned int uint32_t; +typedef signed long long int64_t; +typedef unsigned long long uint64_t; + +/* These are ok for most platforms, unless uint8_t is actually not available, + * in which case you should give the smallest available type. */ +typedef int8_t int_least8_t; +typedef uint8_t uint_least8_t; +typedef uint8_t uint_fast8_t; +typedef int16_t int_least16_t; +typedef uint16_t uint_least16_t; +#endif + +/* stddef.h subset */ +#ifdef HAVE_STDDEF_H +#include +#else + +typedef uint32_t size_t; +#define offsetof(st, m) ((size_t)(&((st *)0)->m)) + +#ifndef NULL +#define NULL 0 +#endif + +#endif + +/* stdbool.h subset */ +#ifdef HAVE_STDBOOL_H +#include +#else + +#ifndef __cplusplus +typedef int bool; +#define false 0 +#define true 1 +#endif + +#endif + +/* stdlib.h subset */ +#ifdef PB_ENABLE_MALLOC +#ifdef HAVE_STDLIB_H +#include +#else +void *realloc(void *ptr, size_t size); +void free(void *ptr); +#endif +#endif + +/* string.h subset */ +#ifdef HAVE_STRING_H +#include +#else + +/* Implementations are from the Public Domain C Library (PDCLib). */ +static size_t strlen( const char * s ) +{ + size_t rc = 0; + while ( s[rc] ) + { + ++rc; + } + return rc; +} + +static void * memcpy( void *s1, const void *s2, size_t n ) +{ + char * dest = (char *) s1; + const char * src = (const char *) s2; + while ( n-- ) + { + *dest++ = *src++; + } + return s1; +} + +static void * memset( void * s, int c, size_t n ) +{ + unsigned char * p = (unsigned char *) s; + while ( n-- ) + { + *p++ = (unsigned char) c; + } + return s; +} +#endif + +#endif diff --git a/libs/nanopb/generator/nanopb/options.proto b/libs/nanopb/generator/nanopb/options.proto new file mode 100644 index 00000000..f08e53d1 --- /dev/null +++ b/libs/nanopb/generator/nanopb/options.proto @@ -0,0 +1,120 @@ +// This is a transitional file, to provide parallel support between the old +// nanopb.proto and new options.proto files. Eventually nanopb.proto will +// be left only for legacy code, but for now the generator is still also +// using it. However, your new code can start using this file already now. +// See pull request #241 for details: +// https://github.com/nanopb/nanopb/pull/241 + +// Custom options for defining: +// - Maximum size of string/bytes +// - Maximum number of elements in array +// +// These are used by nanopb to generate statically allocable structures +// for memory-limited environments. + +syntax = "proto2"; +import "google/protobuf/descriptor.proto"; + +package nanopb; +option java_package = "fi.kapsi.koti.jpa.nanopb"; + +enum FieldType { + FT_DEFAULT = 0; // Automatically decide field type, generate static field if possible. + FT_CALLBACK = 1; // Always generate a callback field. + FT_POINTER = 4; // Always generate a dynamically allocated field. + FT_STATIC = 2; // Generate a static field or raise an exception if not possible. + FT_IGNORE = 3; // Ignore the field completely. + FT_INLINE = 5; // Legacy option, use the separate 'fixed_length' option instead +} + +enum IntSize { + IS_DEFAULT = 0; // Default, 32/64bit based on type in .proto + IS_8 = 8; + IS_16 = 16; + IS_32 = 32; + IS_64 = 64; +} + +// This is the inner options message, which basically defines options for +// a field. When it is used in message or file scope, it applies to all +// fields. +message Options { + // Allocated size for 'bytes' and 'string' fields. + // For string fields, this should include the space for null terminator. + optional int32 max_size = 1; + + // Maximum length for 'string' fields. Setting this is equivalent + // to setting max_size to a value of length+1. + optional int32 max_length = 14; + + // Allocated number of entries in arrays ('repeated' fields) + optional int32 max_count = 2; + + // Size of integer fields. Can save some memory if you don't need + // full 32 bits for the value. + optional IntSize int_size = 7 [default = IS_DEFAULT]; + + // Force type of field (callback or static allocation) + optional FieldType type = 3 [default = FT_DEFAULT]; + + // Use long names for enums, i.e. EnumName_EnumValue. + optional bool long_names = 4 [default = true]; + + // Add 'packed' attribute to generated structs. + // Note: this cannot be used on CPUs that break on unaligned + // accesses to variables. + optional bool packed_struct = 5 [default = false]; + + // Add 'packed' attribute to generated enums. + optional bool packed_enum = 10 [default = false]; + + // Skip this message + optional bool skip_message = 6 [default = false]; + + // Generate oneof fields as normal optional fields instead of union. + optional bool no_unions = 8 [default = false]; + + // integer type tag for a message + optional uint32 msgid = 9; + + // decode oneof as anonymous union + optional bool anonymous_oneof = 11 [default = false]; + + // Proto3 singular field does not generate a "has_" flag + optional bool proto3 = 12 [default = false]; + + // Generate an enum->string mapping function (can take up lots of space). + optional bool enum_to_string = 13 [default = false]; + + // Generate bytes arrays with fixed length + optional bool fixed_length = 15 [default = false]; +} + +// Extensions to protoc 'Descriptor' type in order to define options +// inside a .proto file. +// +// Protocol Buffers extension number registry +// -------------------------------- +// Project: Nanopb +// Contact: Petteri Aimonen +// Web site: http://kapsi.fi/~jpa/nanopb +// Extensions: 1010 (all types) +// -------------------------------- + +extend google.protobuf.FileOptions { + optional Options fileopt = 1010; +} + +extend google.protobuf.MessageOptions { + optional Options msgopt = 1010; +} + +extend google.protobuf.EnumOptions { + optional Options enumopt = 1010; +} + +extend google.protobuf.FieldOptions { + optional Options fieldopt = 1010; +} + + diff --git a/libs/nanopb/generator/nanopb_generator.py b/libs/nanopb/generator/nanopb_generator.py new file mode 100755 index 00000000..42669ace --- /dev/null +++ b/libs/nanopb/generator/nanopb_generator.py @@ -0,0 +1,1671 @@ +#!/usr/bin/env python + +from __future__ import unicode_literals + +'''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.''' +nanopb_version = "nanopb-0.3.9-dev" + +import sys +import re +from functools import reduce + +try: + # Add some dummy imports to keep packaging tools happy. + import google, distutils.util # bbfreeze seems to need these + import pkg_resources # pyinstaller / protobuf 2.5 seem to need these +except: + # Don't care, we will error out later if it is actually important. + pass + +try: + import google.protobuf.text_format as text_format + import google.protobuf.descriptor_pb2 as descriptor +except: + sys.stderr.write(''' + ************************************************************* + *** Could not import the Google protobuf Python libraries *** + *** Try installing package 'python-protobuf' or similar. *** + ************************************************************* + ''' + '\n') + raise + +try: + import proto.nanopb_pb2 as nanopb_pb2 + import proto.plugin_pb2 as plugin_pb2 +except TypeError: + sys.stderr.write(''' + **************************************************************************** + *** Got TypeError when importing the protocol definitions for generator. *** + *** This usually means that the protoc in your path doesn't match the *** + *** Python protobuf library version. *** + *** *** + *** Please check the output of the following commands: *** + *** which protoc *** + *** protoc --version *** + *** python -c 'import google.protobuf; print(google.protobuf.__file__)' *** + **************************************************************************** + ''' + '\n') + raise +except: + sys.stderr.write(''' + ******************************************************************** + *** Failed to import the protocol definitions for generator. *** + *** You have to run 'make' in the nanopb/generator/proto folder. *** + ******************************************************************** + ''' + '\n') + raise + +# --------------------------------------------------------------------------- +# Generation of single fields +# --------------------------------------------------------------------------- + +import time +import os.path + +# Values are tuple (c type, pb type, encoded size, int_size_allowed) +FieldD = descriptor.FieldDescriptorProto +datatypes = { + FieldD.TYPE_BOOL: ('bool', 'BOOL', 1, False), + FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8, False), + FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4, False), + FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8, False), + FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4, False), + FieldD.TYPE_INT32: ('int32_t', 'INT32', 10, True), + FieldD.TYPE_INT64: ('int64_t', 'INT64', 10, True), + FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4, False), + FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8, False), + FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5, True), + FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10, True), + FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5, True), + FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10, True) +} + +# Integer size overrides (from .proto settings) +intsizes = { + nanopb_pb2.IS_8: 'int8_t', + nanopb_pb2.IS_16: 'int16_t', + nanopb_pb2.IS_32: 'int32_t', + nanopb_pb2.IS_64: 'int64_t', +} + +# String types (for python 2 / python 3 compatibility) +try: + strtypes = (unicode, str) +except NameError: + strtypes = (str, ) + +class Names: + '''Keeps a set of nested names and formats them to C identifier.''' + def __init__(self, parts = ()): + if isinstance(parts, Names): + parts = parts.parts + self.parts = tuple(parts) + + def __str__(self): + return '_'.join(self.parts) + + def __add__(self, other): + if isinstance(other, strtypes): + return Names(self.parts + (other,)) + elif isinstance(other, tuple): + return Names(self.parts + other) + else: + raise ValueError("Name parts should be of type str") + + def __eq__(self, other): + return isinstance(other, Names) and self.parts == other.parts + +def names_from_type_name(type_name): + '''Parse Names() from FieldDescriptorProto type_name''' + if type_name[0] != '.': + raise NotImplementedError("Lookup of non-absolute type names is not supported") + return Names(type_name[1:].split('.')) + +def varint_max_size(max_value): + '''Returns the maximum number of bytes a varint can take when encoded.''' + if max_value < 0: + max_value = 2**64 - max_value + for i in range(1, 11): + if (max_value >> (i * 7)) == 0: + return i + raise ValueError("Value too large for varint: " + str(max_value)) + +assert varint_max_size(-1) == 10 +assert varint_max_size(0) == 1 +assert varint_max_size(127) == 1 +assert varint_max_size(128) == 2 + +class EncodedSize: + '''Class used to represent the encoded size of a field or a message. + Consists of a combination of symbolic sizes and integer sizes.''' + def __init__(self, value = 0, symbols = []): + if isinstance(value, EncodedSize): + self.value = value.value + self.symbols = value.symbols + elif isinstance(value, strtypes + (Names,)): + self.symbols = [str(value)] + self.value = 0 + else: + self.value = value + self.symbols = symbols + + def __add__(self, other): + if isinstance(other, int): + return EncodedSize(self.value + other, self.symbols) + elif isinstance(other, strtypes + (Names,)): + return EncodedSize(self.value, self.symbols + [str(other)]) + elif isinstance(other, EncodedSize): + return EncodedSize(self.value + other.value, self.symbols + other.symbols) + else: + raise ValueError("Cannot add size: " + repr(other)) + + def __mul__(self, other): + if isinstance(other, int): + return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols]) + else: + raise ValueError("Cannot multiply size: " + repr(other)) + + def __str__(self): + if not self.symbols: + return str(self.value) + else: + return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')' + + def upperlimit(self): + if not self.symbols: + return self.value + else: + return 2**32 - 1 + +class Enum: + def __init__(self, names, desc, enum_options): + '''desc is EnumDescriptorProto''' + + self.options = enum_options + self.names = names + desc.name + + if enum_options.long_names: + self.values = [(self.names + x.name, x.number) for x in desc.value] + else: + self.values = [(names + x.name, x.number) for x in desc.value] + + self.value_longnames = [self.names + x.name for x in desc.value] + self.packed = enum_options.packed_enum + + def has_negative(self): + for n, v in self.values: + if v < 0: + return True + return False + + def encoded_size(self): + return max([varint_max_size(v) for n,v in self.values]) + + def __str__(self): + result = 'typedef enum _%s {\n' % self.names + result += ',\n'.join([" %s = %d" % x for x in self.values]) + result += '\n}' + + if self.packed: + result += ' pb_packed' + + result += ' %s;' % self.names + + result += '\n#define _%s_MIN %s' % (self.names, self.values[0][0]) + result += '\n#define _%s_MAX %s' % (self.names, self.values[-1][0]) + result += '\n#define _%s_ARRAYSIZE ((%s)(%s+1))' % (self.names, self.names, self.values[-1][0]) + + if not self.options.long_names: + # Define the long names always so that enum value references + # from other files work properly. + for i, x in enumerate(self.values): + result += '\n#define %s %s' % (self.value_longnames[i], x[0]) + + if self.options.enum_to_string: + result += '\nconst char *%s_name(%s v);\n' % (self.names, self.names) + + return result + + def enum_to_string_definition(self): + if not self.options.enum_to_string: + return "" + + result = 'const char *%s_name(%s v) {\n' % (self.names, self.names) + result += ' switch (v) {\n' + + for ((enumname, _), strname) in zip(self.values, self.value_longnames): + # Strip off the leading type name from the string value. + strval = str(strname)[len(str(self.names)) + 1:] + result += ' case %s: return "%s";\n' % (enumname, strval) + + result += ' }\n' + result += ' return "unknown";\n' + result += '}\n' + + return result + +class FieldMaxSize: + def __init__(self, worst = 0, checks = [], field_name = 'undefined'): + if isinstance(worst, list): + self.worst = max(i for i in worst if i is not None) + else: + self.worst = worst + + self.worst_field = field_name + self.checks = list(checks) + + def extend(self, extend, field_name = None): + self.worst = max(self.worst, extend.worst) + + if self.worst == extend.worst: + self.worst_field = extend.worst_field + + self.checks.extend(extend.checks) + +class Field: + def __init__(self, struct_name, desc, field_options): + '''desc is FieldDescriptorProto''' + self.tag = desc.number + self.struct_name = struct_name + self.union_name = None + self.name = desc.name + self.default = None + self.max_size = None + self.max_count = None + self.array_decl = "" + self.enc_size = None + self.ctype = None + + if field_options.type == nanopb_pb2.FT_INLINE: + # Before nanopb-0.3.8, fixed length bytes arrays were specified + # by setting type to FT_INLINE. But to handle pointer typed fields, + # it makes sense to have it as a separate option. + field_options.type = nanopb_pb2.FT_STATIC + field_options.fixed_length = True + + # Parse field options + if field_options.HasField("max_size"): + self.max_size = field_options.max_size + + if desc.type == FieldD.TYPE_STRING and field_options.HasField("max_length"): + # max_length overrides max_size for strings + self.max_size = field_options.max_length + 1 + + if field_options.HasField("max_count"): + self.max_count = field_options.max_count + + if desc.HasField('default_value'): + self.default = desc.default_value + + # Check field rules, i.e. required/optional/repeated. + can_be_static = True + if desc.label == FieldD.LABEL_REPEATED: + self.rules = 'REPEATED' + if self.max_count is None: + can_be_static = False + else: + self.array_decl = '[%d]' % self.max_count + elif field_options.proto3: + self.rules = 'SINGULAR' + elif desc.label == FieldD.LABEL_REQUIRED: + self.rules = 'REQUIRED' + elif desc.label == FieldD.LABEL_OPTIONAL: + self.rules = 'OPTIONAL' + else: + raise NotImplementedError(desc.label) + + # Check if the field can be implemented with static allocation + # i.e. whether the data size is known. + if desc.type == FieldD.TYPE_STRING and self.max_size is None: + can_be_static = False + + if desc.type == FieldD.TYPE_BYTES and self.max_size is None: + can_be_static = False + + # Decide how the field data will be allocated + if field_options.type == nanopb_pb2.FT_DEFAULT: + if can_be_static: + field_options.type = nanopb_pb2.FT_STATIC + else: + field_options.type = nanopb_pb2.FT_CALLBACK + + if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static: + raise Exception("Field %s is defined as static, but max_size or " + "max_count is not given." % self.name) + + if field_options.type == nanopb_pb2.FT_STATIC: + self.allocation = 'STATIC' + elif field_options.type == nanopb_pb2.FT_POINTER: + self.allocation = 'POINTER' + elif field_options.type == nanopb_pb2.FT_CALLBACK: + self.allocation = 'CALLBACK' + else: + raise NotImplementedError(field_options.type) + + # Decide the C data type to use in the struct. + if desc.type in datatypes: + self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type] + + # Override the field size if user wants to use smaller integers + if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT: + self.ctype = intsizes[field_options.int_size] + if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64: + self.ctype = 'u' + self.ctype; + elif desc.type == FieldD.TYPE_ENUM: + self.pbtype = 'ENUM' + self.ctype = names_from_type_name(desc.type_name) + if self.default is not None: + self.default = self.ctype + self.default + self.enc_size = None # Needs to be filled in when enum values are known + elif desc.type == FieldD.TYPE_STRING: + self.pbtype = 'STRING' + self.ctype = 'char' + if self.allocation == 'STATIC': + self.ctype = 'char' + self.array_decl += '[%d]' % self.max_size + self.enc_size = varint_max_size(self.max_size) + self.max_size + elif desc.type == FieldD.TYPE_BYTES: + if field_options.fixed_length: + self.pbtype = 'FIXED_LENGTH_BYTES' + self.enc_size = varint_max_size(self.max_size) + self.max_size + self.ctype = 'pb_byte_t' + self.array_decl += '[%d]' % self.max_size + else: + self.pbtype = 'BYTES' + self.ctype = 'pb_bytes_array_t' + if self.allocation == 'STATIC': + self.ctype = self.struct_name + self.name + 't' + self.enc_size = varint_max_size(self.max_size) + self.max_size + elif desc.type == FieldD.TYPE_MESSAGE: + self.pbtype = 'MESSAGE' + self.ctype = self.submsgname = names_from_type_name(desc.type_name) + self.enc_size = None # Needs to be filled in after the message type is available + else: + raise NotImplementedError(desc.type) + + def __lt__(self, other): + return self.tag < other.tag + + def __str__(self): + result = '' + if self.allocation == 'POINTER': + if self.rules == 'REPEATED': + result += ' pb_size_t ' + self.name + '_count;\n' + + if self.pbtype == 'MESSAGE': + # Use struct definition, so recursive submessages are possible + result += ' struct _%s *%s;' % (self.ctype, self.name) + elif self.pbtype == 'FIXED_LENGTH_BYTES': + # Pointer to fixed size array + result += ' %s (*%s)%s;' % (self.ctype, self.name, self.array_decl) + elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']: + # String/bytes arrays need to be defined as pointers to pointers + result += ' %s **%s;' % (self.ctype, self.name) + else: + result += ' %s *%s;' % (self.ctype, self.name) + elif self.allocation == 'CALLBACK': + result += ' pb_callback_t %s;' % self.name + else: + if self.rules == 'OPTIONAL' and self.allocation == 'STATIC': + result += ' bool has_' + self.name + ';\n' + elif self.rules == 'REPEATED' and self.allocation == 'STATIC': + result += ' pb_size_t ' + self.name + '_count;\n' + result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl) + return result + + def types(self): + '''Return definitions for any special types this field might need.''' + if self.pbtype == 'BYTES' and self.allocation == 'STATIC': + result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype) + else: + result = '' + return result + + def get_dependencies(self): + '''Get list of type names used by this field.''' + if self.allocation == 'STATIC': + return [str(self.ctype)] + else: + return [] + + def get_initializer(self, null_init, inner_init_only = False): + '''Return literal expression for this field's default value. + null_init: If True, initialize to a 0 value instead of default from .proto + inner_init_only: If True, exclude initialization for any count/has fields + ''' + + inner_init = None + if self.pbtype == 'MESSAGE': + if null_init: + inner_init = '%s_init_zero' % self.ctype + else: + inner_init = '%s_init_default' % self.ctype + elif self.default is None or null_init: + if self.pbtype == 'STRING': + inner_init = '""' + elif self.pbtype == 'BYTES': + inner_init = '{0, {0}}' + elif self.pbtype == 'FIXED_LENGTH_BYTES': + inner_init = '{0}' + elif self.pbtype in ('ENUM', 'UENUM'): + inner_init = '(%s)0' % self.ctype + else: + inner_init = '0' + else: + if self.pbtype == 'STRING': + inner_init = self.default.replace('"', '\\"') + inner_init = '"' + inner_init + '"' + elif self.pbtype == 'BYTES': + data = ['0x%02x' % ord(c) for c in self.default] + if len(data) == 0: + inner_init = '{0, {0}}' + else: + inner_init = '{%d, {%s}}' % (len(data), ','.join(data)) + elif self.pbtype == 'FIXED_LENGTH_BYTES': + data = ['0x%02x' % ord(c) for c in self.default] + if len(data) == 0: + inner_init = '{0}' + else: + inner_init = '{%s}' % ','.join(data) + elif self.pbtype in ['FIXED32', 'UINT32']: + inner_init = str(self.default) + 'u' + elif self.pbtype in ['FIXED64', 'UINT64']: + inner_init = str(self.default) + 'ull' + elif self.pbtype in ['SFIXED64', 'INT64']: + inner_init = str(self.default) + 'll' + else: + inner_init = str(self.default) + + if inner_init_only: + return inner_init + + outer_init = None + if self.allocation == 'STATIC': + if self.rules == 'REPEATED': + outer_init = '0, {' + outer_init += ', '.join([inner_init] * self.max_count) + outer_init += '}' + elif self.rules == 'OPTIONAL': + outer_init = 'false, ' + inner_init + else: + outer_init = inner_init + elif self.allocation == 'POINTER': + if self.rules == 'REPEATED': + outer_init = '0, NULL' + else: + outer_init = 'NULL' + elif self.allocation == 'CALLBACK': + if self.pbtype == 'EXTENSION': + outer_init = 'NULL' + else: + outer_init = '{{NULL}, NULL}' + + return outer_init + + def default_decl(self, declaration_only = False): + '''Return definition for this field's default value.''' + if self.default is None: + return None + + ctype = self.ctype + default = self.get_initializer(False, True) + array_decl = '' + + if self.pbtype == 'STRING': + if self.allocation != 'STATIC': + return None # Not implemented + array_decl = '[%d]' % self.max_size + elif self.pbtype == 'BYTES': + if self.allocation != 'STATIC': + return None # Not implemented + elif self.pbtype == 'FIXED_LENGTH_BYTES': + if self.allocation != 'STATIC': + return None # Not implemented + array_decl = '[%d]' % self.max_size + + if declaration_only: + return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl) + else: + return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default) + + def tags(self): + '''Return the #define for the tag number of this field.''' + identifier = '%s_%s_tag' % (self.struct_name, self.name) + return '#define %-40s %d\n' % (identifier, self.tag) + + def pb_field_t(self, prev_field_name, union_index = None): + '''Return the pb_field_t initializer to use in the constant array. + prev_field_name is the name of the previous field or None. For OneOf + unions, union_index is the index of this field inside the OneOf. + ''' + + if self.rules == 'ONEOF': + if self.anonymous: + result = ' PB_ANONYMOUS_ONEOF_FIELD(%s, ' % self.union_name + else: + result = ' PB_ONEOF_FIELD(%s, ' % self.union_name + else: + result = ' PB_FIELD(' + + result += '%3d, ' % self.tag + result += '%-8s, ' % self.pbtype + result += '%s, ' % self.rules + result += '%-8s, ' % self.allocation + + if union_index is not None and union_index > 0: + result += 'UNION, ' + elif prev_field_name is None: + result += 'FIRST, ' + else: + result += 'OTHER, ' + + result += '%s, ' % self.struct_name + result += '%s, ' % self.name + result += '%s, ' % (prev_field_name or self.name) + + if self.pbtype == 'MESSAGE': + result += '&%s_fields)' % self.submsgname + elif self.default is None: + result += '0)' + elif self.pbtype in ['BYTES', 'STRING', 'FIXED_LENGTH_BYTES'] and self.allocation != 'STATIC': + result += '0)' # Arbitrary size default values not implemented + elif self.rules == 'OPTEXT': + result += '0)' # Default value for extensions is not implemented + else: + result += '&%s_default)' % (self.struct_name + self.name) + + return result + + def get_last_field_name(self): + return self.name + + def largest_field_value(self): + '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly. + Returns numeric value or a C-expression for assert.''' + check = [] + if self.pbtype == 'MESSAGE' and self.allocation == 'STATIC': + if self.rules == 'REPEATED': + check.append('pb_membersize(%s, %s[0])' % (self.struct_name, self.name)) + elif self.rules == 'ONEOF': + if self.anonymous: + check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name)) + else: + check.append('pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name)) + else: + check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name)) + elif self.pbtype == 'BYTES' and self.allocation == 'STATIC': + if self.max_size > 251: + check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name)) + + return FieldMaxSize([self.tag, self.max_size, self.max_count], + check, + ('%s.%s' % (self.struct_name, self.name))) + + def encoded_size(self, dependencies): + '''Return the maximum size that this field can take when encoded, + including the field tag. If the size cannot be determined, returns + None.''' + + if self.allocation != 'STATIC': + return None + + if self.pbtype == 'MESSAGE': + encsize = None + if str(self.submsgname) in dependencies: + submsg = dependencies[str(self.submsgname)] + encsize = submsg.encoded_size(dependencies) + if encsize is not None: + # Include submessage length prefix + encsize += varint_max_size(encsize.upperlimit()) + + if encsize is None: + # Submessage or its size cannot be found. + # This can occur if submessage is defined in different + # file, and it or its .options could not be found. + # Instead of direct numeric value, reference the size that + # has been #defined in the other file. + encsize = EncodedSize(self.submsgname + 'size') + + # We will have to make a conservative assumption on the length + # prefix size, though. + encsize += 5 + + elif self.pbtype in ['ENUM', 'UENUM']: + if str(self.ctype) in dependencies: + enumtype = dependencies[str(self.ctype)] + encsize = enumtype.encoded_size() + else: + # Conservative assumption + encsize = 10 + + elif self.enc_size is None: + raise RuntimeError("Could not determine encoded size for %s.%s" + % (self.struct_name, self.name)) + else: + encsize = EncodedSize(self.enc_size) + + encsize += varint_max_size(self.tag << 3) # Tag + wire type + + if self.rules == 'REPEATED': + # Decoders must be always able to handle unpacked arrays. + # Therefore we have to reserve space for it, even though + # we emit packed arrays ourselves. For length of 1, packed + # arrays are larger however so we need to add allowance + # for the length byte. + encsize *= self.max_count + + if self.max_count == 1: + encsize += 1 + + return encsize + + +class ExtensionRange(Field): + def __init__(self, struct_name, range_start, field_options): + '''Implements a special pb_extension_t* field in an extensible message + structure. The range_start signifies the index at which the extensions + start. Not necessarily all tags above this are extensions, it is merely + a speed optimization. + ''' + self.tag = range_start + self.struct_name = struct_name + self.name = 'extensions' + self.pbtype = 'EXTENSION' + self.rules = 'OPTIONAL' + self.allocation = 'CALLBACK' + self.ctype = 'pb_extension_t' + self.array_decl = '' + self.default = None + self.max_size = 0 + self.max_count = 0 + + def __str__(self): + return ' pb_extension_t *extensions;' + + def types(self): + return '' + + def tags(self): + return '' + + def encoded_size(self, dependencies): + # We exclude extensions from the count, because they cannot be known + # until runtime. Other option would be to return None here, but this + # way the value remains useful if extensions are not used. + return EncodedSize(0) + +class ExtensionField(Field): + def __init__(self, struct_name, desc, field_options): + self.fullname = struct_name + desc.name + self.extendee_name = names_from_type_name(desc.extendee) + Field.__init__(self, self.fullname + 'struct', desc, field_options) + + if self.rules != 'OPTIONAL': + self.skip = True + else: + self.skip = False + self.rules = 'OPTEXT' + + def tags(self): + '''Return the #define for the tag number of this field.''' + identifier = '%s_tag' % self.fullname + return '#define %-40s %d\n' % (identifier, self.tag) + + def extension_decl(self): + '''Declaration of the extension type in the .pb.h file''' + if self.skip: + msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname + msg +=' type of extension fields is currently supported. */\n' + return msg + + return ('extern const pb_extension_type_t %s; /* field type: %s */\n' % + (self.fullname, str(self).strip())) + + def extension_def(self): + '''Definition of the extension type in the .pb.c file''' + + if self.skip: + return '' + + result = 'typedef struct {\n' + result += str(self) + result += '\n} %s;\n\n' % self.struct_name + result += ('static const pb_field_t %s_field = \n %s;\n\n' % + (self.fullname, self.pb_field_t(None))) + result += 'const pb_extension_type_t %s = {\n' % self.fullname + result += ' NULL,\n' + result += ' NULL,\n' + result += ' &%s_field\n' % self.fullname + result += '};\n' + return result + + +# --------------------------------------------------------------------------- +# Generation of oneofs (unions) +# --------------------------------------------------------------------------- + +class OneOf(Field): + def __init__(self, struct_name, oneof_desc): + self.struct_name = struct_name + self.name = oneof_desc.name + self.ctype = 'union' + self.pbtype = 'oneof' + self.fields = [] + self.allocation = 'ONEOF' + self.default = None + self.rules = 'ONEOF' + self.anonymous = False + + def add_field(self, field): + if field.allocation == 'CALLBACK': + raise Exception("Callback fields inside of oneof are not supported" + + " (field %s)" % field.name) + + field.union_name = self.name + field.rules = 'ONEOF' + field.anonymous = self.anonymous + self.fields.append(field) + self.fields.sort(key = lambda f: f.tag) + + # Sort by the lowest tag number inside union + self.tag = min([f.tag for f in self.fields]) + + def __str__(self): + result = '' + if self.fields: + result += ' pb_size_t which_' + self.name + ";\n" + result += ' union {\n' + for f in self.fields: + result += ' ' + str(f).replace('\n', '\n ') + '\n' + if self.anonymous: + result += ' };' + else: + result += ' } ' + self.name + ';' + return result + + def types(self): + return ''.join([f.types() for f in self.fields]) + + def get_dependencies(self): + deps = [] + for f in self.fields: + deps += f.get_dependencies() + return deps + + def get_initializer(self, null_init): + return '0, {' + self.fields[0].get_initializer(null_init) + '}' + + def default_decl(self, declaration_only = False): + return None + + def tags(self): + return ''.join([f.tags() for f in self.fields]) + + def pb_field_t(self, prev_field_name): + parts = [] + for union_index, field in enumerate(self.fields): + parts.append(field.pb_field_t(prev_field_name, union_index)) + return ',\n'.join(parts) + + def get_last_field_name(self): + if self.anonymous: + return self.fields[-1].name + else: + return self.name + '.' + self.fields[-1].name + + def largest_field_value(self): + largest = FieldMaxSize() + for f in self.fields: + largest.extend(f.largest_field_value()) + return largest + + def encoded_size(self, dependencies): + '''Returns the size of the largest oneof field.''' + largest = EncodedSize(0) + for f in self.fields: + size = EncodedSize(f.encoded_size(dependencies)) + if size.value is None: + return None + elif size.symbols: + return None # Cannot resolve maximum of symbols + elif size.value > largest.value: + largest = size + + return largest + +# --------------------------------------------------------------------------- +# Generation of messages (structures) +# --------------------------------------------------------------------------- + + +class Message: + def __init__(self, names, desc, message_options): + self.name = names + self.fields = [] + self.oneofs = {} + no_unions = [] + + if message_options.msgid: + self.msgid = message_options.msgid + + if hasattr(desc, 'oneof_decl'): + for i, f in enumerate(desc.oneof_decl): + oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name) + if oneof_options.no_unions: + no_unions.append(i) # No union, but add fields normally + elif oneof_options.type == nanopb_pb2.FT_IGNORE: + pass # No union and skip fields also + else: + oneof = OneOf(self.name, f) + if oneof_options.anonymous_oneof: + oneof.anonymous = True + self.oneofs[i] = oneof + self.fields.append(oneof) + + for f in desc.field: + field_options = get_nanopb_suboptions(f, message_options, self.name + f.name) + if field_options.type == nanopb_pb2.FT_IGNORE: + continue + + field = Field(self.name, f, field_options) + if (hasattr(f, 'oneof_index') and + f.HasField('oneof_index') and + f.oneof_index not in no_unions): + if f.oneof_index in self.oneofs: + self.oneofs[f.oneof_index].add_field(field) + else: + self.fields.append(field) + + if len(desc.extension_range) > 0: + field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions') + range_start = min([r.start for r in desc.extension_range]) + if field_options.type != nanopb_pb2.FT_IGNORE: + self.fields.append(ExtensionRange(self.name, range_start, field_options)) + + self.packed = message_options.packed_struct + self.ordered_fields = self.fields[:] + self.ordered_fields.sort() + + def get_dependencies(self): + '''Get list of type names that this structure refers to.''' + deps = [] + for f in self.fields: + deps += f.get_dependencies() + return deps + + def __str__(self): + result = 'typedef struct _%s {\n' % self.name + + if not self.ordered_fields: + # Empty structs are not allowed in C standard. + # Therefore add a dummy field if an empty message occurs. + result += ' char dummy_field;' + + result += '\n'.join([str(f) for f in self.ordered_fields]) + result += '\n/* @@protoc_insertion_point(struct:%s) */' % self.name + result += '\n}' + + if self.packed: + result += ' pb_packed' + + result += ' %s;' % self.name + + if self.packed: + result = 'PB_PACKED_STRUCT_START\n' + result + result += '\nPB_PACKED_STRUCT_END' + + return result + + def types(self): + return ''.join([f.types() for f in self.fields]) + + def get_initializer(self, null_init): + if not self.ordered_fields: + return '{0}' + + parts = [] + for field in self.ordered_fields: + parts.append(field.get_initializer(null_init)) + return '{' + ', '.join(parts) + '}' + + def default_decl(self, declaration_only = False): + result = "" + for field in self.fields: + default = field.default_decl(declaration_only) + if default is not None: + result += default + '\n' + return result + + def count_required_fields(self): + '''Returns number of required fields inside this message''' + count = 0 + for f in self.fields: + if not isinstance(f, OneOf): + if f.rules == 'REQUIRED': + count += 1 + return count + + def count_all_fields(self): + count = 0 + for f in self.fields: + if isinstance(f, OneOf): + count += len(f.fields) + else: + count += 1 + return count + + def fields_declaration(self): + result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1) + return result + + def fields_definition(self): + result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1) + + prev = None + for field in self.ordered_fields: + result += field.pb_field_t(prev) + result += ',\n' + prev = field.get_last_field_name() + + result += ' PB_LAST_FIELD\n};' + return result + + def encoded_size(self, dependencies): + '''Return the maximum size that this message can take when encoded. + If the size cannot be determined, returns None. + ''' + size = EncodedSize(0) + for field in self.fields: + fsize = field.encoded_size(dependencies) + if fsize is None: + return None + size += fsize + + return size + + +# --------------------------------------------------------------------------- +# Processing of entire .proto files +# --------------------------------------------------------------------------- + +def iterate_messages(desc, names = Names()): + '''Recursively find all messages. For each, yield name, DescriptorProto.''' + if hasattr(desc, 'message_type'): + submsgs = desc.message_type + else: + submsgs = desc.nested_type + + for submsg in submsgs: + sub_names = names + submsg.name + yield sub_names, submsg + + for x in iterate_messages(submsg, sub_names): + yield x + +def iterate_extensions(desc, names = Names()): + '''Recursively find all extensions. + For each, yield name, FieldDescriptorProto. + ''' + for extension in desc.extension: + yield names, extension + + for subname, subdesc in iterate_messages(desc, names): + for extension in subdesc.extension: + yield subname, extension + +def toposort2(data): + '''Topological sort. + From http://code.activestate.com/recipes/577413-topological-sort/ + This function is under the MIT license. + ''' + for k, v in list(data.items()): + v.discard(k) # Ignore self dependencies + extra_items_in_deps = reduce(set.union, list(data.values()), set()) - set(data.keys()) + data.update(dict([(item, set()) for item in extra_items_in_deps])) + while True: + ordered = set(item for item,dep in list(data.items()) if not dep) + if not ordered: + break + for item in sorted(ordered): + yield item + data = dict([(item, (dep - ordered)) for item,dep in list(data.items()) + if item not in ordered]) + assert not data, "A cyclic dependency exists amongst %r" % data + +def sort_dependencies(messages): + '''Sort a list of Messages based on dependencies.''' + dependencies = {} + message_by_name = {} + for message in messages: + dependencies[str(message.name)] = set(message.get_dependencies()) + message_by_name[str(message.name)] = message + + for msgname in toposort2(dependencies): + if msgname in message_by_name: + yield message_by_name[msgname] + +def make_identifier(headername): + '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9''' + result = "" + for c in headername.upper(): + if c.isalnum(): + result += c + else: + result += '_' + return result + +class ProtoFile: + def __init__(self, fdesc, file_options): + '''Takes a FileDescriptorProto and parses it.''' + self.fdesc = fdesc + self.file_options = file_options + self.dependencies = {} + self.parse() + + # Some of types used in this file probably come from the file itself. + # Thus it has implicit dependency on itself. + self.add_dependency(self) + + def parse(self): + self.enums = [] + self.messages = [] + self.extensions = [] + + if self.fdesc.package: + base_name = Names(self.fdesc.package.split('.')) + else: + base_name = Names() + + for enum in self.fdesc.enum_type: + enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name) + self.enums.append(Enum(base_name, enum, enum_options)) + + for names, message in iterate_messages(self.fdesc, base_name): + message_options = get_nanopb_suboptions(message, self.file_options, names) + + if message_options.skip_message: + continue + + self.messages.append(Message(names, message, message_options)) + for enum in message.enum_type: + enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name) + self.enums.append(Enum(names, enum, enum_options)) + + for names, extension in iterate_extensions(self.fdesc, base_name): + field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name) + if field_options.type != nanopb_pb2.FT_IGNORE: + self.extensions.append(ExtensionField(names, extension, field_options)) + + def add_dependency(self, other): + for enum in other.enums: + self.dependencies[str(enum.names)] = enum + + for msg in other.messages: + self.dependencies[str(msg.name)] = msg + + # Fix field default values where enum short names are used. + for enum in other.enums: + if not enum.options.long_names: + for message in self.messages: + for field in message.fields: + if field.default in enum.value_longnames: + idx = enum.value_longnames.index(field.default) + field.default = enum.values[idx][0] + + # Fix field data types where enums have negative values. + for enum in other.enums: + if not enum.has_negative(): + for message in self.messages: + for field in message.fields: + if field.pbtype == 'ENUM' and field.ctype == enum.names: + field.pbtype = 'UENUM' + + def generate_header(self, includes, headername, options): + '''Generate content for a header file. + Generates strings, which should be concatenated and stored to file. + ''' + + yield '/* Automatically generated nanopb header */\n' + if options.notimestamp: + yield '/* Generated by %s */\n\n' % (nanopb_version) + else: + yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime()) + + if self.fdesc.package: + symbol = make_identifier(self.fdesc.package + '_' + headername) + else: + symbol = make_identifier(headername) + yield '#ifndef PB_%s_INCLUDED\n' % symbol + yield '#define PB_%s_INCLUDED\n' % symbol + try: + yield options.libformat % ('pb.h') + except TypeError: + # no %s specified - use whatever was passed in as options.libformat + yield options.libformat + yield '\n' + + for incfile in includes: + noext = os.path.splitext(incfile)[0] + yield options.genformat % (noext + options.extension + '.h') + yield '\n' + + yield '/* @@protoc_insertion_point(includes) */\n' + + yield '#if PB_PROTO_HEADER_VERSION != 30\n' + yield '#error Regenerate this file with the current version of nanopb generator.\n' + yield '#endif\n' + yield '\n' + + yield '#ifdef __cplusplus\n' + yield 'extern "C" {\n' + yield '#endif\n\n' + + if self.enums: + yield '/* Enum definitions */\n' + for enum in self.enums: + yield str(enum) + '\n\n' + + if self.messages: + yield '/* Struct definitions */\n' + for msg in sort_dependencies(self.messages): + yield msg.types() + yield str(msg) + '\n\n' + + if self.extensions: + yield '/* Extensions */\n' + for extension in self.extensions: + yield extension.extension_decl() + yield '\n' + + if self.messages: + yield '/* Default values for struct fields */\n' + for msg in self.messages: + yield msg.default_decl(True) + yield '\n' + + yield '/* Initializer values for message structs */\n' + for msg in self.messages: + identifier = '%s_init_default' % msg.name + yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False)) + for msg in self.messages: + identifier = '%s_init_zero' % msg.name + yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True)) + yield '\n' + + yield '/* Field tags (for use in manual encoding/decoding) */\n' + for msg in sort_dependencies(self.messages): + for field in msg.fields: + yield field.tags() + for extension in self.extensions: + yield extension.tags() + yield '\n' + + yield '/* Struct field encoding specification for nanopb */\n' + for msg in self.messages: + yield msg.fields_declaration() + '\n' + yield '\n' + + yield '/* Maximum encoded size of messages (where known) */\n' + for msg in self.messages: + msize = msg.encoded_size(self.dependencies) + identifier = '%s_size' % msg.name + if msize is not None: + yield '#define %-40s %s\n' % (identifier, msize) + else: + yield '/* %s depends on runtime parameters */\n' % identifier + yield '\n' + + yield '/* Message IDs (where set with "msgid" option) */\n' + + yield '#ifdef PB_MSGID\n' + for msg in self.messages: + if hasattr(msg,'msgid'): + yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name) + yield '\n' + + symbol = make_identifier(headername.split('.')[0]) + yield '#define %s_MESSAGES \\\n' % symbol + + for msg in self.messages: + m = "-1" + msize = msg.encoded_size(self.dependencies) + if msize is not None: + m = msize + if hasattr(msg,'msgid'): + yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name) + yield '\n' + + for msg in self.messages: + if hasattr(msg,'msgid'): + yield '#define %s_msgid %d\n' % (msg.name, msg.msgid) + yield '\n' + + yield '#endif\n\n' + + yield '#ifdef __cplusplus\n' + yield '} /* extern "C" */\n' + yield '#endif\n' + + # End of header + yield '/* @@protoc_insertion_point(eof) */\n' + yield '\n#endif\n' + + def generate_source(self, headername, options): + '''Generate content for a source file.''' + + yield '/* Automatically generated nanopb constant definitions */\n' + if options.notimestamp: + yield '/* Generated by %s */\n\n' % (nanopb_version) + else: + yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime()) + yield options.genformat % (headername) + yield '\n' + yield '/* @@protoc_insertion_point(includes) */\n' + + yield '#if PB_PROTO_HEADER_VERSION != 30\n' + yield '#error Regenerate this file with the current version of nanopb generator.\n' + yield '#endif\n' + yield '\n' + + for msg in self.messages: + yield msg.default_decl(False) + + yield '\n\n' + + for msg in self.messages: + yield msg.fields_definition() + '\n\n' + + for ext in self.extensions: + yield ext.extension_def() + '\n' + + for enum in self.enums: + yield enum.enum_to_string_definition() + '\n' + + # Add checks for numeric limits + if self.messages: + largest_msg = max(self.messages, key = lambda m: m.count_required_fields()) + largest_count = largest_msg.count_required_fields() + if largest_count > 64: + yield '\n/* Check that missing required fields will be properly detected */\n' + yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count + yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name + yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count + yield '#endif\n' + + max_field = FieldMaxSize() + checks_msgnames = [] + for msg in self.messages: + checks_msgnames.append(msg.name) + for field in msg.fields: + max_field.extend(field.largest_field_value()) + + worst = max_field.worst + worst_field = max_field.worst_field + checks = max_field.checks + + if worst > 255 or checks: + yield '\n/* Check that field information fits in pb_field_t */\n' + + if worst > 65535 or checks: + yield '#if !defined(PB_FIELD_32BIT)\n' + if worst > 65535: + yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field + else: + assertion = ' && '.join(str(c) + ' < 65536' for c in checks) + msgs = '_'.join(str(n) for n in checks_msgnames) + yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n' + yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n' + yield ' * \n' + yield ' * The reason you need to do this is that some of your messages contain tag\n' + yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n' + yield ' * field descriptors.\n' + yield ' */\n' + yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs) + yield '#endif\n\n' + + if worst < 65536: + yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n' + if worst > 255: + yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field + else: + assertion = ' && '.join(str(c) + ' < 256' for c in checks) + msgs = '_'.join(str(n) for n in checks_msgnames) + yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n' + yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n' + yield ' * \n' + yield ' * The reason you need to do this is that some of your messages contain tag\n' + yield ' * numbers or field sizes that are larger than what can fit in the default\n' + yield ' * 8 bit descriptors.\n' + yield ' */\n' + yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs) + yield '#endif\n\n' + + # Add check for sizeof(double) + has_double = False + for msg in self.messages: + for field in msg.fields: + if field.ctype == 'double': + has_double = True + + if has_double: + yield '\n' + yield '/* On some platforms (such as AVR), double is really float.\n' + yield ' * These are not directly supported by nanopb, but see example_avr_double.\n' + yield ' * To get rid of this error, remove any double fields from your .proto.\n' + yield ' */\n' + yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n' + + yield '\n' + yield '/* @@protoc_insertion_point(eof) */\n' + +# --------------------------------------------------------------------------- +# Options parsing for the .proto files +# --------------------------------------------------------------------------- + +from fnmatch import fnmatch + +def read_options_file(infile): + '''Parse a separate options file to list: + [(namemask, options), ...] + ''' + results = [] + data = infile.read() + data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE) + data = re.sub('//.*?$', '', data, flags = re.MULTILINE) + data = re.sub('#.*?$', '', data, flags = re.MULTILINE) + for i, line in enumerate(data.split('\n')): + line = line.strip() + if not line: + continue + + parts = line.split(None, 1) + + if len(parts) < 2: + sys.stderr.write("%s:%d: " % (infile.name, i + 1) + + "Option lines should have space between field name and options. " + + "Skipping line: '%s'\n" % line) + continue + + opts = nanopb_pb2.NanoPBOptions() + + try: + text_format.Merge(parts[1], opts) + except Exception as e: + sys.stderr.write("%s:%d: " % (infile.name, i + 1) + + "Unparseable option line: '%s'. " % line + + "Error: %s\n" % str(e)) + continue + results.append((parts[0], opts)) + + return results + +class Globals: + '''Ugly global variables, should find a good way to pass these.''' + verbose_options = False + separate_options = [] + matched_namemasks = set() + +def get_nanopb_suboptions(subdesc, options, name): + '''Get copy of options, and merge information from subdesc.''' + new_options = nanopb_pb2.NanoPBOptions() + new_options.CopyFrom(options) + + if hasattr(subdesc, 'syntax') and subdesc.syntax == "proto3": + new_options.proto3 = True + + # Handle options defined in a separate file + dotname = '.'.join(name.parts) + for namemask, options in Globals.separate_options: + if fnmatch(dotname, namemask): + Globals.matched_namemasks.add(namemask) + new_options.MergeFrom(options) + + # Handle options defined in .proto + if isinstance(subdesc.options, descriptor.FieldOptions): + ext_type = nanopb_pb2.nanopb + elif isinstance(subdesc.options, descriptor.FileOptions): + ext_type = nanopb_pb2.nanopb_fileopt + elif isinstance(subdesc.options, descriptor.MessageOptions): + ext_type = nanopb_pb2.nanopb_msgopt + elif isinstance(subdesc.options, descriptor.EnumOptions): + ext_type = nanopb_pb2.nanopb_enumopt + else: + raise Exception("Unknown options type") + + if subdesc.options.HasExtension(ext_type): + ext = subdesc.options.Extensions[ext_type] + new_options.MergeFrom(ext) + + if Globals.verbose_options: + sys.stderr.write("Options for " + dotname + ": ") + sys.stderr.write(text_format.MessageToString(new_options) + "\n") + + return new_options + + +# --------------------------------------------------------------------------- +# Command line interface +# --------------------------------------------------------------------------- + +import sys +import os.path +from optparse import OptionParser + +optparser = OptionParser( + usage = "Usage: nanopb_generator.py [options] file.pb ...", + epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " + + "Output will be written to file.pb.h and file.pb.c.") +optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[], + help="Exclude file from generated #include list.") +optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb", + help="Set extension to use instead of '.pb' for generated files. [default: %default]") +optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options", + help="Set name of a separate generator options file.") +optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR", + action="append", default = [], + help="Search for .options files additionally in this path") +optparser.add_option("-D", "--output-dir", dest="output_dir", + metavar="OUTPUTDIR", default=None, + help="Output directory of .pb.h and .pb.c files") +optparser.add_option("-Q", "--generated-include-format", dest="genformat", + metavar="FORMAT", default='#include "%s"\n', + help="Set format string to use for including other .pb.h files. [default: %default]") +optparser.add_option("-L", "--library-include-format", dest="libformat", + metavar="FORMAT", default='#include <%s>\n', + help="Set format string to use for including the nanopb pb.h header. [default: %default]") +optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False, + help="Don't add timestamp to .pb.h and .pb.c preambles") +optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False, + help="Don't print anything except errors.") +optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, + help="Print more information.") +optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[], + help="Set generator option (max_size, max_count etc.).") + +def parse_file(filename, fdesc, options): + '''Parse a single file. Returns a ProtoFile instance.''' + toplevel_options = nanopb_pb2.NanoPBOptions() + for s in options.settings: + text_format.Merge(s, toplevel_options) + + if not fdesc: + data = open(filename, 'rb').read() + fdesc = descriptor.FileDescriptorSet.FromString(data).file[0] + + # Check if there is a separate .options file + had_abspath = False + try: + optfilename = options.options_file % os.path.splitext(filename)[0] + except TypeError: + # No %s specified, use the filename as-is + optfilename = options.options_file + had_abspath = True + + paths = ['.'] + options.options_path + for p in paths: + if os.path.isfile(os.path.join(p, optfilename)): + optfilename = os.path.join(p, optfilename) + if options.verbose: + sys.stderr.write('Reading options from ' + optfilename + '\n') + Globals.separate_options = read_options_file(open(optfilename, "rU")) + break + else: + # If we are given a full filename and it does not exist, give an error. + # However, don't give error when we automatically look for .options file + # with the same name as .proto. + if options.verbose or had_abspath: + sys.stderr.write('Options file not found: ' + optfilename + '\n') + Globals.separate_options = [] + + Globals.matched_namemasks = set() + + # Parse the file + file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename])) + f = ProtoFile(fdesc, file_options) + f.optfilename = optfilename + + return f + +def process_file(filename, fdesc, options, other_files = {}): + '''Process a single file. + filename: The full path to the .proto or .pb source file, as string. + fdesc: The loaded FileDescriptorSet, or None to read from the input file. + options: Command line options as they come from OptionsParser. + + Returns a dict: + {'headername': Name of header file, + 'headerdata': Data for the .h header file, + 'sourcename': Name of the source code file, + 'sourcedata': Data for the .c source code file + } + ''' + f = parse_file(filename, fdesc, options) + + # Provide dependencies if available + for dep in f.fdesc.dependency: + if dep in other_files: + f.add_dependency(other_files[dep]) + + # Decide the file names + noext = os.path.splitext(filename)[0] + headername = noext + options.extension + '.h' + sourcename = noext + options.extension + '.c' + headerbasename = os.path.basename(headername) + + # List of .proto files that should not be included in the C header file + # even if they are mentioned in the source .proto. + excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude + includes = [d for d in f.fdesc.dependency if d not in excludes] + + headerdata = ''.join(f.generate_header(includes, headerbasename, options)) + sourcedata = ''.join(f.generate_source(headerbasename, options)) + + # Check if there were any lines in .options that did not match a member + unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks] + if unmatched and not options.quiet: + sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: " + + ', '.join(unmatched) + "\n") + if not Globals.verbose_options: + sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n") + + return {'headername': headername, 'headerdata': headerdata, + 'sourcename': sourcename, 'sourcedata': sourcedata} + +def main_cli(): + '''Main function when invoked directly from the command line.''' + + options, filenames = optparser.parse_args() + + if not filenames: + optparser.print_help() + sys.exit(1) + + if options.quiet: + options.verbose = False + + if options.output_dir and not os.path.exists(options.output_dir): + optparser.print_help() + sys.stderr.write("\noutput_dir does not exist: %s\n" % options.output_dir) + sys.exit(1) + + + Globals.verbose_options = options.verbose + for filename in filenames: + results = process_file(filename, None, options) + + base_dir = options.output_dir or '' + to_write = [ + (os.path.join(base_dir, results['headername']), results['headerdata']), + (os.path.join(base_dir, results['sourcename']), results['sourcedata']), + ] + + if not options.quiet: + paths = " and ".join([x[0] for x in to_write]) + sys.stderr.write("Writing to %s\n" % paths) + + for path, data in to_write: + with open(path, 'w') as f: + f.write(data) + +def main_plugin(): + '''Main function when invoked as a protoc plugin.''' + + import io, sys + if sys.platform == "win32": + import os, msvcrt + # Set stdin and stdout to binary mode + msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) + msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) + + data = io.open(sys.stdin.fileno(), "rb").read() + + request = plugin_pb2.CodeGeneratorRequest.FromString(data) + + try: + # Versions of Python prior to 2.7.3 do not support unicode + # input to shlex.split(). Try to convert to str if possible. + params = str(request.parameter) + except UnicodeEncodeError: + params = request.parameter + + import shlex + args = shlex.split(params) + options, dummy = optparser.parse_args(args) + + Globals.verbose_options = options.verbose + + response = plugin_pb2.CodeGeneratorResponse() + + # Google's protoc does not currently indicate the full path of proto files. + # Instead always add the main file path to the search dirs, that works for + # the common case. + import os.path + options.options_path.append(os.path.dirname(request.file_to_generate[0])) + + # Process any include files first, in order to have them + # available as dependencies + other_files = {} + for fdesc in request.proto_file: + other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options) + + for filename in request.file_to_generate: + for fdesc in request.proto_file: + if fdesc.name == filename: + results = process_file(filename, fdesc, options, other_files) + + f = response.file.add() + f.name = results['headername'] + f.content = results['headerdata'] + + f = response.file.add() + f.name = results['sourcename'] + f.content = results['sourcedata'] + + io.open(sys.stdout.fileno(), "wb").write(response.SerializeToString()) + +if __name__ == '__main__': + # Check if we are running as a plugin under protoc + if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: + main_plugin() + else: + main_cli() diff --git a/libs/nanopb/generator/proto/Makefile b/libs/nanopb/generator/proto/Makefile new file mode 100644 index 00000000..89bfe528 --- /dev/null +++ b/libs/nanopb/generator/proto/Makefile @@ -0,0 +1,4 @@ +all: nanopb_pb2.py plugin_pb2.py + +%_pb2.py: %.proto + protoc --python_out=. $< diff --git a/libs/nanopb/generator/proto/__init__.py b/libs/nanopb/generator/proto/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/libs/nanopb/generator/proto/google/protobuf/descriptor.proto b/libs/nanopb/generator/proto/google/protobuf/descriptor.proto new file mode 100644 index 00000000..e17c0cc8 --- /dev/null +++ b/libs/nanopb/generator/proto/google/protobuf/descriptor.proto @@ -0,0 +1,714 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// The messages in this file describe the definitions found in .proto files. +// A valid .proto file can be translated directly to a FileDescriptorProto +// without any other information (e.g. without reading its imports). + + +syntax = "proto2"; + +package google.protobuf; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DescriptorProtos"; + +// descriptor.proto must be optimized for speed because reflection-based +// algorithms don't work during bootstrapping. +option optimize_for = SPEED; + +// The protocol compiler can output a FileDescriptorSet containing the .proto +// files it parses. +message FileDescriptorSet { + repeated FileDescriptorProto file = 1; +} + +// Describes a complete .proto file. +message FileDescriptorProto { + optional string name = 1; // file name, relative to root of source tree + optional string package = 2; // e.g. "foo", "foo.bar", etc. + + // Names of files imported by this file. + repeated string dependency = 3; + // Indexes of the public imported files in the dependency list above. + repeated int32 public_dependency = 10; + // Indexes of the weak imported files in the dependency list. + // For Google-internal migration only. Do not use. + repeated int32 weak_dependency = 11; + + // All top-level definitions in this file. + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; + + optional FileOptions options = 8; + + // This field contains optional information about the original source code. + // You may safely remove this entire field without harming runtime + // functionality of the descriptors -- the information is needed only by + // development tools. + optional SourceCodeInfo source_code_info = 9; + + // The syntax of the proto file. + // The supported values are "proto2" and "proto3". + optional string syntax = 12; +} + +// Describes a message type. +message DescriptorProto { + optional string name = 1; + + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; + + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; + + message ExtensionRange { + optional int32 start = 1; + optional int32 end = 2; + } + repeated ExtensionRange extension_range = 5; + + repeated OneofDescriptorProto oneof_decl = 8; + + optional MessageOptions options = 7; +} + +// Describes a field within a message. +message FieldDescriptorProto { + enum Type { + // 0 is reserved for errors. + // Order is weird for historical reasons. + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + TYPE_GROUP = 10; // Tag-delimited aggregate. + TYPE_MESSAGE = 11; // Length-delimited aggregate. + + // New in version 2. + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; // Uses ZigZag encoding. + TYPE_SINT64 = 18; // Uses ZigZag encoding. + }; + + enum Label { + // 0 is reserved for errors + LABEL_OPTIONAL = 1; + LABEL_REQUIRED = 2; + LABEL_REPEATED = 3; + // TODO(sanjay): Should we add LABEL_MAP? + }; + + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; + + // If type_name is set, this need not be set. If both this and type_name + // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + optional Type type = 5; + + // For message and enum types, this is the name of the type. If the name + // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + // rules are used to find the type (i.e. first the nested types within this + // message are searched, then within the parent, on up to the root + // namespace). + optional string type_name = 6; + + // For extensions, this is the name of the type being extended. It is + // resolved in the same manner as type_name. + optional string extendee = 2; + + // For numeric types, contains the original text representation of the value. + // For booleans, "true" or "false". + // For strings, contains the default text contents (not escaped in any way). + // For bytes, contains the C escaped value. All bytes >= 128 are escaped. + // TODO(kenton): Base-64 encode? + optional string default_value = 7; + + // If set, gives the index of a oneof in the containing type's oneof_decl + // list. This field is a member of that oneof. Extensions of a oneof should + // not set this since the oneof to which they belong will be inferred based + // on the extension range containing the extension's field number. + optional int32 oneof_index = 9; + + optional FieldOptions options = 8; +} + +// Describes a oneof. +message OneofDescriptorProto { + optional string name = 1; +} + +// Describes an enum type. +message EnumDescriptorProto { + optional string name = 1; + + repeated EnumValueDescriptorProto value = 2; + + optional EnumOptions options = 3; +} + +// Describes a value within an enum. +message EnumValueDescriptorProto { + optional string name = 1; + optional int32 number = 2; + + optional EnumValueOptions options = 3; +} + +// Describes a service. +message ServiceDescriptorProto { + optional string name = 1; + repeated MethodDescriptorProto method = 2; + + optional ServiceOptions options = 3; +} + +// Describes a method of a service. +message MethodDescriptorProto { + optional string name = 1; + + // Input and output type names. These are resolved in the same way as + // FieldDescriptorProto.type_name, but must refer to a message type. + optional string input_type = 2; + optional string output_type = 3; + + optional MethodOptions options = 4; + + // Identifies if client streams multiple client messages + optional bool client_streaming = 5 [default=false]; + // Identifies if server streams multiple server messages + optional bool server_streaming = 6 [default=false]; +} + + +// =================================================================== +// Options + +// Each of the definitions above may have "options" attached. These are +// just annotations which may cause code to be generated slightly differently +// or may contain hints for code that manipulates protocol messages. +// +// Clients may define custom options as extensions of the *Options messages. +// These extensions may not yet be known at parsing time, so the parser cannot +// store the values in them. Instead it stores them in a field in the *Options +// message called uninterpreted_option. This field must have the same name +// across all *Options messages. We then use this field to populate the +// extensions when we build a descriptor, at which point all protos have been +// parsed and so all extensions are known. +// +// Extension numbers for custom options may be chosen as follows: +// * For options which will only be used within a single application or +// organization, or for experimental options, use field numbers 50000 +// through 99999. It is up to you to ensure that you do not use the +// same number for multiple options. +// * For options which will be published and used publicly by multiple +// independent entities, e-mail protobuf-global-extension-registry@google.com +// to reserve extension numbers. Simply provide your project name (e.g. +// Object-C plugin) and your porject website (if available) -- there's no need +// to explain how you intend to use them. Usually you only need one extension +// number. You can declare multiple options with only one extension number by +// putting them in a sub-message. See the Custom Options section of the docs +// for examples: +// https://developers.google.com/protocol-buffers/docs/proto#options +// If this turns out to be popular, a web service will be set up +// to automatically assign option numbers. + + +message FileOptions { + + // Sets the Java package where classes generated from this .proto will be + // placed. By default, the proto package is used, but this is often + // inappropriate because proto packages do not normally start with backwards + // domain names. + optional string java_package = 1; + + + // If set, all the classes from the .proto file are wrapped in a single + // outer class with the given name. This applies to both Proto1 + // (equivalent to the old "--one_java_file" option) and Proto2 (where + // a .proto always translates to a single class, but you may want to + // explicitly choose the class name). + optional string java_outer_classname = 8; + + // If set true, then the Java code generator will generate a separate .java + // file for each top-level message, enum, and service defined in the .proto + // file. Thus, these types will *not* be nested inside the outer class + // named by java_outer_classname. However, the outer class will still be + // generated to contain the file's getDescriptor() method as well as any + // top-level extensions defined in the file. + optional bool java_multiple_files = 10 [default=false]; + + // If set true, then the Java code generator will generate equals() and + // hashCode() methods for all messages defined in the .proto file. + // - In the full runtime, this is purely a speed optimization, as the + // AbstractMessage base class includes reflection-based implementations of + // these methods. + //- In the lite runtime, setting this option changes the semantics of + // equals() and hashCode() to more closely match those of the full runtime; + // the generated methods compute their results based on field values rather + // than object identity. (Implementations should not assume that hashcodes + // will be consistent across runtimes or versions of the protocol compiler.) + optional bool java_generate_equals_and_hash = 20 [default=false]; + + // If set true, then the Java2 code generator will generate code that + // throws an exception whenever an attempt is made to assign a non-UTF-8 + // byte sequence to a string field. + // Message reflection will do the same. + // However, an extension field still accepts non-UTF-8 byte sequences. + // This option has no effect on when used with the lite runtime. + optional bool java_string_check_utf8 = 27 [default=false]; + + + // Generated classes can be optimized for speed or code size. + enum OptimizeMode { + SPEED = 1; // Generate complete code for parsing, serialization, + // etc. + CODE_SIZE = 2; // Use ReflectionOps to implement these methods. + LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. + } + optional OptimizeMode optimize_for = 9 [default=SPEED]; + + // Sets the Go package where structs generated from this .proto will be + // placed. If omitted, the Go package will be derived from the following: + // - The basename of the package import path, if provided. + // - Otherwise, the package statement in the .proto file, if present. + // - Otherwise, the basename of the .proto file, without extension. + optional string go_package = 11; + + + + // Should generic services be generated in each language? "Generic" services + // are not specific to any particular RPC system. They are generated by the + // main code generators in each language (without additional plugins). + // Generic services were the only kind of service generation supported by + // early versions of google.protobuf. + // + // Generic services are now considered deprecated in favor of using plugins + // that generate code specific to your particular RPC system. Therefore, + // these default to false. Old code which depends on generic services should + // explicitly set them to true. + optional bool cc_generic_services = 16 [default=false]; + optional bool java_generic_services = 17 [default=false]; + optional bool py_generic_services = 18 [default=false]; + + // Is this file deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for everything in the file, or it will be completely ignored; in the very + // least, this is a formalization for deprecating files. + optional bool deprecated = 23 [default=false]; + + + // Enables the use of arenas for the proto messages in this file. This applies + // only to generated classes for C++. + optional bool cc_enable_arenas = 31 [default=false]; + + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message MessageOptions { + // Set true to use the old proto1 MessageSet wire format for extensions. + // This is provided for backwards-compatibility with the MessageSet wire + // format. You should not use this for any other reason: It's less + // efficient, has fewer features, and is more complicated. + // + // The message must be defined exactly as follows: + // message Foo { + // option message_set_wire_format = true; + // extensions 4 to max; + // } + // Note that the message cannot have any defined fields; MessageSets only + // have extensions. + // + // All extensions of your type must be singular messages; e.g. they cannot + // be int32s, enums, or repeated messages. + // + // Because this is an option, the above two restrictions are not enforced by + // the protocol compiler. + optional bool message_set_wire_format = 1 [default=false]; + + // Disables the generation of the standard "descriptor()" accessor, which can + // conflict with a field of the same name. This is meant to make migration + // from proto1 easier; new code should avoid fields named "descriptor". + optional bool no_standard_descriptor_accessor = 2 [default=false]; + + // Is this message deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the message, or it will be completely ignored; in the very least, + // this is a formalization for deprecating messages. + optional bool deprecated = 3 [default=false]; + + // Whether the message is an automatically generated map entry type for the + // maps field. + // + // For maps fields: + // map map_field = 1; + // The parsed descriptor looks like: + // message MapFieldEntry { + // option map_entry = true; + // optional KeyType key = 1; + // optional ValueType value = 2; + // } + // repeated MapFieldEntry map_field = 1; + // + // Implementations may choose not to generate the map_entry=true message, but + // use a native map in the target language to hold the keys and values. + // The reflection APIs in such implementions still need to work as + // if the field is a repeated message field. + // + // NOTE: Do not set the option in .proto files. Always use the maps syntax + // instead. The option should only be implicitly set by the proto compiler + // parser. + optional bool map_entry = 7; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message FieldOptions { + // The ctype option instructs the C++ code generator to use a different + // representation of the field than it normally would. See the specific + // options below. This option is not yet implemented in the open source + // release -- sorry, we'll try to include it in a future version! + optional CType ctype = 1 [default = STRING]; + enum CType { + // Default mode. + STRING = 0; + + CORD = 1; + + STRING_PIECE = 2; + } + // The packed option can be enabled for repeated primitive fields to enable + // a more efficient representation on the wire. Rather than repeatedly + // writing the tag and type for each element, the entire array is encoded as + // a single length-delimited blob. + optional bool packed = 2; + + + + // Should this field be parsed lazily? Lazy applies only to message-type + // fields. It means that when the outer message is initially parsed, the + // inner message's contents will not be parsed but instead stored in encoded + // form. The inner message will actually be parsed when it is first accessed. + // + // This is only a hint. Implementations are free to choose whether to use + // eager or lazy parsing regardless of the value of this option. However, + // setting this option true suggests that the protocol author believes that + // using lazy parsing on this field is worth the additional bookkeeping + // overhead typically needed to implement it. + // + // This option does not affect the public interface of any generated code; + // all method signatures remain the same. Furthermore, thread-safety of the + // interface is not affected by this option; const methods remain safe to + // call from multiple threads concurrently, while non-const methods continue + // to require exclusive access. + // + // + // Note that implementations may choose not to check required fields within + // a lazy sub-message. That is, calling IsInitialized() on the outher message + // may return true even if the inner message has missing required fields. + // This is necessary because otherwise the inner message would have to be + // parsed in order to perform the check, defeating the purpose of lazy + // parsing. An implementation which chooses not to check required fields + // must be consistent about it. That is, for any particular sub-message, the + // implementation must either *always* check its required fields, or *never* + // check its required fields, regardless of whether or not the message has + // been parsed. + optional bool lazy = 5 [default=false]; + + // Is this field deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for accessors, or it will be completely ignored; in the very least, this + // is a formalization for deprecating fields. + optional bool deprecated = 3 [default=false]; + + // For Google-internal migration only. Do not use. + optional bool weak = 10 [default=false]; + + + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumOptions { + + // Set this option to true to allow mapping different tag names to the same + // value. + optional bool allow_alias = 2; + + // Is this enum deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum, or it will be completely ignored; in the very least, this + // is a formalization for deprecating enums. + optional bool deprecated = 3 [default=false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumValueOptions { + // Is this enum value deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the enum value, or it will be completely ignored; in the very least, + // this is a formalization for deprecating enum values. + optional bool deprecated = 1 [default=false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message ServiceOptions { + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this service deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the service, or it will be completely ignored; in the very least, + // this is a formalization for deprecating services. + optional bool deprecated = 33 [default=false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message MethodOptions { + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // Is this method deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for the method, or it will be completely ignored; in the very least, + // this is a formalization for deprecating methods. + optional bool deprecated = 33 [default=false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + + +// A message representing a option the parser does not recognize. This only +// appears in options protos created by the compiler::Parser class. +// DescriptorPool resolves these when building Descriptor objects. Therefore, +// options protos in descriptor objects (e.g. returned by Descriptor::options(), +// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions +// in them. +message UninterpretedOption { + // The name of the uninterpreted option. Each string represents a segment in + // a dot-separated name. is_extension is true iff a segment represents an + // extension (denoted with parentheses in options specs in .proto files). + // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents + // "foo.(bar.baz).qux". + message NamePart { + required string name_part = 1; + required bool is_extension = 2; + } + repeated NamePart name = 2; + + // The value of the uninterpreted option, in whatever type the tokenizer + // identified it as during parsing. Exactly one of these should be set. + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; +} + +// =================================================================== +// Optional source code info + +// Encapsulates information about the original source file from which a +// FileDescriptorProto was generated. +message SourceCodeInfo { + // A Location identifies a piece of source code in a .proto file which + // corresponds to a particular definition. This information is intended + // to be useful to IDEs, code indexers, documentation generators, and similar + // tools. + // + // For example, say we have a file like: + // message Foo { + // optional string foo = 1; + // } + // Let's look at just the field definition: + // optional string foo = 1; + // ^ ^^ ^^ ^ ^^^ + // a bc de f ghi + // We have the following locations: + // span path represents + // [a,i) [ 4, 0, 2, 0 ] The whole field definition. + // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + // + // Notes: + // - A location may refer to a repeated field itself (i.e. not to any + // particular index within it). This is used whenever a set of elements are + // logically enclosed in a single code segment. For example, an entire + // extend block (possibly containing multiple extension definitions) will + // have an outer location whose path refers to the "extensions" repeated + // field without an index. + // - Multiple locations may have the same path. This happens when a single + // logical declaration is spread out across multiple places. The most + // obvious example is the "extend" block again -- there may be multiple + // extend blocks in the same scope, each of which will have the same path. + // - A location's span is not always a subset of its parent's span. For + // example, the "extendee" of an extension declaration appears at the + // beginning of the "extend" block and is shared by all extensions within + // the block. + // - Just because a location's span is a subset of some other location's span + // does not mean that it is a descendent. For example, a "group" defines + // both a type and a field in a single declaration. Thus, the locations + // corresponding to the type and field and their components will overlap. + // - Code which tries to interpret locations should probably be designed to + // ignore those that it doesn't understand, as more types of locations could + // be recorded in the future. + repeated Location location = 1; + message Location { + // Identifies which part of the FileDescriptorProto was defined at this + // location. + // + // Each element is a field number or an index. They form a path from + // the root FileDescriptorProto to the place where the definition. For + // example, this path: + // [ 4, 3, 2, 7, 1 ] + // refers to: + // file.message_type(3) // 4, 3 + // .field(7) // 2, 7 + // .name() // 1 + // This is because FileDescriptorProto.message_type has field number 4: + // repeated DescriptorProto message_type = 4; + // and DescriptorProto.field has field number 2: + // repeated FieldDescriptorProto field = 2; + // and FieldDescriptorProto.name has field number 1: + // optional string name = 1; + // + // Thus, the above path gives the location of a field name. If we removed + // the last element: + // [ 4, 3, 2, 7 ] + // this path refers to the whole field declaration (from the beginning + // of the label to the terminating semicolon). + repeated int32 path = 1 [packed=true]; + + // Always has exactly three or four elements: start line, start column, + // end line (optional, otherwise assumed same as start line), end column. + // These are packed into a single field for efficiency. Note that line + // and column numbers are zero-based -- typically you will want to add + // 1 to each before displaying to a user. + repeated int32 span = 2 [packed=true]; + + // If this SourceCodeInfo represents a complete declaration, these are any + // comments appearing before and after the declaration which appear to be + // attached to the declaration. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // Only the comment content is provided; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk + // will be stripped from the beginning of each line other than the first. + // Newlines are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to qux. + // // + // // Another line attached to qux. + // optional double qux = 4; + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + optional string leading_comments = 3; + optional string trailing_comments = 4; + } +} diff --git a/libs/nanopb/generator/proto/nanopb.proto b/libs/nanopb/generator/proto/nanopb.proto new file mode 100644 index 00000000..e4c1da79 --- /dev/null +++ b/libs/nanopb/generator/proto/nanopb.proto @@ -0,0 +1,112 @@ +// Custom options for defining: +// - Maximum size of string/bytes +// - Maximum number of elements in array +// +// These are used by nanopb to generate statically allocable structures +// for memory-limited environments. + +syntax = "proto2"; +import "google/protobuf/descriptor.proto"; + +option java_package = "fi.kapsi.koti.jpa.nanopb"; + +enum FieldType { + FT_DEFAULT = 0; // Automatically decide field type, generate static field if possible. + FT_CALLBACK = 1; // Always generate a callback field. + FT_POINTER = 4; // Always generate a dynamically allocated field. + FT_STATIC = 2; // Generate a static field or raise an exception if not possible. + FT_IGNORE = 3; // Ignore the field completely. + FT_INLINE = 5; // Legacy option, use the separate 'fixed_length' option instead +} + +enum IntSize { + IS_DEFAULT = 0; // Default, 32/64bit based on type in .proto + IS_8 = 8; + IS_16 = 16; + IS_32 = 32; + IS_64 = 64; +} + +// This is the inner options message, which basically defines options for +// a field. When it is used in message or file scope, it applies to all +// fields. +message NanoPBOptions { + // Allocated size for 'bytes' and 'string' fields. + // For string fields, this should include the space for null terminator. + optional int32 max_size = 1; + + // Maximum length for 'string' fields. Setting this is equivalent + // to setting max_size to a value of length+1. + optional int32 max_length = 14; + + // Allocated number of entries in arrays ('repeated' fields) + optional int32 max_count = 2; + + // Size of integer fields. Can save some memory if you don't need + // full 32 bits for the value. + optional IntSize int_size = 7 [default = IS_DEFAULT]; + + // Force type of field (callback or static allocation) + optional FieldType type = 3 [default = FT_DEFAULT]; + + // Use long names for enums, i.e. EnumName_EnumValue. + optional bool long_names = 4 [default = true]; + + // Add 'packed' attribute to generated structs. + // Note: this cannot be used on CPUs that break on unaligned + // accesses to variables. + optional bool packed_struct = 5 [default = false]; + + // Add 'packed' attribute to generated enums. + optional bool packed_enum = 10 [default = false]; + + // Skip this message + optional bool skip_message = 6 [default = false]; + + // Generate oneof fields as normal optional fields instead of union. + optional bool no_unions = 8 [default = false]; + + // integer type tag for a message + optional uint32 msgid = 9; + + // decode oneof as anonymous union + optional bool anonymous_oneof = 11 [default = false]; + + // Proto3 singular field does not generate a "has_" flag + optional bool proto3 = 12 [default = false]; + + // Generate an enum->string mapping function (can take up lots of space). + optional bool enum_to_string = 13 [default = false]; + + // Generate bytes arrays with fixed length + optional bool fixed_length = 15 [default = false]; +} + +// Extensions to protoc 'Descriptor' type in order to define options +// inside a .proto file. +// +// Protocol Buffers extension number registry +// -------------------------------- +// Project: Nanopb +// Contact: Petteri Aimonen +// Web site: http://kapsi.fi/~jpa/nanopb +// Extensions: 1010 (all types) +// -------------------------------- + +extend google.protobuf.FileOptions { + optional NanoPBOptions nanopb_fileopt = 1010; +} + +extend google.protobuf.MessageOptions { + optional NanoPBOptions nanopb_msgopt = 1010; +} + +extend google.protobuf.EnumOptions { + optional NanoPBOptions nanopb_enumopt = 1010; +} + +extend google.protobuf.FieldOptions { + optional NanoPBOptions nanopb = 1010; +} + + diff --git a/libs/nanopb/generator/proto/plugin.proto b/libs/nanopb/generator/proto/plugin.proto new file mode 100644 index 00000000..e627289b --- /dev/null +++ b/libs/nanopb/generator/proto/plugin.proto @@ -0,0 +1,148 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// +// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to +// change. +// +// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is +// just a program that reads a CodeGeneratorRequest from stdin and writes a +// CodeGeneratorResponse to stdout. +// +// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead +// of dealing with the raw protocol defined here. +// +// A plugin executable needs only to be placed somewhere in the path. The +// plugin should be named "protoc-gen-$NAME", and will then be used when the +// flag "--${NAME}_out" is passed to protoc. + +syntax = "proto2"; +package google.protobuf.compiler; +option java_package = "com.google.protobuf.compiler"; +option java_outer_classname = "PluginProtos"; + +import "google/protobuf/descriptor.proto"; + +// An encoded CodeGeneratorRequest is written to the plugin's stdin. +message CodeGeneratorRequest { + // The .proto files that were explicitly listed on the command-line. The + // code generator should generate code only for these files. Each file's + // descriptor will be included in proto_file, below. + repeated string file_to_generate = 1; + + // The generator parameter passed on the command-line. + optional string parameter = 2; + + // FileDescriptorProtos for all files in files_to_generate and everything + // they import. The files will appear in topological order, so each file + // appears before any file that imports it. + // + // protoc guarantees that all proto_files will be written after + // the fields above, even though this is not technically guaranteed by the + // protobuf wire format. This theoretically could allow a plugin to stream + // in the FileDescriptorProtos and handle them one by one rather than read + // the entire set into memory at once. However, as of this writing, this + // is not similarly optimized on protoc's end -- it will store all fields in + // memory at once before sending them to the plugin. + repeated FileDescriptorProto proto_file = 15; +} + +// The plugin writes an encoded CodeGeneratorResponse to stdout. +message CodeGeneratorResponse { + // Error message. If non-empty, code generation failed. The plugin process + // should exit with status code zero even if it reports an error in this way. + // + // This should be used to indicate errors in .proto files which prevent the + // code generator from generating correct code. Errors which indicate a + // problem in protoc itself -- such as the input CodeGeneratorRequest being + // unparseable -- should be reported by writing a message to stderr and + // exiting with a non-zero status code. + optional string error = 1; + + // Represents a single generated file. + message File { + // The file name, relative to the output directory. The name must not + // contain "." or ".." components and must be relative, not be absolute (so, + // the file cannot lie outside the output directory). "/" must be used as + // the path separator, not "\". + // + // If the name is omitted, the content will be appended to the previous + // file. This allows the generator to break large files into small chunks, + // and allows the generated text to be streamed back to protoc so that large + // files need not reside completely in memory at one time. Note that as of + // this writing protoc does not optimize for this -- it will read the entire + // CodeGeneratorResponse before writing files to disk. + optional string name = 1; + + // If non-empty, indicates that the named file should already exist, and the + // content here is to be inserted into that file at a defined insertion + // point. This feature allows a code generator to extend the output + // produced by another code generator. The original generator may provide + // insertion points by placing special annotations in the file that look + // like: + // @@protoc_insertion_point(NAME) + // The annotation can have arbitrary text before and after it on the line, + // which allows it to be placed in a comment. NAME should be replaced with + // an identifier naming the point -- this is what other generators will use + // as the insertion_point. Code inserted at this point will be placed + // immediately above the line containing the insertion point (thus multiple + // insertions to the same point will come out in the order they were added). + // The double-@ is intended to make it unlikely that the generated code + // could contain things that look like insertion points by accident. + // + // For example, the C++ code generator places the following line in the + // .pb.h files that it generates: + // // @@protoc_insertion_point(namespace_scope) + // This line appears within the scope of the file's package namespace, but + // outside of any particular class. Another plugin can then specify the + // insertion_point "namespace_scope" to generate additional classes or + // other declarations that should be placed in this scope. + // + // Note that if the line containing the insertion point begins with + // whitespace, the same whitespace will be added to every line of the + // inserted text. This is useful for languages like Python, where + // indentation matters. In these languages, the insertion point comment + // should be indented the same amount as any inserted code will need to be + // in order to work correctly in that context. + // + // The code generator that generates the initial file and the one which + // inserts into it must both run as part of a single invocation of protoc. + // Code generators are executed in the order in which they appear on the + // command line. + // + // If |insertion_point| is present, |name| must also be present. + optional string insertion_point = 2; + + // The file contents. + optional string content = 15; + } + repeated File file = 15; +} diff --git a/libs/nanopb/generator/protoc-gen-nanopb b/libs/nanopb/generator/protoc-gen-nanopb new file mode 100755 index 00000000..471a620b --- /dev/null +++ b/libs/nanopb/generator/protoc-gen-nanopb @@ -0,0 +1,13 @@ +#!/bin/sh + +# This file is used to invoke nanopb_generator.py as a plugin +# to protoc on Linux and other *nix-style systems. +# Use it like this: +# protoc --plugin=protoc-gen-nanopb=..../protoc-gen-nanopb --nanopb_out=dir foo.proto +# +# Note that if you use the binary package of nanopb, the protoc +# path is already set up properly and there is no need to give +# --plugin= on the command line. + +MYPATH=$(dirname "$0") +exec "$MYPATH/nanopb_generator.py" --protoc-plugin diff --git a/libs/nanopb/generator/protoc-gen-nanopb.bat b/libs/nanopb/generator/protoc-gen-nanopb.bat new file mode 100644 index 00000000..e6cf187f --- /dev/null +++ b/libs/nanopb/generator/protoc-gen-nanopb.bat @@ -0,0 +1,12 @@ +@echo off +:: This file is used to invoke nanopb_generator.py as a plugin +:: to protoc on Windows. +:: Use it like this: +:: protoc --plugin=protoc-gen-nanopb=..../protoc-gen-nanopb.bat --nanopb_out=dir foo.proto +:: +:: Note that if you use the binary package of nanopb, the protoc +:: path is already set up properly and there is no need to give +:: --plugin= on the command line. + +set mydir=%~dp0 +python "%mydir%\nanopb_generator.py" --protoc-plugin diff --git a/libs/nanopb/library.json b/libs/nanopb/library.json new file mode 100644 index 00000000..8e963f34 --- /dev/null +++ b/libs/nanopb/library.json @@ -0,0 +1,23 @@ +{ + "name": "Nanopb", + "version": "0.3.9-dev", + "keywords": "protocol buffers, protobuf, google", + "description": "Nanopb is a plain-C implementation of Google's Protocol Buffers data format. It is targeted at 32 bit microcontrollers, but is also fit for other embedded systems with tight (2-10 kB ROM, <1 kB RAM) memory constraints.", + "repository": { + "type": "git", + "url": "https://github.com/nanopb/nanopb.git" + }, + "authors": [{ + "name": "Petteri Aimonen", + "email": "jpa@nanopb.mail.kapsi.fi", + "url": "http://koti.kapsi.fi/jpa/nanopb/" + }], + "include": [ + "*.c", + "*.cpp", + "*.h" + ], + "examples": "examples/*/*.c", + "frameworks": "*", + "platforms": "*" +} diff --git a/libs/nanopb/pb.h b/libs/nanopb/pb.h new file mode 100644 index 00000000..c7e6bc67 --- /dev/null +++ b/libs/nanopb/pb.h @@ -0,0 +1,583 @@ +/* Common parts of the nanopb library. Most of these are quite low-level + * stuff. For the high-level interface, see pb_encode.h and pb_decode.h. + */ + +#ifndef PB_H_INCLUDED +#define PB_H_INCLUDED + +/***************************************************************** + * Nanopb compilation time options. You can change these here by * + * uncommenting the lines, or on the compiler command line. * + *****************************************************************/ + +/* Enable support for dynamically allocated fields */ +/* #define PB_ENABLE_MALLOC 1 */ + +/* Define this if your CPU / compiler combination does not support + * unaligned memory access to packed structures. */ +/* #define PB_NO_PACKED_STRUCTS 1 */ + +/* Increase the number of required fields that are tracked. + * A compiler warning will tell if you need this. */ +/* #define PB_MAX_REQUIRED_FIELDS 256 */ + +/* Add support for tag numbers > 255 and fields larger than 255 bytes. */ +/* #define PB_FIELD_16BIT 1 */ + +/* Add support for tag numbers > 65536 and fields larger than 65536 bytes. */ +/* #define PB_FIELD_32BIT 1 */ + +/* Disable support for error messages in order to save some code space. */ +/* #define PB_NO_ERRMSG 1 */ + +/* Disable support for custom streams (support only memory buffers). */ +/* #define PB_BUFFER_ONLY 1 */ + +/* Switch back to the old-style callback function signature. + * This was the default until nanopb-0.2.1. */ +/* #define PB_OLD_CALLBACK_STYLE */ + + +/****************************************************************** + * You usually don't need to change anything below this line. * + * Feel free to look around and use the defined macros, though. * + ******************************************************************/ + + +/* Version of the nanopb library. Just in case you want to check it in + * your own program. */ +#define NANOPB_VERSION nanopb-0.3.9-dev + +/* Include all the system headers needed by nanopb. You will need the + * definitions of the following: + * - strlen, memcpy, memset functions + * - [u]int_least8_t, uint_fast8_t, [u]int_least16_t, [u]int32_t, [u]int64_t + * - size_t + * - bool + * + * If you don't have the standard header files, you can instead provide + * a custom header that defines or includes all this. In that case, + * define PB_SYSTEM_HEADER to the path of this file. + */ +#ifdef PB_SYSTEM_HEADER +#include PB_SYSTEM_HEADER +#else +#include +#include +#include +#include + +#ifdef PB_ENABLE_MALLOC +#include +#endif +#endif + +/* Macro for defining packed structures (compiler dependent). + * This just reduces memory requirements, but is not required. + */ +#if defined(PB_NO_PACKED_STRUCTS) + /* Disable struct packing */ +# define PB_PACKED_STRUCT_START +# define PB_PACKED_STRUCT_END +# define pb_packed +#elif defined(__GNUC__) || defined(__clang__) + /* For GCC and clang */ +# define PB_PACKED_STRUCT_START +# define PB_PACKED_STRUCT_END +# define pb_packed __attribute__((packed)) +#elif defined(__ICCARM__) || defined(__CC_ARM) + /* For IAR ARM and Keil MDK-ARM compilers */ +# define PB_PACKED_STRUCT_START _Pragma("pack(push, 1)") +# define PB_PACKED_STRUCT_END _Pragma("pack(pop)") +# define pb_packed +#elif defined(_MSC_VER) && (_MSC_VER >= 1500) + /* For Microsoft Visual C++ */ +# define PB_PACKED_STRUCT_START __pragma(pack(push, 1)) +# define PB_PACKED_STRUCT_END __pragma(pack(pop)) +# define pb_packed +#else + /* Unknown compiler */ +# define PB_PACKED_STRUCT_START +# define PB_PACKED_STRUCT_END +# define pb_packed +#endif + +/* Handly macro for suppressing unreferenced-parameter compiler warnings. */ +#ifndef PB_UNUSED +#define PB_UNUSED(x) (void)(x) +#endif + +/* Compile-time assertion, used for checking compatible compilation options. + * If this does not work properly on your compiler, use + * #define PB_NO_STATIC_ASSERT to disable it. + * + * But before doing that, check carefully the error message / place where it + * comes from to see if the error has a real cause. Unfortunately the error + * message is not always very clear to read, but you can see the reason better + * in the place where the PB_STATIC_ASSERT macro was called. + */ +#ifndef PB_NO_STATIC_ASSERT +#ifndef PB_STATIC_ASSERT +#define PB_STATIC_ASSERT(COND,MSG) typedef char PB_STATIC_ASSERT_MSG(MSG, __LINE__, __COUNTER__)[(COND)?1:-1]; +#define PB_STATIC_ASSERT_MSG(MSG, LINE, COUNTER) PB_STATIC_ASSERT_MSG_(MSG, LINE, COUNTER) +#define PB_STATIC_ASSERT_MSG_(MSG, LINE, COUNTER) pb_static_assertion_##MSG##LINE##COUNTER +#endif +#else +#define PB_STATIC_ASSERT(COND,MSG) +#endif + +/* Number of required fields to keep track of. */ +#ifndef PB_MAX_REQUIRED_FIELDS +#define PB_MAX_REQUIRED_FIELDS 64 +#endif + +#if PB_MAX_REQUIRED_FIELDS < 64 +#error You should not lower PB_MAX_REQUIRED_FIELDS from the default value (64). +#endif + +/* List of possible field types. These are used in the autogenerated code. + * Least-significant 4 bits tell the scalar type + * Most-significant 4 bits specify repeated/required/packed etc. + */ + +typedef uint_least8_t pb_type_t; + +/**** Field data types ****/ + +/* Numeric types */ +#define PB_LTYPE_VARINT 0x00 /* int32, int64, enum, bool */ +#define PB_LTYPE_UVARINT 0x01 /* uint32, uint64 */ +#define PB_LTYPE_SVARINT 0x02 /* sint32, sint64 */ +#define PB_LTYPE_FIXED32 0x03 /* fixed32, sfixed32, float */ +#define PB_LTYPE_FIXED64 0x04 /* fixed64, sfixed64, double */ + +/* Marker for last packable field type. */ +#define PB_LTYPE_LAST_PACKABLE 0x04 + +/* Byte array with pre-allocated buffer. + * data_size is the length of the allocated PB_BYTES_ARRAY structure. */ +#define PB_LTYPE_BYTES 0x05 + +/* String with pre-allocated buffer. + * data_size is the maximum length. */ +#define PB_LTYPE_STRING 0x06 + +/* Submessage + * submsg_fields is pointer to field descriptions */ +#define PB_LTYPE_SUBMESSAGE 0x07 + +/* Extension pseudo-field + * The field contains a pointer to pb_extension_t */ +#define PB_LTYPE_EXTENSION 0x08 + +/* Byte array with inline, pre-allocated byffer. + * data_size is the length of the inline, allocated buffer. + * This differs from PB_LTYPE_BYTES by defining the element as + * pb_byte_t[data_size] rather than pb_bytes_array_t. */ +#define PB_LTYPE_FIXED_LENGTH_BYTES 0x09 + +/* Number of declared LTYPES */ +#define PB_LTYPES_COUNT 0x0A +#define PB_LTYPE_MASK 0x0F + +/**** Field repetition rules ****/ + +#define PB_HTYPE_REQUIRED 0x00 +#define PB_HTYPE_OPTIONAL 0x10 +#define PB_HTYPE_REPEATED 0x20 +#define PB_HTYPE_ONEOF 0x30 +#define PB_HTYPE_MASK 0x30 + +/**** Field allocation types ****/ + +#define PB_ATYPE_STATIC 0x00 +#define PB_ATYPE_POINTER 0x80 +#define PB_ATYPE_CALLBACK 0x40 +#define PB_ATYPE_MASK 0xC0 + +#define PB_ATYPE(x) ((x) & PB_ATYPE_MASK) +#define PB_HTYPE(x) ((x) & PB_HTYPE_MASK) +#define PB_LTYPE(x) ((x) & PB_LTYPE_MASK) + +/* Data type used for storing sizes of struct fields + * and array counts. + */ +#if defined(PB_FIELD_32BIT) + typedef uint32_t pb_size_t; + typedef int32_t pb_ssize_t; +#elif defined(PB_FIELD_16BIT) + typedef uint_least16_t pb_size_t; + typedef int_least16_t pb_ssize_t; +#else + typedef uint_least8_t pb_size_t; + typedef int_least8_t pb_ssize_t; +#endif +#define PB_SIZE_MAX ((pb_size_t)-1) + +/* Data type for storing encoded data and other byte streams. + * This typedef exists to support platforms where uint8_t does not exist. + * You can regard it as equivalent on uint8_t on other platforms. + */ +typedef uint_least8_t pb_byte_t; + +/* This structure is used in auto-generated constants + * to specify struct fields. + * You can change field sizes if you need structures + * larger than 256 bytes or field tags larger than 256. + * The compiler should complain if your .proto has such + * structures. Fix that by defining PB_FIELD_16BIT or + * PB_FIELD_32BIT. + */ +PB_PACKED_STRUCT_START +typedef struct pb_field_s pb_field_t; +struct pb_field_s { + pb_size_t tag; + pb_type_t type; + pb_size_t data_offset; /* Offset of field data, relative to previous field. */ + pb_ssize_t size_offset; /* Offset of array size or has-boolean, relative to data */ + pb_size_t data_size; /* Data size in bytes for a single item */ + pb_size_t array_size; /* Maximum number of entries in array */ + + /* Field definitions for submessage + * OR default value for all other non-array, non-callback types + * If null, then field will zeroed. */ + const void *ptr; +} pb_packed; +PB_PACKED_STRUCT_END + +/* Make sure that the standard integer types are of the expected sizes. + * Otherwise fixed32/fixed64 fields can break. + * + * If you get errors here, it probably means that your stdint.h is not + * correct for your platform. + */ +PB_STATIC_ASSERT(sizeof(int64_t) == 2 * sizeof(int32_t), INT64_T_WRONG_SIZE) +PB_STATIC_ASSERT(sizeof(uint64_t) == 2 * sizeof(uint32_t), UINT64_T_WRONG_SIZE) + +/* This structure is used for 'bytes' arrays. + * It has the number of bytes in the beginning, and after that an array. + * Note that actual structs used will have a different length of bytes array. + */ +#define PB_BYTES_ARRAY_T(n) struct { pb_size_t size; pb_byte_t bytes[n]; } +#define PB_BYTES_ARRAY_T_ALLOCSIZE(n) ((size_t)n + offsetof(pb_bytes_array_t, bytes)) + +struct pb_bytes_array_s { + pb_size_t size; + pb_byte_t bytes[1]; +}; +typedef struct pb_bytes_array_s pb_bytes_array_t; + +/* This structure is used for giving the callback function. + * It is stored in the message structure and filled in by the method that + * calls pb_decode. + * + * The decoding callback will be given a limited-length stream + * If the wire type was string, the length is the length of the string. + * If the wire type was a varint/fixed32/fixed64, the length is the length + * of the actual value. + * The function may be called multiple times (especially for repeated types, + * but also otherwise if the message happens to contain the field multiple + * times.) + * + * The encoding callback will receive the actual output stream. + * It should write all the data in one call, including the field tag and + * wire type. It can write multiple fields. + * + * The callback can be null if you want to skip a field. + */ +typedef struct pb_istream_s pb_istream_t; +typedef struct pb_ostream_s pb_ostream_t; +typedef struct pb_callback_s pb_callback_t; +struct pb_callback_s { +#ifdef PB_OLD_CALLBACK_STYLE + /* Deprecated since nanopb-0.2.1 */ + union { + bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void *arg); + bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, const void *arg); + } funcs; +#else + /* New function signature, which allows modifying arg contents in callback. */ + union { + bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void **arg); + bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, void * const *arg); + } funcs; +#endif + + /* Free arg for use by callback */ + void *arg; +}; + +/* Wire types. Library user needs these only in encoder callbacks. */ +typedef enum { + PB_WT_VARINT = 0, + PB_WT_64BIT = 1, + PB_WT_STRING = 2, + PB_WT_32BIT = 5 +} pb_wire_type_t; + +/* Structure for defining the handling of unknown/extension fields. + * Usually the pb_extension_type_t structure is automatically generated, + * while the pb_extension_t structure is created by the user. However, + * if you want to catch all unknown fields, you can also create a custom + * pb_extension_type_t with your own callback. + */ +typedef struct pb_extension_type_s pb_extension_type_t; +typedef struct pb_extension_s pb_extension_t; +struct pb_extension_type_s { + /* Called for each unknown field in the message. + * If you handle the field, read off all of its data and return true. + * If you do not handle the field, do not read anything and return true. + * If you run into an error, return false. + * Set to NULL for default handler. + */ + bool (*decode)(pb_istream_t *stream, pb_extension_t *extension, + uint32_t tag, pb_wire_type_t wire_type); + + /* Called once after all regular fields have been encoded. + * If you have something to write, do so and return true. + * If you do not have anything to write, just return true. + * If you run into an error, return false. + * Set to NULL for default handler. + */ + bool (*encode)(pb_ostream_t *stream, const pb_extension_t *extension); + + /* Free field for use by the callback. */ + const void *arg; +}; + +struct pb_extension_s { + /* Type describing the extension field. Usually you'll initialize + * this to a pointer to the automatically generated structure. */ + const pb_extension_type_t *type; + + /* Destination for the decoded data. This must match the datatype + * of the extension field. */ + void *dest; + + /* Pointer to the next extension handler, or NULL. + * If this extension does not match a field, the next handler is + * automatically called. */ + pb_extension_t *next; + + /* The decoder sets this to true if the extension was found. + * Ignored for encoding. */ + bool found; +}; + +/* Memory allocation functions to use. You can define pb_realloc and + * pb_free to custom functions if you want. */ +#ifdef PB_ENABLE_MALLOC +# ifndef pb_realloc +# define pb_realloc(ptr, size) realloc(ptr, size) +# endif +# ifndef pb_free +# define pb_free(ptr) free(ptr) +# endif +#endif + +/* This is used to inform about need to regenerate .pb.h/.pb.c files. */ +#define PB_PROTO_HEADER_VERSION 30 + +/* These macros are used to declare pb_field_t's in the constant array. */ +/* Size of a structure member, in bytes. */ +#define pb_membersize(st, m) (sizeof ((st*)0)->m) +/* Number of entries in an array. */ +#define pb_arraysize(st, m) (pb_membersize(st, m) / pb_membersize(st, m[0])) +/* Delta from start of one member to the start of another member. */ +#define pb_delta(st, m1, m2) ((int)offsetof(st, m1) - (int)offsetof(st, m2)) +/* Marks the end of the field list */ +#define PB_LAST_FIELD {0,(pb_type_t) 0,0,0,0,0,0} + +/* Macros for filling in the data_offset field */ +/* data_offset for first field in a message */ +#define PB_DATAOFFSET_FIRST(st, m1, m2) (offsetof(st, m1)) +/* data_offset for subsequent fields */ +#define PB_DATAOFFSET_OTHER(st, m1, m2) (offsetof(st, m1) - offsetof(st, m2) - pb_membersize(st, m2)) +/* data offset for subsequent fields inside an union (oneof) */ +#define PB_DATAOFFSET_UNION(st, m1, m2) (PB_SIZE_MAX) +/* Choose first/other based on m1 == m2 (deprecated, remains for backwards compatibility) */ +#define PB_DATAOFFSET_CHOOSE(st, m1, m2) (int)(offsetof(st, m1) == offsetof(st, m2) \ + ? PB_DATAOFFSET_FIRST(st, m1, m2) \ + : PB_DATAOFFSET_OTHER(st, m1, m2)) + +/* Required fields are the simplest. They just have delta (padding) from + * previous field end, and the size of the field. Pointer is used for + * submessages and default values. + */ +#define PB_REQUIRED_STATIC(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_REQUIRED | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +/* Optional fields add the delta to the has_ variable. */ +#define PB_OPTIONAL_STATIC(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_OPTIONAL | ltype, \ + fd, \ + pb_delta(st, has_ ## m, m), \ + pb_membersize(st, m), 0, ptr} + +#define PB_SINGULAR_STATIC(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_OPTIONAL | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +/* Repeated fields have a _count field and also the maximum number of entries. */ +#define PB_REPEATED_STATIC(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_REPEATED | ltype, \ + fd, \ + pb_delta(st, m ## _count, m), \ + pb_membersize(st, m[0]), \ + pb_arraysize(st, m), ptr} + +/* Allocated fields carry the size of the actual data, not the pointer */ +#define PB_REQUIRED_POINTER(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_REQUIRED | ltype, \ + fd, 0, pb_membersize(st, m[0]), 0, ptr} + +/* Optional fields don't need a has_ variable, as information would be redundant */ +#define PB_OPTIONAL_POINTER(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_OPTIONAL | ltype, \ + fd, 0, pb_membersize(st, m[0]), 0, ptr} + +/* Same as optional fields*/ +#define PB_SINGULAR_POINTER(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_OPTIONAL | ltype, \ + fd, 0, pb_membersize(st, m[0]), 0, ptr} + +/* Repeated fields have a _count field and a pointer to array of pointers */ +#define PB_REPEATED_POINTER(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_REPEATED | ltype, \ + fd, pb_delta(st, m ## _count, m), \ + pb_membersize(st, m[0]), 0, ptr} + +/* Callbacks are much like required fields except with special datatype. */ +#define PB_REQUIRED_CALLBACK(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_CALLBACK | PB_HTYPE_REQUIRED | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +#define PB_OPTIONAL_CALLBACK(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_CALLBACK | PB_HTYPE_OPTIONAL | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +#define PB_SINGULAR_CALLBACK(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_CALLBACK | PB_HTYPE_OPTIONAL | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +#define PB_REPEATED_CALLBACK(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_CALLBACK | PB_HTYPE_REPEATED | ltype, \ + fd, 0, pb_membersize(st, m), 0, ptr} + +/* Optional extensions don't have the has_ field, as that would be redundant. + * Furthermore, the combination of OPTIONAL without has_ field is used + * for indicating proto3 style fields. Extensions exist in proto2 mode only, + * so they should be encoded according to proto2 rules. To avoid the conflict, + * extensions are marked as REQUIRED instead. + */ +#define PB_OPTEXT_STATIC(tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_REQUIRED | ltype, \ + 0, \ + 0, \ + pb_membersize(st, m), 0, ptr} + +#define PB_OPTEXT_POINTER(tag, st, m, fd, ltype, ptr) \ + PB_OPTIONAL_POINTER(tag, st, m, fd, ltype, ptr) + +#define PB_OPTEXT_CALLBACK(tag, st, m, fd, ltype, ptr) \ + PB_OPTIONAL_CALLBACK(tag, st, m, fd, ltype, ptr) + +/* The mapping from protobuf types to LTYPEs is done using these macros. */ +#define PB_LTYPE_MAP_BOOL PB_LTYPE_VARINT +#define PB_LTYPE_MAP_BYTES PB_LTYPE_BYTES +#define PB_LTYPE_MAP_DOUBLE PB_LTYPE_FIXED64 +#define PB_LTYPE_MAP_ENUM PB_LTYPE_VARINT +#define PB_LTYPE_MAP_UENUM PB_LTYPE_UVARINT +#define PB_LTYPE_MAP_FIXED32 PB_LTYPE_FIXED32 +#define PB_LTYPE_MAP_FIXED64 PB_LTYPE_FIXED64 +#define PB_LTYPE_MAP_FLOAT PB_LTYPE_FIXED32 +#define PB_LTYPE_MAP_INT32 PB_LTYPE_VARINT +#define PB_LTYPE_MAP_INT64 PB_LTYPE_VARINT +#define PB_LTYPE_MAP_MESSAGE PB_LTYPE_SUBMESSAGE +#define PB_LTYPE_MAP_SFIXED32 PB_LTYPE_FIXED32 +#define PB_LTYPE_MAP_SFIXED64 PB_LTYPE_FIXED64 +#define PB_LTYPE_MAP_SINT32 PB_LTYPE_SVARINT +#define PB_LTYPE_MAP_SINT64 PB_LTYPE_SVARINT +#define PB_LTYPE_MAP_STRING PB_LTYPE_STRING +#define PB_LTYPE_MAP_UINT32 PB_LTYPE_UVARINT +#define PB_LTYPE_MAP_UINT64 PB_LTYPE_UVARINT +#define PB_LTYPE_MAP_EXTENSION PB_LTYPE_EXTENSION +#define PB_LTYPE_MAP_FIXED_LENGTH_BYTES PB_LTYPE_FIXED_LENGTH_BYTES + +/* This is the actual macro used in field descriptions. + * It takes these arguments: + * - Field tag number + * - Field type: BOOL, BYTES, DOUBLE, ENUM, UENUM, FIXED32, FIXED64, + * FLOAT, INT32, INT64, MESSAGE, SFIXED32, SFIXED64 + * SINT32, SINT64, STRING, UINT32, UINT64 or EXTENSION + * - Field rules: REQUIRED, OPTIONAL or REPEATED + * - Allocation: STATIC, CALLBACK or POINTER + * - Placement: FIRST or OTHER, depending on if this is the first field in structure. + * - Message name + * - Field name + * - Previous field name (or field name again for first field) + * - Pointer to default value or submsg fields. + */ + +#define PB_FIELD(tag, type, rules, allocation, placement, message, field, prevfield, ptr) \ + PB_ ## rules ## _ ## allocation(tag, message, field, \ + PB_DATAOFFSET_ ## placement(message, field, prevfield), \ + PB_LTYPE_MAP_ ## type, ptr) + +/* Field description for oneof fields. This requires taking into account the + * union name also, that's why a separate set of macros is needed. + */ +#define PB_ONEOF_STATIC(u, tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_ONEOF | ltype, \ + fd, pb_delta(st, which_ ## u, u.m), \ + pb_membersize(st, u.m), 0, ptr} + +#define PB_ONEOF_POINTER(u, tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_ONEOF | ltype, \ + fd, pb_delta(st, which_ ## u, u.m), \ + pb_membersize(st, u.m[0]), 0, ptr} + +#define PB_ONEOF_FIELD(union_name, tag, type, rules, allocation, placement, message, field, prevfield, ptr) \ + PB_ONEOF_ ## allocation(union_name, tag, message, field, \ + PB_DATAOFFSET_ ## placement(message, union_name.field, prevfield), \ + PB_LTYPE_MAP_ ## type, ptr) + +#define PB_ANONYMOUS_ONEOF_STATIC(u, tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_STATIC | PB_HTYPE_ONEOF | ltype, \ + fd, pb_delta(st, which_ ## u, m), \ + pb_membersize(st, m), 0, ptr} + +#define PB_ANONYMOUS_ONEOF_POINTER(u, tag, st, m, fd, ltype, ptr) \ + {tag, PB_ATYPE_POINTER | PB_HTYPE_ONEOF | ltype, \ + fd, pb_delta(st, which_ ## u, m), \ + pb_membersize(st, m[0]), 0, ptr} + +#define PB_ANONYMOUS_ONEOF_FIELD(union_name, tag, type, rules, allocation, placement, message, field, prevfield, ptr) \ + PB_ANONYMOUS_ONEOF_ ## allocation(union_name, tag, message, field, \ + PB_DATAOFFSET_ ## placement(message, field, prevfield), \ + PB_LTYPE_MAP_ ## type, ptr) + +/* These macros are used for giving out error messages. + * They are mostly a debugging aid; the main error information + * is the true/false return value from functions. + * Some code space can be saved by disabling the error + * messages if not used. + * + * PB_SET_ERROR() sets the error message if none has been set yet. + * msg must be a constant string literal. + * PB_GET_ERROR() always returns a pointer to a string. + * PB_RETURN_ERROR() sets the error and returns false from current + * function. + */ +#ifdef PB_NO_ERRMSG +#define PB_SET_ERROR(stream, msg) PB_UNUSED(stream) +#define PB_GET_ERROR(stream) "(errmsg disabled)" +#else +#define PB_SET_ERROR(stream, msg) (stream->errmsg = (stream)->errmsg ? (stream)->errmsg : (msg)) +#define PB_GET_ERROR(stream) ((stream)->errmsg ? (stream)->errmsg : "(none)") +#endif + +#define PB_RETURN_ERROR(stream, msg) return PB_SET_ERROR(stream, msg), false + +#endif diff --git a/libs/nanopb/pb_common.c b/libs/nanopb/pb_common.c new file mode 100644 index 00000000..4fb7186b --- /dev/null +++ b/libs/nanopb/pb_common.c @@ -0,0 +1,97 @@ +/* pb_common.c: Common support functions for pb_encode.c and pb_decode.c. + * + * 2014 Petteri Aimonen + */ + +#include "pb_common.h" + +bool pb_field_iter_begin(pb_field_iter_t *iter, const pb_field_t *fields, void *dest_struct) +{ + iter->start = fields; + iter->pos = fields; + iter->required_field_index = 0; + iter->dest_struct = dest_struct; + iter->pData = (char*)dest_struct + iter->pos->data_offset; + iter->pSize = (char*)iter->pData + iter->pos->size_offset; + + return (iter->pos->tag != 0); +} + +bool pb_field_iter_next(pb_field_iter_t *iter) +{ + const pb_field_t *prev_field = iter->pos; + + if (prev_field->tag == 0) + { + /* Handle empty message types, where the first field is already the terminator. + * In other cases, the iter->pos never points to the terminator. */ + return false; + } + + iter->pos++; + + if (iter->pos->tag == 0) + { + /* Wrapped back to beginning, reinitialize */ + (void)pb_field_iter_begin(iter, iter->start, iter->dest_struct); + return false; + } + else + { + /* Increment the pointers based on previous field size */ + size_t prev_size = prev_field->data_size; + + if (PB_HTYPE(prev_field->type) == PB_HTYPE_ONEOF && + PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF && + iter->pos->data_offset == PB_SIZE_MAX) + { + /* Don't advance pointers inside unions */ + return true; + } + else if (PB_ATYPE(prev_field->type) == PB_ATYPE_STATIC && + PB_HTYPE(prev_field->type) == PB_HTYPE_REPEATED) + { + /* In static arrays, the data_size tells the size of a single entry and + * array_size is the number of entries */ + prev_size *= prev_field->array_size; + } + else if (PB_ATYPE(prev_field->type) == PB_ATYPE_POINTER) + { + /* Pointer fields always have a constant size in the main structure. + * The data_size only applies to the dynamically allocated area. */ + prev_size = sizeof(void*); + } + + if (PB_HTYPE(prev_field->type) == PB_HTYPE_REQUIRED) + { + /* Count the required fields, in order to check their presence in the + * decoder. */ + iter->required_field_index++; + } + + iter->pData = (char*)iter->pData + prev_size + iter->pos->data_offset; + iter->pSize = (char*)iter->pData + iter->pos->size_offset; + return true; + } +} + +bool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag) +{ + const pb_field_t *start = iter->pos; + + do { + if (iter->pos->tag == tag && + PB_LTYPE(iter->pos->type) != PB_LTYPE_EXTENSION) + { + /* Found the wanted field */ + return true; + } + + (void)pb_field_iter_next(iter); + } while (iter->pos != start); + + /* Searched all the way back to start, and found nothing. */ + return false; +} + + diff --git a/libs/nanopb/pb_common.h b/libs/nanopb/pb_common.h new file mode 100644 index 00000000..60b3d374 --- /dev/null +++ b/libs/nanopb/pb_common.h @@ -0,0 +1,42 @@ +/* pb_common.h: Common support functions for pb_encode.c and pb_decode.c. + * These functions are rarely needed by applications directly. + */ + +#ifndef PB_COMMON_H_INCLUDED +#define PB_COMMON_H_INCLUDED + +#include "pb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Iterator for pb_field_t list */ +struct pb_field_iter_s { + const pb_field_t *start; /* Start of the pb_field_t array */ + const pb_field_t *pos; /* Current position of the iterator */ + unsigned required_field_index; /* Zero-based index that counts only the required fields */ + void *dest_struct; /* Pointer to start of the structure */ + void *pData; /* Pointer to current field value */ + void *pSize; /* Pointer to count/has field */ +}; +typedef struct pb_field_iter_s pb_field_iter_t; + +/* Initialize the field iterator structure to beginning. + * Returns false if the message type is empty. */ +bool pb_field_iter_begin(pb_field_iter_t *iter, const pb_field_t *fields, void *dest_struct); + +/* Advance the iterator to the next field. + * Returns false when the iterator wraps back to the first field. */ +bool pb_field_iter_next(pb_field_iter_t *iter); + +/* Advance the iterator until it points at a field with the given tag. + * Returns false if no such field exists. */ +bool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif + diff --git a/libs/nanopb/pb_decode.c b/libs/nanopb/pb_decode.c new file mode 100644 index 00000000..06d766af --- /dev/null +++ b/libs/nanopb/pb_decode.c @@ -0,0 +1,1388 @@ +/* pb_decode.c -- decode a protobuf using minimal resources + * + * 2011 Petteri Aimonen + */ + +/* Use the GCC warn_unused_result attribute to check that all return values + * are propagated correctly. On other compilers and gcc before 3.4.0 just + * ignore the annotation. + */ +#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4) + #define checkreturn +#else + #define checkreturn __attribute__((warn_unused_result)) +#endif + +#include "pb.h" +#include "pb_decode.h" +#include "pb_common.h" + +/************************************** + * Declarations internal to this file * + **************************************/ + +typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn; + +static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count); +static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size); +static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); +static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); +static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter); +static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension); +static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type); +static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter); +static bool checkreturn find_extension_field(pb_field_iter_t *iter); +static void pb_field_set_to_default(pb_field_iter_t *iter); +static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct); +static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest); +static bool checkreturn pb_skip_varint(pb_istream_t *stream); +static bool checkreturn pb_skip_string(pb_istream_t *stream); + +#ifdef PB_ENABLE_MALLOC +static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size); +static bool checkreturn pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter); +static void pb_release_single_field(const pb_field_iter_t *iter); +#endif + +/* --- Function pointers to field decoders --- + * Order in the array must match pb_action_t LTYPE numbering. + */ +static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = { + &pb_dec_varint, + &pb_dec_uvarint, + &pb_dec_svarint, + &pb_dec_fixed32, + &pb_dec_fixed64, + + &pb_dec_bytes, + &pb_dec_string, + &pb_dec_submessage, + NULL, /* extensions */ + &pb_dec_fixed_length_bytes +}; + +/******************************* + * pb_istream_t implementation * + *******************************/ + +static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count) +{ + size_t i; + const pb_byte_t *source = (const pb_byte_t*)stream->state; + stream->state = (pb_byte_t*)stream->state + count; + + if (buf != NULL) + { + for (i = 0; i < count; i++) + buf[i] = source[i]; + } + + return true; +} + +bool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count) +{ +#ifndef PB_BUFFER_ONLY + if (buf == NULL && stream->callback != buf_read) + { + /* Skip input bytes */ + pb_byte_t tmp[16]; + while (count > 16) + { + if (!pb_read(stream, tmp, 16)) + return false; + + count -= 16; + } + + return pb_read(stream, tmp, count); + } +#endif + + if (stream->bytes_left < count) + PB_RETURN_ERROR(stream, "end-of-stream"); + +#ifndef PB_BUFFER_ONLY + if (!stream->callback(stream, buf, count)) + PB_RETURN_ERROR(stream, "io error"); +#else + if (!buf_read(stream, buf, count)) + return false; +#endif + + stream->bytes_left -= count; + return true; +} + +/* Read a single byte from input stream. buf may not be NULL. + * This is an optimization for the varint decoding. */ +static bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf) +{ + if (stream->bytes_left == 0) + PB_RETURN_ERROR(stream, "end-of-stream"); + +#ifndef PB_BUFFER_ONLY + if (!stream->callback(stream, buf, 1)) + PB_RETURN_ERROR(stream, "io error"); +#else + *buf = *(const pb_byte_t*)stream->state; + stream->state = (pb_byte_t*)stream->state + 1; +#endif + + stream->bytes_left--; + + return true; +} + +pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize) +{ + pb_istream_t stream; + /* Cast away the const from buf without a compiler error. We are + * careful to use it only in a const manner in the callbacks. + */ + union { + void *state; + const void *c_state; + } state; +#ifdef PB_BUFFER_ONLY + stream.callback = NULL; +#else + stream.callback = &buf_read; +#endif + state.c_state = buf; + stream.state = state.state; + stream.bytes_left = bufsize; +#ifndef PB_NO_ERRMSG + stream.errmsg = NULL; +#endif + return stream; +} + +/******************** + * Helper functions * + ********************/ + +bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest) +{ + pb_byte_t byte; + uint32_t result; + + if (!pb_readbyte(stream, &byte)) + return false; + + if ((byte & 0x80) == 0) + { + /* Quick case, 1 byte value */ + result = byte; + } + else + { + /* Multibyte case */ + uint_fast8_t bitpos = 7; + result = byte & 0x7F; + + do + { + if (bitpos >= 32) + PB_RETURN_ERROR(stream, "varint overflow"); + + if (!pb_readbyte(stream, &byte)) + return false; + + result |= (uint32_t)(byte & 0x7F) << bitpos; + bitpos = (uint_fast8_t)(bitpos + 7); + } while (byte & 0x80); + } + + *dest = result; + return true; +} + +bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest) +{ + pb_byte_t byte; + uint_fast8_t bitpos = 0; + uint64_t result = 0; + + do + { + if (bitpos >= 64) + PB_RETURN_ERROR(stream, "varint overflow"); + + if (!pb_readbyte(stream, &byte)) + return false; + + result |= (uint64_t)(byte & 0x7F) << bitpos; + bitpos = (uint_fast8_t)(bitpos + 7); + } while (byte & 0x80); + + *dest = result; + return true; +} + +bool checkreturn pb_skip_varint(pb_istream_t *stream) +{ + pb_byte_t byte; + do + { + if (!pb_read(stream, &byte, 1)) + return false; + } while (byte & 0x80); + return true; +} + +bool checkreturn pb_skip_string(pb_istream_t *stream) +{ + uint32_t length; + if (!pb_decode_varint32(stream, &length)) + return false; + + return pb_read(stream, NULL, length); +} + +bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof) +{ + uint32_t temp; + *eof = false; + *wire_type = (pb_wire_type_t) 0; + *tag = 0; + + if (!pb_decode_varint32(stream, &temp)) + { + if (stream->bytes_left == 0) + *eof = true; + + return false; + } + + if (temp == 0) + { + *eof = true; /* Special feature: allow 0-terminated messages. */ + return false; + } + + *tag = temp >> 3; + *wire_type = (pb_wire_type_t)(temp & 7); + return true; +} + +bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type) +{ + switch (wire_type) + { + case PB_WT_VARINT: return pb_skip_varint(stream); + case PB_WT_64BIT: return pb_read(stream, NULL, 8); + case PB_WT_STRING: return pb_skip_string(stream); + case PB_WT_32BIT: return pb_read(stream, NULL, 4); + default: PB_RETURN_ERROR(stream, "invalid wire_type"); + } +} + +/* Read a raw value to buffer, for the purpose of passing it to callback as + * a substream. Size is maximum size on call, and actual size on return. + */ +static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size) +{ + size_t max_size = *size; + switch (wire_type) + { + case PB_WT_VARINT: + *size = 0; + do + { + (*size)++; + if (*size > max_size) return false; + if (!pb_read(stream, buf, 1)) return false; + } while (*buf++ & 0x80); + return true; + + case PB_WT_64BIT: + *size = 8; + return pb_read(stream, buf, 8); + + case PB_WT_32BIT: + *size = 4; + return pb_read(stream, buf, 4); + + default: PB_RETURN_ERROR(stream, "invalid wire_type"); + } +} + +/* Decode string length from stream and return a substream with limited length. + * Remember to close the substream using pb_close_string_substream(). + */ +bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream) +{ + uint32_t size; + if (!pb_decode_varint32(stream, &size)) + return false; + + *substream = *stream; + if (substream->bytes_left < size) + PB_RETURN_ERROR(stream, "parent stream too short"); + + substream->bytes_left = size; + stream->bytes_left -= size; + return true; +} + +bool checkreturn pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream) +{ + if (substream->bytes_left) { + if (!pb_read(substream, NULL, substream->bytes_left)) + return false; + } + + stream->state = substream->state; + +#ifndef PB_NO_ERRMSG + stream->errmsg = substream->errmsg; +#endif + return true; +} + +/************************* + * Decode a single field * + *************************/ + +static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) +{ + pb_type_t type; + pb_decoder_t func; + + type = iter->pos->type; + func = PB_DECODERS[PB_LTYPE(type)]; + + switch (PB_HTYPE(type)) + { + case PB_HTYPE_REQUIRED: + return func(stream, iter->pos, iter->pData); + + case PB_HTYPE_OPTIONAL: + if (iter->pSize != iter->pData) + *(bool*)iter->pSize = true; + return func(stream, iter->pos, iter->pData); + + case PB_HTYPE_REPEATED: + if (wire_type == PB_WT_STRING + && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE) + { + /* Packed array */ + bool status = true; + pb_size_t *size = (pb_size_t*)iter->pSize; + pb_istream_t substream; + if (!pb_make_string_substream(stream, &substream)) + return false; + + while (substream.bytes_left > 0 && *size < iter->pos->array_size) + { + void *pItem = (char*)iter->pData + iter->pos->data_size * (*size); + if (!func(&substream, iter->pos, pItem)) + { + status = false; + break; + } + (*size)++; + } + + if (substream.bytes_left != 0) + PB_RETURN_ERROR(stream, "array overflow"); + if (!pb_close_string_substream(stream, &substream)) + return false; + + return status; + } + else + { + /* Repeated field */ + pb_size_t *size = (pb_size_t*)iter->pSize; + void *pItem = (char*)iter->pData + iter->pos->data_size * (*size); + if (*size >= iter->pos->array_size) + PB_RETURN_ERROR(stream, "array overflow"); + + (*size)++; + return func(stream, iter->pos, pItem); + } + + case PB_HTYPE_ONEOF: + *(pb_size_t*)iter->pSize = iter->pos->tag; + if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE) + { + /* We memset to zero so that any callbacks are set to NULL. + * Then set any default values. */ + memset(iter->pData, 0, iter->pos->data_size); + pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData); + } + return func(stream, iter->pos, iter->pData); + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } +} + +#ifdef PB_ENABLE_MALLOC +/* Allocate storage for the field and store the pointer at iter->pData. + * array_size is the number of entries to reserve in an array. + * Zero size is not allowed, use pb_free() for releasing. + */ +static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size) +{ + void *ptr = *(void**)pData; + + if (data_size == 0 || array_size == 0) + PB_RETURN_ERROR(stream, "invalid size"); + + /* Check for multiplication overflows. + * This code avoids the costly division if the sizes are small enough. + * Multiplication is safe as long as only half of bits are set + * in either multiplicand. + */ + { + const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4); + if (data_size >= check_limit || array_size >= check_limit) + { + const size_t size_max = (size_t)-1; + if (size_max / array_size < data_size) + { + PB_RETURN_ERROR(stream, "size too large"); + } + } + } + + /* Allocate new or expand previous allocation */ + /* Note: on failure the old pointer will remain in the structure, + * the message must be freed by caller also on error return. */ + ptr = pb_realloc(ptr, array_size * data_size); + if (ptr == NULL) + PB_RETURN_ERROR(stream, "realloc failed"); + + *(void**)pData = ptr; + return true; +} + +/* Clear a newly allocated item in case it contains a pointer, or is a submessage. */ +static void initialize_pointer_field(void *pItem, pb_field_iter_t *iter) +{ + if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING || + PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES) + { + *(void**)pItem = NULL; + } + else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE) + { + pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem); + } +} +#endif + +static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) +{ +#ifndef PB_ENABLE_MALLOC + PB_UNUSED(wire_type); + PB_UNUSED(iter); + PB_RETURN_ERROR(stream, "no malloc support"); +#else + pb_type_t type; + pb_decoder_t func; + + type = iter->pos->type; + func = PB_DECODERS[PB_LTYPE(type)]; + + switch (PB_HTYPE(type)) + { + case PB_HTYPE_REQUIRED: + case PB_HTYPE_OPTIONAL: + case PB_HTYPE_ONEOF: + if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE && + *(void**)iter->pData != NULL) + { + /* Duplicate field, have to release the old allocation first. */ + pb_release_single_field(iter); + } + + if (PB_HTYPE(type) == PB_HTYPE_ONEOF) + { + *(pb_size_t*)iter->pSize = iter->pos->tag; + } + + if (PB_LTYPE(type) == PB_LTYPE_STRING || + PB_LTYPE(type) == PB_LTYPE_BYTES) + { + return func(stream, iter->pos, iter->pData); + } + else + { + if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1)) + return false; + + initialize_pointer_field(*(void**)iter->pData, iter); + return func(stream, iter->pos, *(void**)iter->pData); + } + + case PB_HTYPE_REPEATED: + if (wire_type == PB_WT_STRING + && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE) + { + /* Packed array, multiple items come in at once. */ + bool status = true; + pb_size_t *size = (pb_size_t*)iter->pSize; + size_t allocated_size = *size; + void *pItem; + pb_istream_t substream; + + if (!pb_make_string_substream(stream, &substream)) + return false; + + while (substream.bytes_left) + { + if ((size_t)*size + 1 > allocated_size) + { + /* Allocate more storage. This tries to guess the + * number of remaining entries. Round the division + * upwards. */ + allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1; + + if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size)) + { + status = false; + break; + } + } + + /* Decode the array entry */ + pItem = *(char**)iter->pData + iter->pos->data_size * (*size); + initialize_pointer_field(pItem, iter); + if (!func(&substream, iter->pos, pItem)) + { + status = false; + break; + } + + if (*size == PB_SIZE_MAX) + { +#ifndef PB_NO_ERRMSG + stream->errmsg = "too many array entries"; +#endif + status = false; + break; + } + + (*size)++; + } + if (!pb_close_string_substream(stream, &substream)) + return false; + + return status; + } + else + { + /* Normal repeated field, i.e. only one item at a time. */ + pb_size_t *size = (pb_size_t*)iter->pSize; + void *pItem; + + if (*size == PB_SIZE_MAX) + PB_RETURN_ERROR(stream, "too many array entries"); + + (*size)++; + if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size)) + return false; + + pItem = *(char**)iter->pData + iter->pos->data_size * (*size - 1); + initialize_pointer_field(pItem, iter); + return func(stream, iter->pos, pItem); + } + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } +#endif +} + +static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) +{ + pb_callback_t *pCallback = (pb_callback_t*)iter->pData; + +#ifdef PB_OLD_CALLBACK_STYLE + void *arg = pCallback->arg; +#else + void **arg = &(pCallback->arg); +#endif + + if (pCallback->funcs.decode == NULL) + return pb_skip_field(stream, wire_type); + + if (wire_type == PB_WT_STRING) + { + pb_istream_t substream; + + if (!pb_make_string_substream(stream, &substream)) + return false; + + do + { + if (!pCallback->funcs.decode(&substream, iter->pos, arg)) + PB_RETURN_ERROR(stream, "callback failed"); + } while (substream.bytes_left); + + if (!pb_close_string_substream(stream, &substream)) + return false; + + return true; + } + else + { + /* Copy the single scalar value to stack. + * This is required so that we can limit the stream length, + * which in turn allows to use same callback for packed and + * not-packed fields. */ + pb_istream_t substream; + pb_byte_t buffer[10]; + size_t size = sizeof(buffer); + + if (!read_raw_value(stream, wire_type, buffer, &size)) + return false; + substream = pb_istream_from_buffer(buffer, size); + + return pCallback->funcs.decode(&substream, iter->pos, arg); + } +} + +static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter) +{ +#ifdef PB_ENABLE_MALLOC + /* When decoding an oneof field, check if there is old data that must be + * released first. */ + if (PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF) + { + if (!pb_release_union_field(stream, iter)) + return false; + } +#endif + + switch (PB_ATYPE(iter->pos->type)) + { + case PB_ATYPE_STATIC: + return decode_static_field(stream, wire_type, iter); + + case PB_ATYPE_POINTER: + return decode_pointer_field(stream, wire_type, iter); + + case PB_ATYPE_CALLBACK: + return decode_callback_field(stream, wire_type, iter); + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } +} + +static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension) +{ + /* Fake a field iterator for the extension field. + * It is not actually safe to advance this iterator, but decode_field + * will not even try to. */ + const pb_field_t *field = (const pb_field_t*)extension->type->arg; + (void)pb_field_iter_begin(iter, field, extension->dest); + iter->pData = extension->dest; + iter->pSize = &extension->found; + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + { + /* For pointer extensions, the pointer is stored directly + * in the extension structure. This avoids having an extra + * indirection. */ + iter->pData = &extension->dest; + } +} + +/* Default handler for extension fields. Expects a pb_field_t structure + * in extension->type->arg. */ +static bool checkreturn default_extension_decoder(pb_istream_t *stream, + pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type) +{ + const pb_field_t *field = (const pb_field_t*)extension->type->arg; + pb_field_iter_t iter; + + if (field->tag != tag) + return true; + + iter_from_extension(&iter, extension); + extension->found = true; + return decode_field(stream, wire_type, &iter); +} + +/* Try to decode an unknown field as an extension field. Tries each extension + * decoder in turn, until one of them handles the field or loop ends. */ +static bool checkreturn decode_extension(pb_istream_t *stream, + uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter) +{ + pb_extension_t *extension = *(pb_extension_t* const *)iter->pData; + size_t pos = stream->bytes_left; + + while (extension != NULL && pos == stream->bytes_left) + { + bool status; + if (extension->type->decode) + status = extension->type->decode(stream, extension, tag, wire_type); + else + status = default_extension_decoder(stream, extension, tag, wire_type); + + if (!status) + return false; + + extension = extension->next; + } + + return true; +} + +/* Step through the iterator until an extension field is found or until all + * entries have been checked. There can be only one extension field per + * message. Returns false if no extension field is found. */ +static bool checkreturn find_extension_field(pb_field_iter_t *iter) +{ + const pb_field_t *start = iter->pos; + + do { + if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION) + return true; + (void)pb_field_iter_next(iter); + } while (iter->pos != start); + + return false; +} + +/* Initialize message fields to default values, recursively */ +static void pb_field_set_to_default(pb_field_iter_t *iter) +{ + pb_type_t type; + type = iter->pos->type; + + if (PB_LTYPE(type) == PB_LTYPE_EXTENSION) + { + pb_extension_t *ext = *(pb_extension_t* const *)iter->pData; + while (ext != NULL) + { + pb_field_iter_t ext_iter; + ext->found = false; + iter_from_extension(&ext_iter, ext); + pb_field_set_to_default(&ext_iter); + ext = ext->next; + } + } + else if (PB_ATYPE(type) == PB_ATYPE_STATIC) + { + bool init_data = true; + if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && iter->pSize != iter->pData) + { + /* Set has_field to false. Still initialize the optional field + * itself also. */ + *(bool*)iter->pSize = false; + } + else if (PB_HTYPE(type) == PB_HTYPE_REPEATED || + PB_HTYPE(type) == PB_HTYPE_ONEOF) + { + /* REPEATED: Set array count to 0, no need to initialize contents. + ONEOF: Set which_field to 0. */ + *(pb_size_t*)iter->pSize = 0; + init_data = false; + } + + if (init_data) + { + if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE) + { + /* Initialize submessage to defaults */ + pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, iter->pData); + } + else if (iter->pos->ptr != NULL) + { + /* Initialize to default value */ + memcpy(iter->pData, iter->pos->ptr, iter->pos->data_size); + } + else + { + /* Initialize to zeros */ + memset(iter->pData, 0, iter->pos->data_size); + } + } + } + else if (PB_ATYPE(type) == PB_ATYPE_POINTER) + { + /* Initialize the pointer to NULL. */ + *(void**)iter->pData = NULL; + + /* Initialize array count to 0. */ + if (PB_HTYPE(type) == PB_HTYPE_REPEATED || + PB_HTYPE(type) == PB_HTYPE_ONEOF) + { + *(pb_size_t*)iter->pSize = 0; + } + } + else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK) + { + /* Don't overwrite callback */ + } +} + +static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct) +{ + pb_field_iter_t iter; + + if (!pb_field_iter_begin(&iter, fields, dest_struct)) + return; /* Empty message type */ + + do + { + pb_field_set_to_default(&iter); + } while (pb_field_iter_next(&iter)); +} + +/********************* + * Decode all fields * + *********************/ + +bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) +{ + uint32_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 31) / 32] = {0, 0}; + const uint32_t allbits = ~(uint32_t)0; + uint32_t extension_range_start = 0; + pb_field_iter_t iter; + + /* Return value ignored, as empty message types will be correctly handled by + * pb_field_iter_find() anyway. */ + (void)pb_field_iter_begin(&iter, fields, dest_struct); + + while (stream->bytes_left) + { + uint32_t tag; + pb_wire_type_t wire_type; + bool eof; + + if (!pb_decode_tag(stream, &wire_type, &tag, &eof)) + { + if (eof) + break; + else + return false; + } + + if (!pb_field_iter_find(&iter, tag)) + { + /* No match found, check if it matches an extension. */ + if (tag >= extension_range_start) + { + if (!find_extension_field(&iter)) + extension_range_start = (uint32_t)-1; + else + extension_range_start = iter.pos->tag; + + if (tag >= extension_range_start) + { + size_t pos = stream->bytes_left; + + if (!decode_extension(stream, tag, wire_type, &iter)) + return false; + + if (pos != stream->bytes_left) + { + /* The field was handled */ + continue; + } + } + } + + /* No match found, skip data */ + if (!pb_skip_field(stream, wire_type)) + return false; + continue; + } + + if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED + && iter.required_field_index < PB_MAX_REQUIRED_FIELDS) + { + uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31)); + fields_seen[iter.required_field_index >> 5] |= tmp; + } + + if (!decode_field(stream, wire_type, &iter)) + return false; + } + + /* Check that all required fields were present. */ + { + /* First figure out the number of required fields by + * seeking to the end of the field array. Usually we + * are already close to end after decoding. + */ + unsigned req_field_count; + pb_type_t last_type; + unsigned i; + do { + req_field_count = iter.required_field_index; + last_type = iter.pos->type; + } while (pb_field_iter_next(&iter)); + + /* Fixup if last field was also required. */ + if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0) + req_field_count++; + + if (req_field_count > PB_MAX_REQUIRED_FIELDS) + req_field_count = PB_MAX_REQUIRED_FIELDS; + + if (req_field_count > 0) + { + /* Check the whole words */ + for (i = 0; i < (req_field_count >> 5); i++) + { + if (fields_seen[i] != allbits) + PB_RETURN_ERROR(stream, "missing required field"); + } + + /* Check the remaining bits (if any) */ + if ((req_field_count & 31) != 0) + { + if (fields_seen[req_field_count >> 5] != + (allbits >> (32 - (req_field_count & 31)))) + { + PB_RETURN_ERROR(stream, "missing required field"); + } + } + } + } + + return true; +} + +bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) +{ + bool status; + pb_message_set_to_defaults(fields, dest_struct); + status = pb_decode_noinit(stream, fields, dest_struct); + +#ifdef PB_ENABLE_MALLOC + if (!status) + pb_release(fields, dest_struct); +#endif + + return status; +} + +bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct) +{ + pb_istream_t substream; + bool status; + + if (!pb_make_string_substream(stream, &substream)) + return false; + + status = pb_decode(&substream, fields, dest_struct); + + if (!pb_close_string_substream(stream, &substream)) + return false; + return status; +} + +#ifdef PB_ENABLE_MALLOC +/* Given an oneof field, if there has already been a field inside this oneof, + * release it before overwriting with a different one. */ +static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter) +{ + pb_size_t old_tag = *(pb_size_t*)iter->pSize; /* Previous which_ value */ + pb_size_t new_tag = iter->pos->tag; /* New which_ value */ + + if (old_tag == 0) + return true; /* Ok, no old data in union */ + + if (old_tag == new_tag) + return true; /* Ok, old data is of same type => merge */ + + /* Release old data. The find can fail if the message struct contains + * invalid data. */ + if (!pb_field_iter_find(iter, old_tag)) + PB_RETURN_ERROR(stream, "invalid union tag"); + + pb_release_single_field(iter); + + /* Restore iterator to where it should be. + * This shouldn't fail unless the pb_field_t structure is corrupted. */ + if (!pb_field_iter_find(iter, new_tag)) + PB_RETURN_ERROR(stream, "iterator error"); + + return true; +} + +static void pb_release_single_field(const pb_field_iter_t *iter) +{ + pb_type_t type; + type = iter->pos->type; + + if (PB_HTYPE(type) == PB_HTYPE_ONEOF) + { + if (*(pb_size_t*)iter->pSize != iter->pos->tag) + return; /* This is not the current field in the union */ + } + + /* Release anything contained inside an extension or submsg. + * This has to be done even if the submsg itself is statically + * allocated. */ + if (PB_LTYPE(type) == PB_LTYPE_EXTENSION) + { + /* Release fields from all extensions in the linked list */ + pb_extension_t *ext = *(pb_extension_t**)iter->pData; + while (ext != NULL) + { + pb_field_iter_t ext_iter; + iter_from_extension(&ext_iter, ext); + pb_release_single_field(&ext_iter); + ext = ext->next; + } + } + else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE) + { + /* Release fields in submessage or submsg array */ + void *pItem = iter->pData; + pb_size_t count = 1; + + if (PB_ATYPE(type) == PB_ATYPE_POINTER) + { + pItem = *(void**)iter->pData; + } + + if (PB_HTYPE(type) == PB_HTYPE_REPEATED) + { + count = *(pb_size_t*)iter->pSize; + + if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size) + { + /* Protect against corrupted _count fields */ + count = iter->pos->array_size; + } + } + + if (pItem) + { + while (count--) + { + pb_release((const pb_field_t*)iter->pos->ptr, pItem); + pItem = (char*)pItem + iter->pos->data_size; + } + } + } + + if (PB_ATYPE(type) == PB_ATYPE_POINTER) + { + if (PB_HTYPE(type) == PB_HTYPE_REPEATED && + (PB_LTYPE(type) == PB_LTYPE_STRING || + PB_LTYPE(type) == PB_LTYPE_BYTES)) + { + /* Release entries in repeated string or bytes array */ + void **pItem = *(void***)iter->pData; + pb_size_t count = *(pb_size_t*)iter->pSize; + while (count--) + { + pb_free(*pItem); + *pItem++ = NULL; + } + } + + if (PB_HTYPE(type) == PB_HTYPE_REPEATED) + { + /* We are going to release the array, so set the size to 0 */ + *(pb_size_t*)iter->pSize = 0; + } + + /* Release main item */ + pb_free(*(void**)iter->pData); + *(void**)iter->pData = NULL; + } +} + +void pb_release(const pb_field_t fields[], void *dest_struct) +{ + pb_field_iter_t iter; + + if (!dest_struct) + return; /* Ignore NULL pointers, similar to free() */ + + if (!pb_field_iter_begin(&iter, fields, dest_struct)) + return; /* Empty message type */ + + do + { + pb_release_single_field(&iter); + } while (pb_field_iter_next(&iter)); +} +#endif + +/* Field decoders */ + +bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest) +{ + uint64_t value; + if (!pb_decode_varint(stream, &value)) + return false; + + if (value & 1) + *dest = (int64_t)(~(value >> 1)); + else + *dest = (int64_t)(value >> 1); + + return true; +} + +bool pb_decode_fixed32(pb_istream_t *stream, void *dest) +{ + pb_byte_t bytes[4]; + + if (!pb_read(stream, bytes, 4)) + return false; + + *(uint32_t*)dest = ((uint32_t)bytes[0] << 0) | + ((uint32_t)bytes[1] << 8) | + ((uint32_t)bytes[2] << 16) | + ((uint32_t)bytes[3] << 24); + return true; +} + +bool pb_decode_fixed64(pb_istream_t *stream, void *dest) +{ + pb_byte_t bytes[8]; + + if (!pb_read(stream, bytes, 8)) + return false; + + *(uint64_t*)dest = ((uint64_t)bytes[0] << 0) | + ((uint64_t)bytes[1] << 8) | + ((uint64_t)bytes[2] << 16) | + ((uint64_t)bytes[3] << 24) | + ((uint64_t)bytes[4] << 32) | + ((uint64_t)bytes[5] << 40) | + ((uint64_t)bytes[6] << 48) | + ((uint64_t)bytes[7] << 56); + + return true; +} + +static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + uint64_t value; + int64_t svalue; + int64_t clamped; + if (!pb_decode_varint(stream, &value)) + return false; + + /* See issue 97: Google's C++ protobuf allows negative varint values to + * be cast as int32_t, instead of the int64_t that should be used when + * encoding. Previous nanopb versions had a bug in encoding. In order to + * not break decoding of such messages, we cast <=32 bit fields to + * int32_t first to get the sign correct. + */ + if (field->data_size == sizeof(int64_t)) + svalue = (int64_t)value; + else + svalue = (int32_t)value; + + /* Cast to the proper field size, while checking for overflows */ + if (field->data_size == sizeof(int64_t)) + clamped = *(int64_t*)dest = svalue; + else if (field->data_size == sizeof(int32_t)) + clamped = *(int32_t*)dest = (int32_t)svalue; + else if (field->data_size == sizeof(int_least16_t)) + clamped = *(int_least16_t*)dest = (int_least16_t)svalue; + else if (field->data_size == sizeof(int_least8_t)) + clamped = *(int_least8_t*)dest = (int_least8_t)svalue; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + if (clamped != svalue) + PB_RETURN_ERROR(stream, "integer too large"); + + return true; +} + +static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + uint64_t value, clamped; + if (!pb_decode_varint(stream, &value)) + return false; + + /* Cast to the proper field size, while checking for overflows */ + if (field->data_size == sizeof(uint64_t)) + clamped = *(uint64_t*)dest = value; + else if (field->data_size == sizeof(uint32_t)) + clamped = *(uint32_t*)dest = (uint32_t)value; + else if (field->data_size == sizeof(uint_least16_t)) + clamped = *(uint_least16_t*)dest = (uint_least16_t)value; + else if (field->data_size == sizeof(uint_least8_t)) + clamped = *(uint_least8_t*)dest = (uint_least8_t)value; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + if (clamped != value) + PB_RETURN_ERROR(stream, "integer too large"); + + return true; +} + +static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + int64_t value, clamped; + if (!pb_decode_svarint(stream, &value)) + return false; + + /* Cast to the proper field size, while checking for overflows */ + if (field->data_size == sizeof(int64_t)) + clamped = *(int64_t*)dest = value; + else if (field->data_size == sizeof(int32_t)) + clamped = *(int32_t*)dest = (int32_t)value; + else if (field->data_size == sizeof(int_least16_t)) + clamped = *(int_least16_t*)dest = (int_least16_t)value; + else if (field->data_size == sizeof(int_least8_t)) + clamped = *(int_least8_t*)dest = (int_least8_t)value; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + if (clamped != value) + PB_RETURN_ERROR(stream, "integer too large"); + + return true; +} + +static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + PB_UNUSED(field); + return pb_decode_fixed32(stream, dest); +} + +static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + PB_UNUSED(field); + return pb_decode_fixed64(stream, dest); +} + +static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + uint32_t size; + size_t alloc_size; + pb_bytes_array_t *bdest; + + if (!pb_decode_varint32(stream, &size)) + return false; + + if (size > PB_SIZE_MAX) + PB_RETURN_ERROR(stream, "bytes overflow"); + + alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size); + if (size > alloc_size) + PB_RETURN_ERROR(stream, "size too large"); + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + { +#ifndef PB_ENABLE_MALLOC + PB_RETURN_ERROR(stream, "no malloc support"); +#else + if (!allocate_field(stream, dest, alloc_size, 1)) + return false; + bdest = *(pb_bytes_array_t**)dest; +#endif + } + else + { + if (alloc_size > field->data_size) + PB_RETURN_ERROR(stream, "bytes overflow"); + bdest = (pb_bytes_array_t*)dest; + } + + bdest->size = (pb_size_t)size; + return pb_read(stream, bdest->bytes, size); +} + +static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + uint32_t size; + size_t alloc_size; + bool status; + if (!pb_decode_varint32(stream, &size)) + return false; + + /* Space for null terminator */ + alloc_size = size + 1; + + if (alloc_size < size) + PB_RETURN_ERROR(stream, "size too large"); + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + { +#ifndef PB_ENABLE_MALLOC + PB_RETURN_ERROR(stream, "no malloc support"); +#else + if (!allocate_field(stream, dest, alloc_size, 1)) + return false; + dest = *(void**)dest; +#endif + } + else + { + if (alloc_size > field->data_size) + PB_RETURN_ERROR(stream, "string overflow"); + } + + status = pb_read(stream, (pb_byte_t*)dest, size); + *((pb_byte_t*)dest + size) = 0; + return status; +} + +static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + bool status; + pb_istream_t substream; + const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr; + + if (!pb_make_string_substream(stream, &substream)) + return false; + + if (field->ptr == NULL) + PB_RETURN_ERROR(stream, "invalid field descriptor"); + + /* New array entries need to be initialized, while required and optional + * submessages have already been initialized in the top-level pb_decode. */ + if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED) + status = pb_decode(&substream, submsg_fields, dest); + else + status = pb_decode_noinit(&substream, submsg_fields, dest); + + if (!pb_close_string_substream(stream, &substream)) + return false; + return status; +} + +static bool checkreturn pb_dec_fixed_length_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest) +{ + uint32_t size; + + if (!pb_decode_varint32(stream, &size)) + return false; + + if (size > PB_SIZE_MAX) + PB_RETURN_ERROR(stream, "bytes overflow"); + + if (size == 0) + { + /* As a special case, treat empty bytes string as all zeros for fixed_length_bytes. */ + memset(dest, 0, field->data_size); + return true; + } + + if (size != field->data_size) + PB_RETURN_ERROR(stream, "incorrect fixed length bytes size"); + + return pb_read(stream, (pb_byte_t*)dest, field->data_size); +} diff --git a/libs/nanopb/pb_decode.h b/libs/nanopb/pb_decode.h new file mode 100644 index 00000000..a426bdd7 --- /dev/null +++ b/libs/nanopb/pb_decode.h @@ -0,0 +1,153 @@ +/* pb_decode.h: Functions to decode protocol buffers. Depends on pb_decode.c. + * The main function is pb_decode. You also need an input stream, and the + * field descriptions created by nanopb_generator.py. + */ + +#ifndef PB_DECODE_H_INCLUDED +#define PB_DECODE_H_INCLUDED + +#include "pb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Structure for defining custom input streams. You will need to provide + * a callback function to read the bytes from your storage, which can be + * for example a file or a network socket. + * + * The callback must conform to these rules: + * + * 1) Return false on IO errors. This will cause decoding to abort. + * 2) You can use state to store your own data (e.g. buffer pointer), + * and rely on pb_read to verify that no-body reads past bytes_left. + * 3) Your callback may be used with substreams, in which case bytes_left + * is different than from the main stream. Don't use bytes_left to compute + * any pointers. + */ +struct pb_istream_s +{ +#ifdef PB_BUFFER_ONLY + /* Callback pointer is not used in buffer-only configuration. + * Having an int pointer here allows binary compatibility but + * gives an error if someone tries to assign callback function. + */ + int *callback; +#else + bool (*callback)(pb_istream_t *stream, pb_byte_t *buf, size_t count); +#endif + + void *state; /* Free field for use by callback implementation */ + size_t bytes_left; + +#ifndef PB_NO_ERRMSG + const char *errmsg; +#endif +}; + +/*************************** + * Main decoding functions * + ***************************/ + +/* Decode a single protocol buffers message from input stream into a C structure. + * Returns true on success, false on any failure. + * The actual struct pointed to by dest must match the description in fields. + * Callback fields of the destination structure must be initialized by caller. + * All other fields will be initialized by this function. + * + * Example usage: + * MyMessage msg = {}; + * uint8_t buffer[64]; + * pb_istream_t stream; + * + * // ... read some data into buffer ... + * + * stream = pb_istream_from_buffer(buffer, count); + * pb_decode(&stream, MyMessage_fields, &msg); + */ +bool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +/* Same as pb_decode, except does not initialize the destination structure + * to default values. This is slightly faster if you need no default values + * and just do memset(struct, 0, sizeof(struct)) yourself. + * + * This can also be used for 'merging' two messages, i.e. update only the + * fields that exist in the new message. + * + * Note: If this function returns with an error, it will not release any + * dynamically allocated fields. You will need to call pb_release() yourself. + */ +bool pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +/* Same as pb_decode, except expects the stream to start with the message size + * encoded as varint. Corresponds to parseDelimitedFrom() in Google's + * protobuf API. + */ +bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct); + +#ifdef PB_ENABLE_MALLOC +/* Release any allocated pointer fields. If you use dynamic allocation, you should + * call this for any successfully decoded message when you are done with it. If + * pb_decode() returns with an error, the message is already released. + */ +void pb_release(const pb_field_t fields[], void *dest_struct); +#endif + + +/************************************** + * Functions for manipulating streams * + **************************************/ + +/* Create an input stream for reading from a memory buffer. + * + * Alternatively, you can use a custom stream that reads directly from e.g. + * a file or a network socket. + */ +pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize); + +/* Function to read from a pb_istream_t. You can use this if you need to + * read some custom header data, or to read data in field callbacks. + */ +bool pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count); + + +/************************************************ + * Helper functions for writing field callbacks * + ************************************************/ + +/* Decode the tag for the next field in the stream. Gives the wire type and + * field tag. At end of the message, returns false and sets eof to true. */ +bool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof); + +/* Skip the field payload data, given the wire type. */ +bool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type); + +/* Decode an integer in the varint format. This works for bool, enum, int32, + * int64, uint32 and uint64 field types. */ +bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest); + +/* Decode an integer in the varint format. This works for bool, enum, int32, + * and uint32 field types. */ +bool pb_decode_varint32(pb_istream_t *stream, uint32_t *dest); + +/* Decode an integer in the zig-zagged svarint format. This works for sint32 + * and sint64. */ +bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest); + +/* Decode a fixed32, sfixed32 or float value. You need to pass a pointer to + * a 4-byte wide C variable. */ +bool pb_decode_fixed32(pb_istream_t *stream, void *dest); + +/* Decode a fixed64, sfixed64 or double value. You need to pass a pointer to + * a 8-byte wide C variable. */ +bool pb_decode_fixed64(pb_istream_t *stream, void *dest); + +/* Make a limited-length substream for reading a PB_WT_STRING field. */ +bool pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream); +bool pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/libs/nanopb/pb_encode.c b/libs/nanopb/pb_encode.c new file mode 100644 index 00000000..05d691df --- /dev/null +++ b/libs/nanopb/pb_encode.c @@ -0,0 +1,803 @@ +/* pb_encode.c -- encode a protobuf using minimal resources + * + * 2011 Petteri Aimonen + */ + +#include "pb.h" +#include "pb_encode.h" +#include "pb_common.h" + +/* Use the GCC warn_unused_result attribute to check that all return values + * are propagated correctly. On other compilers and gcc before 3.4.0 just + * ignore the annotation. + */ +#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4) + #define checkreturn +#else + #define checkreturn __attribute__((warn_unused_result)) +#endif + +/************************************** + * Declarations internal to this file * + **************************************/ +typedef bool (*pb_encoder_t)(pb_ostream_t *stream, const pb_field_t *field, const void *src) checkreturn; + +static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count); +static bool checkreturn encode_array(pb_ostream_t *stream, const pb_field_t *field, const void *pData, size_t count, pb_encoder_t func); +static bool checkreturn encode_field(pb_ostream_t *stream, const pb_field_t *field, const void *pData); +static bool checkreturn default_extension_encoder(pb_ostream_t *stream, const pb_extension_t *extension); +static bool checkreturn encode_extension_field(pb_ostream_t *stream, const pb_field_t *field, const void *pData); +static void *pb_const_cast(const void *p); +static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_uvarint(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src); +static bool checkreturn pb_enc_fixed_length_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src); + +/* --- Function pointers to field encoders --- + * Order in the array must match pb_action_t LTYPE numbering. + */ +static const pb_encoder_t PB_ENCODERS[PB_LTYPES_COUNT] = { + &pb_enc_varint, + &pb_enc_uvarint, + &pb_enc_svarint, + &pb_enc_fixed32, + &pb_enc_fixed64, + + &pb_enc_bytes, + &pb_enc_string, + &pb_enc_submessage, + NULL, /* extensions */ + &pb_enc_fixed_length_bytes +}; + +/******************************* + * pb_ostream_t implementation * + *******************************/ + +static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count) +{ + size_t i; + pb_byte_t *dest = (pb_byte_t*)stream->state; + stream->state = dest + count; + + for (i = 0; i < count; i++) + dest[i] = buf[i]; + + return true; +} + +pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize) +{ + pb_ostream_t stream; +#ifdef PB_BUFFER_ONLY + stream.callback = (void*)1; /* Just a marker value */ +#else + stream.callback = &buf_write; +#endif + stream.state = buf; + stream.max_size = bufsize; + stream.bytes_written = 0; +#ifndef PB_NO_ERRMSG + stream.errmsg = NULL; +#endif + return stream; +} + +bool checkreturn pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count) +{ + if (stream->callback != NULL) + { + if (stream->bytes_written + count > stream->max_size) + PB_RETURN_ERROR(stream, "stream full"); + +#ifdef PB_BUFFER_ONLY + if (!buf_write(stream, buf, count)) + PB_RETURN_ERROR(stream, "io error"); +#else + if (!stream->callback(stream, buf, count)) + PB_RETURN_ERROR(stream, "io error"); +#endif + } + + stream->bytes_written += count; + return true; +} + +/************************* + * Encode a single field * + *************************/ + +/* Encode a static array. Handles the size calculations and possible packing. */ +static bool checkreturn encode_array(pb_ostream_t *stream, const pb_field_t *field, + const void *pData, size_t count, pb_encoder_t func) +{ + size_t i; + const void *p; + size_t size; + + if (count == 0) + return true; + + if (PB_ATYPE(field->type) != PB_ATYPE_POINTER && count > field->array_size) + PB_RETURN_ERROR(stream, "array max size exceeded"); + + /* We always pack arrays if the datatype allows it. */ + if (PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE) + { + if (!pb_encode_tag(stream, PB_WT_STRING, field->tag)) + return false; + + /* Determine the total size of packed array. */ + if (PB_LTYPE(field->type) == PB_LTYPE_FIXED32) + { + size = 4 * count; + } + else if (PB_LTYPE(field->type) == PB_LTYPE_FIXED64) + { + size = 8 * count; + } + else + { + pb_ostream_t sizestream = PB_OSTREAM_SIZING; + p = pData; + for (i = 0; i < count; i++) + { + if (!func(&sizestream, field, p)) + return false; + p = (const char*)p + field->data_size; + } + size = sizestream.bytes_written; + } + + if (!pb_encode_varint(stream, (uint64_t)size)) + return false; + + if (stream->callback == NULL) + return pb_write(stream, NULL, size); /* Just sizing.. */ + + /* Write the data */ + p = pData; + for (i = 0; i < count; i++) + { + if (!func(stream, field, p)) + return false; + p = (const char*)p + field->data_size; + } + } + else + { + p = pData; + for (i = 0; i < count; i++) + { + if (!pb_encode_tag_for_field(stream, field)) + return false; + + /* Normally the data is stored directly in the array entries, but + * for pointer-type string and bytes fields, the array entries are + * actually pointers themselves also. So we have to dereference once + * more to get to the actual data. */ + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER && + (PB_LTYPE(field->type) == PB_LTYPE_STRING || + PB_LTYPE(field->type) == PB_LTYPE_BYTES)) + { + if (!func(stream, field, *(const void* const*)p)) + return false; + } + else + { + if (!func(stream, field, p)) + return false; + } + p = (const char*)p + field->data_size; + } + } + + return true; +} + +/* In proto3, all fields are optional and are only encoded if their value is "non-zero". + * This function implements the check for the zero value. */ +static bool pb_check_proto3_default_value(const pb_field_t *field, const void *pData) +{ + pb_type_t type = field->type; + const void *pSize = (const char*)pData + field->size_offset; + + if (PB_HTYPE(type) == PB_HTYPE_REQUIRED) + { + /* Required proto2 fields inside proto3 submessage, pretty rare case */ + return false; + } + else if (PB_HTYPE(type) == PB_HTYPE_REPEATED) + { + /* Repeated fields inside proto3 submessage: present if count != 0 */ + return *(const pb_size_t*)pSize == 0; + } + else if (PB_HTYPE(type) == PB_HTYPE_ONEOF) + { + /* Oneof fields */ + return *(const pb_size_t*)pSize == 0; + } + else if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL && field->size_offset) + { + /* Proto2 optional fields inside proto3 submessage */ + return *(const bool*)pSize == false; + } + + /* Rest is proto3 singular fields */ + + if (PB_ATYPE(type) == PB_ATYPE_STATIC) + { + if (PB_LTYPE(type) == PB_LTYPE_BYTES) + { + const pb_bytes_array_t *bytes = (const pb_bytes_array_t*)pData; + return bytes->size == 0; + } + else if (PB_LTYPE(type) == PB_LTYPE_STRING) + { + return *(const char*)pData == '\0'; + } + else if (PB_LTYPE(type) == PB_LTYPE_FIXED_LENGTH_BYTES) + { + /* Fixed length bytes is only empty if its length is fixed + * as 0. Which would be pretty strange, but we can check + * it anyway. */ + return field->data_size == 0; + } + else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE) + { + /* Check all fields in the submessage to find if any of them + * are non-zero. The comparison cannot be done byte-per-byte + * because the C struct may contain padding bytes that must + * be skipped. + */ + pb_field_iter_t iter; + if (pb_field_iter_begin(&iter, (const pb_field_t*)field->ptr, pb_const_cast(pData))) + { + do + { + if (!pb_check_proto3_default_value(iter.pos, iter.pData)) + { + return false; + } + } while (pb_field_iter_next(&iter)); + } + return true; + } + } + + { + /* Catch-all branch that does byte-per-byte comparison for zero value. + * + * This is for all pointer fields, and for static PB_LTYPE_VARINT, + * UVARINT, SVARINT, FIXED32, FIXED64, EXTENSION fields, and also + * callback fields. These all have integer or pointer value which + * can be compared with 0. + */ + pb_size_t i; + const char *p = (const char*)pData; + for (i = 0; i < field->data_size; i++) + { + if (p[i] != 0) + { + return false; + } + } + + return true; + } +} + +/* Encode a field with static or pointer allocation, i.e. one whose data + * is available to the encoder directly. */ +static bool checkreturn encode_basic_field(pb_ostream_t *stream, + const pb_field_t *field, const void *pData) +{ + pb_encoder_t func; + bool implicit_has; + const void *pSize = &implicit_has; + + func = PB_ENCODERS[PB_LTYPE(field->type)]; + + if (field->size_offset) + { + /* Static optional, repeated or oneof field */ + pSize = (const char*)pData + field->size_offset; + } + else if (PB_HTYPE(field->type) == PB_HTYPE_OPTIONAL) + { + /* Proto3 style field, optional but without explicit has_ field. */ + implicit_has = !pb_check_proto3_default_value(field, pData); + } + else + { + /* Required field, always present */ + implicit_has = true; + } + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + { + /* pData is a pointer to the field, which contains pointer to + * the data. If the 2nd pointer is NULL, it is interpreted as if + * the has_field was false. + */ + pData = *(const void* const*)pData; + implicit_has = (pData != NULL); + } + + switch (PB_HTYPE(field->type)) + { + case PB_HTYPE_REQUIRED: + if (!pData) + PB_RETURN_ERROR(stream, "missing required field"); + if (!pb_encode_tag_for_field(stream, field)) + return false; + if (!func(stream, field, pData)) + return false; + break; + + case PB_HTYPE_OPTIONAL: + if (*(const bool*)pSize) + { + if (!pb_encode_tag_for_field(stream, field)) + return false; + + if (!func(stream, field, pData)) + return false; + } + break; + + case PB_HTYPE_REPEATED: + if (!encode_array(stream, field, pData, *(const pb_size_t*)pSize, func)) + return false; + break; + + case PB_HTYPE_ONEOF: + if (*(const pb_size_t*)pSize == field->tag) + { + if (!pb_encode_tag_for_field(stream, field)) + return false; + + if (!func(stream, field, pData)) + return false; + } + break; + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } + + return true; +} + +/* Encode a field with callback semantics. This means that a user function is + * called to provide and encode the actual data. */ +static bool checkreturn encode_callback_field(pb_ostream_t *stream, + const pb_field_t *field, const void *pData) +{ + const pb_callback_t *callback = (const pb_callback_t*)pData; + +#ifdef PB_OLD_CALLBACK_STYLE + const void *arg = callback->arg; +#else + void * const *arg = &(callback->arg); +#endif + + if (callback->funcs.encode != NULL) + { + if (!callback->funcs.encode(stream, field, arg)) + PB_RETURN_ERROR(stream, "callback error"); + } + return true; +} + +/* Encode a single field of any callback or static type. */ +static bool checkreturn encode_field(pb_ostream_t *stream, + const pb_field_t *field, const void *pData) +{ + switch (PB_ATYPE(field->type)) + { + case PB_ATYPE_STATIC: + case PB_ATYPE_POINTER: + return encode_basic_field(stream, field, pData); + + case PB_ATYPE_CALLBACK: + return encode_callback_field(stream, field, pData); + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } +} + +/* Default handler for extension fields. Expects to have a pb_field_t + * pointer in the extension->type->arg field. */ +static bool checkreturn default_extension_encoder(pb_ostream_t *stream, + const pb_extension_t *extension) +{ + const pb_field_t *field = (const pb_field_t*)extension->type->arg; + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + { + /* For pointer extensions, the pointer is stored directly + * in the extension structure. This avoids having an extra + * indirection. */ + return encode_field(stream, field, &extension->dest); + } + else + { + return encode_field(stream, field, extension->dest); + } +} + +/* Walk through all the registered extensions and give them a chance + * to encode themselves. */ +static bool checkreturn encode_extension_field(pb_ostream_t *stream, + const pb_field_t *field, const void *pData) +{ + const pb_extension_t *extension = *(const pb_extension_t* const *)pData; + PB_UNUSED(field); + + while (extension) + { + bool status; + if (extension->type->encode) + status = extension->type->encode(stream, extension); + else + status = default_extension_encoder(stream, extension); + + if (!status) + return false; + + extension = extension->next; + } + + return true; +} + +/********************* + * Encode all fields * + *********************/ + +static void *pb_const_cast(const void *p) +{ + /* Note: this casts away const, in order to use the common field iterator + * logic for both encoding and decoding. */ + union { + void *p1; + const void *p2; + } t; + t.p2 = p; + return t.p1; +} + +bool checkreturn pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct) +{ + pb_field_iter_t iter; + if (!pb_field_iter_begin(&iter, fields, pb_const_cast(src_struct))) + return true; /* Empty message type */ + + do { + if (PB_LTYPE(iter.pos->type) == PB_LTYPE_EXTENSION) + { + /* Special case for the extension field placeholder */ + if (!encode_extension_field(stream, iter.pos, iter.pData)) + return false; + } + else + { + /* Regular field */ + if (!encode_field(stream, iter.pos, iter.pData)) + return false; + } + } while (pb_field_iter_next(&iter)); + + return true; +} + +bool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct) +{ + return pb_encode_submessage(stream, fields, src_struct); +} + +bool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct) +{ + pb_ostream_t stream = PB_OSTREAM_SIZING; + + if (!pb_encode(&stream, fields, src_struct)) + return false; + + *size = stream.bytes_written; + return true; +} + +/******************** + * Helper functions * + ********************/ +bool checkreturn pb_encode_varint(pb_ostream_t *stream, uint64_t value) +{ + pb_byte_t buffer[10]; + size_t i = 0; + + if (value <= 0x7F) + { + pb_byte_t v = (pb_byte_t)value; + return pb_write(stream, &v, 1); + } + + while (value) + { + buffer[i] = (pb_byte_t)((value & 0x7F) | 0x80); + value >>= 7; + i++; + } + buffer[i-1] &= 0x7F; /* Unset top bit on last byte */ + + return pb_write(stream, buffer, i); +} + +bool checkreturn pb_encode_svarint(pb_ostream_t *stream, int64_t value) +{ + uint64_t zigzagged; + if (value < 0) + zigzagged = ~((uint64_t)value << 1); + else + zigzagged = (uint64_t)value << 1; + + return pb_encode_varint(stream, zigzagged); +} + +bool checkreturn pb_encode_fixed32(pb_ostream_t *stream, const void *value) +{ + uint32_t val = *(const uint32_t*)value; + pb_byte_t bytes[4]; + bytes[0] = (pb_byte_t)(val & 0xFF); + bytes[1] = (pb_byte_t)((val >> 8) & 0xFF); + bytes[2] = (pb_byte_t)((val >> 16) & 0xFF); + bytes[3] = (pb_byte_t)((val >> 24) & 0xFF); + return pb_write(stream, bytes, 4); +} + +bool checkreturn pb_encode_fixed64(pb_ostream_t *stream, const void *value) +{ + uint64_t val = *(const uint64_t*)value; + pb_byte_t bytes[8]; + bytes[0] = (pb_byte_t)(val & 0xFF); + bytes[1] = (pb_byte_t)((val >> 8) & 0xFF); + bytes[2] = (pb_byte_t)((val >> 16) & 0xFF); + bytes[3] = (pb_byte_t)((val >> 24) & 0xFF); + bytes[4] = (pb_byte_t)((val >> 32) & 0xFF); + bytes[5] = (pb_byte_t)((val >> 40) & 0xFF); + bytes[6] = (pb_byte_t)((val >> 48) & 0xFF); + bytes[7] = (pb_byte_t)((val >> 56) & 0xFF); + return pb_write(stream, bytes, 8); +} + +bool checkreturn pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number) +{ + uint64_t tag = ((uint64_t)field_number << 3) | wiretype; + return pb_encode_varint(stream, tag); +} + +bool checkreturn pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field) +{ + pb_wire_type_t wiretype; + switch (PB_LTYPE(field->type)) + { + case PB_LTYPE_VARINT: + case PB_LTYPE_UVARINT: + case PB_LTYPE_SVARINT: + wiretype = PB_WT_VARINT; + break; + + case PB_LTYPE_FIXED32: + wiretype = PB_WT_32BIT; + break; + + case PB_LTYPE_FIXED64: + wiretype = PB_WT_64BIT; + break; + + case PB_LTYPE_BYTES: + case PB_LTYPE_STRING: + case PB_LTYPE_SUBMESSAGE: + case PB_LTYPE_FIXED_LENGTH_BYTES: + wiretype = PB_WT_STRING; + break; + + default: + PB_RETURN_ERROR(stream, "invalid field type"); + } + + return pb_encode_tag(stream, wiretype, field->tag); +} + +bool checkreturn pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size) +{ + if (!pb_encode_varint(stream, (uint64_t)size)) + return false; + + return pb_write(stream, buffer, size); +} + +bool checkreturn pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct) +{ + /* First calculate the message size using a non-writing substream. */ + pb_ostream_t substream = PB_OSTREAM_SIZING; + size_t size; + bool status; + + if (!pb_encode(&substream, fields, src_struct)) + { +#ifndef PB_NO_ERRMSG + stream->errmsg = substream.errmsg; +#endif + return false; + } + + size = substream.bytes_written; + + if (!pb_encode_varint(stream, (uint64_t)size)) + return false; + + if (stream->callback == NULL) + return pb_write(stream, NULL, size); /* Just sizing */ + + if (stream->bytes_written + size > stream->max_size) + PB_RETURN_ERROR(stream, "stream full"); + + /* Use a substream to verify that a callback doesn't write more than + * what it did the first time. */ + substream.callback = stream->callback; + substream.state = stream->state; + substream.max_size = size; + substream.bytes_written = 0; +#ifndef PB_NO_ERRMSG + substream.errmsg = NULL; +#endif + + status = pb_encode(&substream, fields, src_struct); + + stream->bytes_written += substream.bytes_written; + stream->state = substream.state; +#ifndef PB_NO_ERRMSG + stream->errmsg = substream.errmsg; +#endif + + if (substream.bytes_written != size) + PB_RETURN_ERROR(stream, "submsg size changed"); + + return status; +} + +/* Field encoders */ + +static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + int64_t value = 0; + + if (field->data_size == sizeof(int_least8_t)) + value = *(const int_least8_t*)src; + else if (field->data_size == sizeof(int_least16_t)) + value = *(const int_least16_t*)src; + else if (field->data_size == sizeof(int32_t)) + value = *(const int32_t*)src; + else if (field->data_size == sizeof(int64_t)) + value = *(const int64_t*)src; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + return pb_encode_varint(stream, (uint64_t)value); +} + +static bool checkreturn pb_enc_uvarint(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + uint64_t value = 0; + + if (field->data_size == sizeof(uint_least8_t)) + value = *(const uint_least8_t*)src; + else if (field->data_size == sizeof(uint_least16_t)) + value = *(const uint_least16_t*)src; + else if (field->data_size == sizeof(uint32_t)) + value = *(const uint32_t*)src; + else if (field->data_size == sizeof(uint64_t)) + value = *(const uint64_t*)src; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + return pb_encode_varint(stream, value); +} + +static bool checkreturn pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + int64_t value = 0; + + if (field->data_size == sizeof(int_least8_t)) + value = *(const int_least8_t*)src; + else if (field->data_size == sizeof(int_least16_t)) + value = *(const int_least16_t*)src; + else if (field->data_size == sizeof(int32_t)) + value = *(const int32_t*)src; + else if (field->data_size == sizeof(int64_t)) + value = *(const int64_t*)src; + else + PB_RETURN_ERROR(stream, "invalid data_size"); + + return pb_encode_svarint(stream, value); +} + +static bool checkreturn pb_enc_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + PB_UNUSED(field); + return pb_encode_fixed64(stream, src); +} + +static bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + PB_UNUSED(field); + return pb_encode_fixed32(stream, src); +} + +static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + const pb_bytes_array_t *bytes = NULL; + + bytes = (const pb_bytes_array_t*)src; + + if (src == NULL) + { + /* Treat null pointer as an empty bytes field */ + return pb_encode_string(stream, NULL, 0); + } + + if (PB_ATYPE(field->type) == PB_ATYPE_STATIC && + PB_BYTES_ARRAY_T_ALLOCSIZE(bytes->size) > field->data_size) + { + PB_RETURN_ERROR(stream, "bytes size exceeded"); + } + + return pb_encode_string(stream, bytes->bytes, bytes->size); +} + +static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + size_t size = 0; + size_t max_size = field->data_size; + const char *p = (const char*)src; + + if (PB_ATYPE(field->type) == PB_ATYPE_POINTER) + max_size = (size_t)-1; + + if (src == NULL) + { + size = 0; /* Treat null pointer as an empty string */ + } + else + { + /* strnlen() is not always available, so just use a loop */ + while (size < max_size && *p != '\0') + { + size++; + p++; + } + } + + return pb_encode_string(stream, (const pb_byte_t*)src, size); +} + +static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + if (field->ptr == NULL) + PB_RETURN_ERROR(stream, "invalid field descriptor"); + + return pb_encode_submessage(stream, (const pb_field_t*)field->ptr, src); +} + +static bool checkreturn pb_enc_fixed_length_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src) +{ + return pb_encode_string(stream, (const pb_byte_t*)src, field->data_size); +} + diff --git a/libs/nanopb/pb_encode.h b/libs/nanopb/pb_encode.h new file mode 100644 index 00000000..d9909fb0 --- /dev/null +++ b/libs/nanopb/pb_encode.h @@ -0,0 +1,154 @@ +/* pb_encode.h: Functions to encode protocol buffers. Depends on pb_encode.c. + * The main function is pb_encode. You also need an output stream, and the + * field descriptions created by nanopb_generator.py. + */ + +#ifndef PB_ENCODE_H_INCLUDED +#define PB_ENCODE_H_INCLUDED + +#include "pb.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Structure for defining custom output streams. You will need to provide + * a callback function to write the bytes to your storage, which can be + * for example a file or a network socket. + * + * The callback must conform to these rules: + * + * 1) Return false on IO errors. This will cause encoding to abort. + * 2) You can use state to store your own data (e.g. buffer pointer). + * 3) pb_write will update bytes_written after your callback runs. + * 4) Substreams will modify max_size and bytes_written. Don't use them + * to calculate any pointers. + */ +struct pb_ostream_s +{ +#ifdef PB_BUFFER_ONLY + /* Callback pointer is not used in buffer-only configuration. + * Having an int pointer here allows binary compatibility but + * gives an error if someone tries to assign callback function. + * Also, NULL pointer marks a 'sizing stream' that does not + * write anything. + */ + int *callback; +#else + bool (*callback)(pb_ostream_t *stream, const pb_byte_t *buf, size_t count); +#endif + void *state; /* Free field for use by callback implementation. */ + size_t max_size; /* Limit number of output bytes written (or use SIZE_MAX). */ + size_t bytes_written; /* Number of bytes written so far. */ + +#ifndef PB_NO_ERRMSG + const char *errmsg; +#endif +}; + +/*************************** + * Main encoding functions * + ***************************/ + +/* Encode a single protocol buffers message from C structure into a stream. + * Returns true on success, false on any failure. + * The actual struct pointed to by src_struct must match the description in fields. + * All required fields in the struct are assumed to have been filled in. + * + * Example usage: + * MyMessage msg = {}; + * uint8_t buffer[64]; + * pb_ostream_t stream; + * + * msg.field1 = 42; + * stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + * pb_encode(&stream, MyMessage_fields, &msg); + */ +bool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); + +/* Same as pb_encode, but prepends the length of the message as a varint. + * Corresponds to writeDelimitedTo() in Google's protobuf API. + */ +bool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); + +/* Encode the message to get the size of the encoded data, but do not store + * the data. */ +bool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct); + +/************************************** + * Functions for manipulating streams * + **************************************/ + +/* Create an output stream for writing into a memory buffer. + * The number of bytes written can be found in stream.bytes_written after + * encoding the message. + * + * Alternatively, you can use a custom stream that writes directly to e.g. + * a file or a network socket. + */ +pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize); + +/* Pseudo-stream for measuring the size of a message without actually storing + * the encoded data. + * + * Example usage: + * MyMessage msg = {}; + * pb_ostream_t stream = PB_OSTREAM_SIZING; + * pb_encode(&stream, MyMessage_fields, &msg); + * printf("Message size is %d\n", stream.bytes_written); + */ +#ifndef PB_NO_ERRMSG +#define PB_OSTREAM_SIZING {0,0,0,0,0} +#else +#define PB_OSTREAM_SIZING {0,0,0,0} +#endif + +/* Function to write into a pb_ostream_t stream. You can use this if you need + * to append or prepend some custom headers to the message. + */ +bool pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count); + + +/************************************************ + * Helper functions for writing field callbacks * + ************************************************/ + +/* Encode field header based on type and field number defined in the field + * structure. Call this from the callback before writing out field contents. */ +bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field); + +/* Encode field header by manually specifing wire type. You need to use this + * if you want to write out packed arrays from a callback field. */ +bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number); + +/* Encode an integer in the varint format. + * This works for bool, enum, int32, int64, uint32 and uint64 field types. */ +bool pb_encode_varint(pb_ostream_t *stream, uint64_t value); + +/* Encode an integer in the zig-zagged svarint format. + * This works for sint32 and sint64. */ +bool pb_encode_svarint(pb_ostream_t *stream, int64_t value); + +/* Encode a string or bytes type field. For strings, pass strlen(s) as size. */ +bool pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size); + +/* Encode a fixed32, sfixed32 or float value. + * You need to pass a pointer to a 4-byte wide C variable. */ +bool pb_encode_fixed32(pb_ostream_t *stream, const void *value); + +/* Encode a fixed64, sfixed64 or double value. + * You need to pass a pointer to a 8-byte wide C variable. */ +bool pb_encode_fixed64(pb_ostream_t *stream, const void *value); + +/* Encode a submessage field. + * You need to pass the pb_field_t array and pointer to struct, just like + * with pb_encode(). This internally encodes the submessage twice, first to + * calculate message size and then to actually write it out. + */ +bool pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/libs/nanopb/tests/Makefile b/libs/nanopb/tests/Makefile new file mode 100644 index 00000000..cee6bf67 --- /dev/null +++ b/libs/nanopb/tests/Makefile @@ -0,0 +1,21 @@ +all: + scons + +clean: + scons -c + +coverage: + rm -rf build coverage + + # LCOV does not like the newer gcov format + scons CC=gcc-4.6 CXX=gcc-4.6 + + # Collect the data + mkdir build/coverage + lcov --base-directory . --directory build/ --gcov-tool gcov-4.6 -c -o build/coverage/nanopb.info + + # Remove the test code from results + lcov -r build/coverage/nanopb.info '*tests*' -o build/coverage/nanopb.info + + # Generate HTML + genhtml -o build/coverage build/coverage/nanopb.info diff --git a/libs/nanopb/tests/SConstruct b/libs/nanopb/tests/SConstruct new file mode 100644 index 00000000..ae79f710 --- /dev/null +++ b/libs/nanopb/tests/SConstruct @@ -0,0 +1,157 @@ +Help(''' +Type 'scons' to build and run all the available test cases. +It will automatically detect your platform and C compiler and +build appropriately. + +You can modify the behavious using following options: +CC Name of C compiler +CXX Name of C++ compiler +CCFLAGS Flags to pass to the C compiler +CXXFLAGS Flags to pass to the C++ compiler + +For example, for a clang build, use: +scons CC=clang CXX=clang++ +''') + +import os +env = Environment(ENV = os.environ, tools = ['default', 'nanopb']) + +# Allow overriding the compiler with scons CC=??? +if 'CC' in ARGUMENTS: env.Replace(CC = ARGUMENTS['CC']) +if 'CXX' in ARGUMENTS: env.Replace(CXX = ARGUMENTS['CXX']) +if 'CCFLAGS' in ARGUMENTS: env.Append(CCFLAGS = ARGUMENTS['CCFLAGS']) +if 'CXXFLAGS' in ARGUMENTS: env.Append(CXXFLAGS = ARGUMENTS['CXXFLAGS']) + +# Add the builders defined in site_init.py +add_nanopb_builders(env) + +# Path to the files shared by tests, and to the nanopb core. +env.Append(CPPPATH = ["#../", "$COMMON"]) + +# Path for finding nanopb.proto +env.Append(PROTOCPATH = '#../generator') + +# Check the compilation environment, unless we are just cleaning up. +if not env.GetOption('clean'): + def check_ccflags(context, flags, linkflags = ''): + '''Check if given CCFLAGS are supported''' + context.Message('Checking support for CCFLAGS="%s"... ' % flags) + oldflags = context.env['CCFLAGS'] + oldlinkflags = context.env['CCFLAGS'] + context.env.Append(CCFLAGS = flags) + context.env.Append(LINKFLAGS = linkflags) + result = context.TryCompile("int main() {return 0;}", '.c') + context.env.Replace(CCFLAGS = oldflags) + context.env.Replace(LINKFLAGS = oldlinkflags) + context.Result(result) + return result + + conf = Configure(env, custom_tests = {'CheckCCFLAGS': check_ccflags}) + + # If the platform doesn't support C99, use our own header file instead. + stdbool = conf.CheckCHeader('stdbool.h') + stdint = conf.CheckCHeader('stdint.h') + stddef = conf.CheckCHeader('stddef.h') + string = conf.CheckCHeader('string.h') + stdlib = conf.CheckCHeader('stdlib.h') + if not stdbool or not stdint or not stddef or not string: + conf.env.Append(CPPDEFINES = {'PB_SYSTEM_HEADER': '\\"pb_syshdr.h\\"'}) + conf.env.Append(CPPPATH = "#../extra") + conf.env.Append(SYSHDR = '\\"pb_syshdr.h\\"') + + if stdbool: conf.env.Append(CPPDEFINES = {'HAVE_STDBOOL_H': 1}) + if stdint: conf.env.Append(CPPDEFINES = {'HAVE_STDINT_H': 1}) + if stddef: conf.env.Append(CPPDEFINES = {'HAVE_STDDEF_H': 1}) + if string: conf.env.Append(CPPDEFINES = {'HAVE_STRING_H': 1}) + if stdlib: conf.env.Append(CPPDEFINES = {'HAVE_STDLIB_H': 1}) + + # Check if we can use pkg-config to find protobuf include path + status, output = conf.TryAction('pkg-config protobuf --variable=includedir > $TARGET') + if status: + conf.env.Append(PROTOCPATH = output.strip()) + else: + conf.env.Append(PROTOCPATH = '/usr/include') + + # Check protoc version + status, output = conf.TryAction('$PROTOC --version > $TARGET') + if status: + conf.env['PROTOC_VERSION'] = output + + # Check if libmudflap is available (only with GCC) + if 'gcc' in env['CC']: + if conf.CheckLib('mudflap'): + conf.env.Append(CCFLAGS = '-fmudflap') + conf.env.Append(LINKFLAGS = '-fmudflap') + + # Check if we can use extra strict warning flags (only with GCC) + extra = '-Wcast-qual -Wlogical-op -Wconversion' + extra += ' -fstrict-aliasing -Wstrict-aliasing=1' + extra += ' -Wmissing-prototypes -Wmissing-declarations -Wredundant-decls' + extra += ' -Wstack-protector ' + if 'gcc' in env['CC']: + if conf.CheckCCFLAGS(extra): + conf.env.Append(CORECFLAGS = extra) + + # Check if we can use undefined behaviour sanitizer (only with clang) + # TODO: Fuzz test triggers the bool sanitizer, figure out whether to + # modify the fuzz test or to keep ignoring the check. + extra = '-fsanitize=undefined,integer -fno-sanitize-recover=undefined,integer -fsanitize-recover=bool ' + if 'clang' in env['CC']: + if conf.CheckCCFLAGS(extra, linkflags = extra): + conf.env.Append(CORECFLAGS = extra) + conf.env.Append(LINKFLAGS = extra) + + # End the config stuff + env = conf.Finish() + +# Initialize the CCFLAGS according to the compiler +if 'gcc' in env['CC']: + # GNU Compiler Collection + + # Debug info, warnings as errors + env.Append(CFLAGS = '-ansi -pedantic -g -Wall -Werror -fprofile-arcs -ftest-coverage ') + env.Append(CORECFLAGS = '-Wextra') + env.Append(LINKFLAGS = '-g --coverage') + + # We currently need uint64_t anyway, even though ANSI C90 otherwise.. + env.Append(CFLAGS = '-Wno-long-long') +elif 'clang' in env['CC']: + # CLang + env.Append(CFLAGS = '-ansi -g -Wall -Werror') + env.Append(CORECFLAGS = ' -Wextra -Wcast-qual -Wconversion') +elif 'cl' in env['CC']: + # Microsoft Visual C++ + + # Debug info on, warning level 2 for tests, warnings as errors + env.Append(CFLAGS = '/Zi /W2 /WX') + env.Append(LINKFLAGS = '/DEBUG') + + # More strict checks on the nanopb core + env.Append(CORECFLAGS = '/W4') +elif 'tcc' in env['CC']: + # Tiny C Compiler + env.Append(CFLAGS = '-Wall -Werror -g') + +env.SetDefault(CORECFLAGS = '') + +if 'clang' in env['CXX']: + env.Append(CXXFLAGS = '-g -Wall -Werror -Wextra -Wno-missing-field-initializers') +elif 'g++' in env['CXX'] or 'gcc' in env['CXX']: + env.Append(CXXFLAGS = '-g -Wall -Werror -Wextra -Wno-missing-field-initializers') +elif 'cl' in env['CXX']: + env.Append(CXXFLAGS = '/Zi /W2 /WX') + +# Now include the SConscript files from all subdirectories +import os.path +env['VARIANT_DIR'] = 'build' +env['BUILD'] = '#' + env['VARIANT_DIR'] +env['COMMON'] = '#' + env['VARIANT_DIR'] + '/common' + +# Include common/SConscript first to make sure its exports are available +# to other SConscripts. +SConscript("common/SConscript", exports = 'env', variant_dir = env['VARIANT_DIR'] + '/common') + +for subdir in Glob('*/SConscript') + Glob('regression/*/SConscript'): + if str(subdir).startswith("common"): continue + SConscript(subdir, exports = 'env', variant_dir = env['VARIANT_DIR'] + '/' + os.path.dirname(str(subdir))) + diff --git a/libs/nanopb/tests/alltypes/SConscript b/libs/nanopb/tests/alltypes/SConscript new file mode 100644 index 00000000..6c6238c6 --- /dev/null +++ b/libs/nanopb/tests/alltypes/SConscript @@ -0,0 +1,35 @@ +# Build and run a test that encodes and decodes a message that contains +# all of the Protocol Buffers data types. + +Import("env") + +env.NanopbProto(["alltypes", "alltypes.options"]) +enc = env.Program(["encode_alltypes.c", "alltypes.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) +dec = env.Program(["decode_alltypes.c", "alltypes.pb.c", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) + +# Test the round-trip from nanopb encoder to nanopb decoder +env.RunTest(enc) +env.RunTest([dec, "encode_alltypes.output"]) + +# Re-encode the data using protoc, and check that the results from nanopb +# match byte-per-byte to the protoc output. +env.Decode("encode_alltypes.output.decoded", + ["encode_alltypes.output", "alltypes.proto"], + MESSAGE='AllTypes') +env.Encode("encode_alltypes.output.recoded", + ["encode_alltypes.output.decoded", "alltypes.proto"], + MESSAGE='AllTypes') +env.Compare(["encode_alltypes.output", "encode_alltypes.output.recoded"]) + +# Do the same checks with the optional fields present. +env.RunTest("optionals.output", enc, ARGS = ['1']) +env.RunTest("optionals.decout", [dec, "optionals.output"], ARGS = ['1']) +env.Decode("optionals.output.decoded", + ["optionals.output", "alltypes.proto"], + MESSAGE='AllTypes') +env.Encode("optionals.output.recoded", + ["optionals.output.decoded", "alltypes.proto"], + MESSAGE='AllTypes') +env.Compare(["optionals.output", "optionals.output.recoded"]) + + diff --git a/libs/nanopb/tests/alltypes/alltypes.options b/libs/nanopb/tests/alltypes/alltypes.options new file mode 100644 index 00000000..0d5ab12b --- /dev/null +++ b/libs/nanopb/tests/alltypes/alltypes.options @@ -0,0 +1,3 @@ +* max_size:16 +* max_count:5 +*.*fbytes fixed_length:true max_size:4 diff --git a/libs/nanopb/tests/alltypes/alltypes.proto b/libs/nanopb/tests/alltypes/alltypes.proto new file mode 100644 index 00000000..b2250c00 --- /dev/null +++ b/libs/nanopb/tests/alltypes/alltypes.proto @@ -0,0 +1,125 @@ +syntax = "proto2"; +// package name placeholder + +message SubMessage { + required string substuff1 = 1 [default = "1"]; + required int32 substuff2 = 2 [default = 2]; + optional fixed32 substuff3 = 3 [default = 3]; +} + +message EmptyMessage { + +} + +enum HugeEnum { + Negative = -2147483647; /* protoc doesn't accept -2147483648 here */ + Positive = 2147483647; +} + +message Limits { + required int32 int32_min = 1 [default = 2147483647]; + required int32 int32_max = 2 [default = -2147483647]; + required uint32 uint32_min = 3 [default = 4294967295]; + required uint32 uint32_max = 4 [default = 0]; + required int64 int64_min = 5 [default = 9223372036854775807]; + required int64 int64_max = 6 [default = -9223372036854775807]; + required uint64 uint64_min = 7 [default = 18446744073709551615]; + required uint64 uint64_max = 8 [default = 0]; + required HugeEnum enum_min = 9 [default = Positive]; + required HugeEnum enum_max = 10 [default = Negative]; +} + +enum MyEnum { + Zero = 0; + First = 1; + Second = 2; + Truth = 42; +} + +message AllTypes { + required int32 req_int32 = 1; + required int64 req_int64 = 2; + required uint32 req_uint32 = 3; + required uint64 req_uint64 = 4; + required sint32 req_sint32 = 5; + required sint64 req_sint64 = 6; + required bool req_bool = 7; + + required fixed32 req_fixed32 = 8; + required sfixed32 req_sfixed32= 9; + required float req_float = 10; + + required fixed64 req_fixed64 = 11; + required sfixed64 req_sfixed64= 12; + required double req_double = 13; + + required string req_string = 14; + required bytes req_bytes = 15; + required SubMessage req_submsg = 16; + required MyEnum req_enum = 17; + required EmptyMessage req_emptymsg = 18; + required bytes req_fbytes = 19; + + repeated int32 rep_int32 = 21 [packed = true]; + repeated int64 rep_int64 = 22 [packed = true]; + repeated uint32 rep_uint32 = 23 [packed = true]; + repeated uint64 rep_uint64 = 24 [packed = true]; + repeated sint32 rep_sint32 = 25 [packed = true]; + repeated sint64 rep_sint64 = 26 [packed = true]; + repeated bool rep_bool = 27 [packed = true]; + + repeated fixed32 rep_fixed32 = 28 [packed = true]; + repeated sfixed32 rep_sfixed32= 29 [packed = true]; + repeated float rep_float = 30 [packed = true]; + + repeated fixed64 rep_fixed64 = 31 [packed = true]; + repeated sfixed64 rep_sfixed64= 32 [packed = true]; + repeated double rep_double = 33 [packed = true]; + + repeated string rep_string = 34; + repeated bytes rep_bytes = 35; + repeated SubMessage rep_submsg = 36; + repeated MyEnum rep_enum = 37 [packed = true]; + repeated EmptyMessage rep_emptymsg = 38; + repeated bytes rep_fbytes = 39; + + optional int32 opt_int32 = 41 [default = 4041]; + optional int64 opt_int64 = 42 [default = 4042]; + optional uint32 opt_uint32 = 43 [default = 4043]; + optional uint64 opt_uint64 = 44 [default = 4044]; + optional sint32 opt_sint32 = 45 [default = 4045]; + optional sint64 opt_sint64 = 46 [default = 4046]; + optional bool opt_bool = 47 [default = false]; + + optional fixed32 opt_fixed32 = 48 [default = 4048]; + optional sfixed32 opt_sfixed32= 49 [default = 4049]; + optional float opt_float = 50 [default = 4050]; + + optional fixed64 opt_fixed64 = 51 [default = 4051]; + optional sfixed64 opt_sfixed64= 52 [default = 4052]; + optional double opt_double = 53 [default = 4053]; + + optional string opt_string = 54 [default = "4054"]; + optional bytes opt_bytes = 55 [default = "4055"]; + optional SubMessage opt_submsg = 56; + optional MyEnum opt_enum = 57 [default = Second]; + optional EmptyMessage opt_emptymsg = 58; + optional bytes opt_fbytes = 59 [default = "4059"]; + + oneof oneof + { + SubMessage oneof_msg1 = 60; + EmptyMessage oneof_msg2 = 61; + } + + // Check that extreme integer values are handled correctly + required Limits req_limits = 98; + + // Just to make sure that the size of the fields has been calculated + // properly, i.e. otherwise a bug in last field might not be detected. + required int32 end = 99; + + + extensions 200 to 255; +} + diff --git a/libs/nanopb/tests/alltypes/decode_alltypes.c b/libs/nanopb/tests/alltypes/decode_alltypes.c new file mode 100644 index 00000000..2e609e56 --- /dev/null +++ b/libs/nanopb/tests/alltypes/decode_alltypes.c @@ -0,0 +1,229 @@ +/* Tests the decoding of all types. + * This is the counterpart of test_encode3. + * Run e.g. ./test_encode3 | ./test_decode3 + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +#define TEST(x) if (!(x)) { \ + printf("Test " #x " failed.\n"); \ + return false; \ + } + +/* This function is called once from main(), it handles + the decoding and checks the fields. */ +bool check_alltypes(pb_istream_t *stream, int mode) +{ + /* Uses _init_default to just make sure that it works. */ + AllTypes alltypes = AllTypes_init_default; + + /* Fill with garbage to better detect initialization errors */ + memset(&alltypes, 0xAA, sizeof(alltypes)); + alltypes.extensions = 0; + + if (!pb_decode(stream, AllTypes_fields, &alltypes)) + return false; + + TEST(alltypes.req_int32 == -1001); + TEST(alltypes.req_int64 == -1002); + TEST(alltypes.req_uint32 == 1003); + TEST(alltypes.req_uint64 == 1004); + TEST(alltypes.req_sint32 == -1005); + TEST(alltypes.req_sint64 == -1006); + TEST(alltypes.req_bool == true); + + TEST(alltypes.req_fixed32 == 1008); + TEST(alltypes.req_sfixed32 == -1009); + TEST(alltypes.req_float == 1010.0f); + + TEST(alltypes.req_fixed64 == 1011); + TEST(alltypes.req_sfixed64 == -1012); + TEST(alltypes.req_double == 1013.0f); + + TEST(strcmp(alltypes.req_string, "1014") == 0); + TEST(alltypes.req_bytes.size == 4); + TEST(memcmp(alltypes.req_bytes.bytes, "1015", 4) == 0); + TEST(strcmp(alltypes.req_submsg.substuff1, "1016") == 0); + TEST(alltypes.req_submsg.substuff2 == 1016); + TEST(alltypes.req_submsg.substuff3 == 3); + TEST(alltypes.req_enum == MyEnum_Truth); + TEST(memcmp(alltypes.req_fbytes, "1019", 4) == 0); + + TEST(alltypes.rep_int32_count == 5 && alltypes.rep_int32[4] == -2001 && alltypes.rep_int32[0] == 0); + TEST(alltypes.rep_int64_count == 5 && alltypes.rep_int64[4] == -2002 && alltypes.rep_int64[0] == 0); + TEST(alltypes.rep_uint32_count == 5 && alltypes.rep_uint32[4] == 2003 && alltypes.rep_uint32[0] == 0); + TEST(alltypes.rep_uint64_count == 5 && alltypes.rep_uint64[4] == 2004 && alltypes.rep_uint64[0] == 0); + TEST(alltypes.rep_sint32_count == 5 && alltypes.rep_sint32[4] == -2005 && alltypes.rep_sint32[0] == 0); + TEST(alltypes.rep_sint64_count == 5 && alltypes.rep_sint64[4] == -2006 && alltypes.rep_sint64[0] == 0); + TEST(alltypes.rep_bool_count == 5 && alltypes.rep_bool[4] == true && alltypes.rep_bool[0] == false); + + TEST(alltypes.rep_fixed32_count == 5 && alltypes.rep_fixed32[4] == 2008 && alltypes.rep_fixed32[0] == 0); + TEST(alltypes.rep_sfixed32_count == 5 && alltypes.rep_sfixed32[4] == -2009 && alltypes.rep_sfixed32[0] == 0); + TEST(alltypes.rep_float_count == 5 && alltypes.rep_float[4] == 2010.0f && alltypes.rep_float[0] == 0.0f); + + TEST(alltypes.rep_fixed64_count == 5 && alltypes.rep_fixed64[4] == 2011 && alltypes.rep_fixed64[0] == 0); + TEST(alltypes.rep_sfixed64_count == 5 && alltypes.rep_sfixed64[4] == -2012 && alltypes.rep_sfixed64[0] == 0); + TEST(alltypes.rep_double_count == 5 && alltypes.rep_double[4] == 2013.0 && alltypes.rep_double[0] == 0.0); + + TEST(alltypes.rep_string_count == 5 && strcmp(alltypes.rep_string[4], "2014") == 0 && alltypes.rep_string[0][0] == '\0'); + TEST(alltypes.rep_bytes_count == 5 && alltypes.rep_bytes[4].size == 4 && alltypes.rep_bytes[0].size == 0); + TEST(memcmp(alltypes.rep_bytes[4].bytes, "2015", 4) == 0); + + TEST(alltypes.rep_submsg_count == 5); + TEST(strcmp(alltypes.rep_submsg[4].substuff1, "2016") == 0 && alltypes.rep_submsg[0].substuff1[0] == '\0'); + TEST(alltypes.rep_submsg[4].substuff2 == 2016 && alltypes.rep_submsg[0].substuff2 == 0); + TEST(alltypes.rep_submsg[4].substuff3 == 2016 && alltypes.rep_submsg[0].substuff3 == 3); + + TEST(alltypes.rep_enum_count == 5 && alltypes.rep_enum[4] == MyEnum_Truth && alltypes.rep_enum[0] == MyEnum_Zero); + TEST(alltypes.rep_emptymsg_count == 5); + TEST(alltypes.rep_fbytes_count == 5); + TEST(alltypes.rep_fbytes[0][0] == 0 && alltypes.rep_fbytes[0][3] == 0); + TEST(memcmp(alltypes.rep_fbytes[4], "2019", 4) == 0); + + if (mode == 0) + { + /* Expect default values */ + TEST(alltypes.has_opt_int32 == false); + TEST(alltypes.opt_int32 == 4041); + TEST(alltypes.has_opt_int64 == false); + TEST(alltypes.opt_int64 == 4042); + TEST(alltypes.has_opt_uint32 == false); + TEST(alltypes.opt_uint32 == 4043); + TEST(alltypes.has_opt_uint64 == false); + TEST(alltypes.opt_uint64 == 4044); + TEST(alltypes.has_opt_sint32 == false); + TEST(alltypes.opt_sint32 == 4045); + TEST(alltypes.has_opt_sint64 == false); + TEST(alltypes.opt_sint64 == 4046); + TEST(alltypes.has_opt_bool == false); + TEST(alltypes.opt_bool == false); + + TEST(alltypes.has_opt_fixed32 == false); + TEST(alltypes.opt_fixed32 == 4048); + TEST(alltypes.has_opt_sfixed32 == false); + TEST(alltypes.opt_sfixed32 == 4049); + TEST(alltypes.has_opt_float == false); + TEST(alltypes.opt_float == 4050.0f); + + TEST(alltypes.has_opt_fixed64 == false); + TEST(alltypes.opt_fixed64 == 4051); + TEST(alltypes.has_opt_sfixed64 == false); + TEST(alltypes.opt_sfixed64 == 4052); + TEST(alltypes.has_opt_double == false); + TEST(alltypes.opt_double == 4053.0); + + TEST(alltypes.has_opt_string == false); + TEST(strcmp(alltypes.opt_string, "4054") == 0); + TEST(alltypes.has_opt_bytes == false); + TEST(alltypes.opt_bytes.size == 4); + TEST(memcmp(alltypes.opt_bytes.bytes, "4055", 4) == 0); + TEST(alltypes.has_opt_submsg == false); + TEST(strcmp(alltypes.opt_submsg.substuff1, "1") == 0); + TEST(alltypes.opt_submsg.substuff2 == 2); + TEST(alltypes.opt_submsg.substuff3 == 3); + TEST(alltypes.has_opt_enum == false); + TEST(alltypes.opt_enum == MyEnum_Second); + TEST(alltypes.has_opt_emptymsg == false); + TEST(alltypes.has_opt_fbytes == false); + TEST(memcmp(alltypes.opt_fbytes, "4059", 4) == 0); + + TEST(alltypes.which_oneof == 0); + } + else + { + /* Expect filled-in values */ + TEST(alltypes.has_opt_int32 == true); + TEST(alltypes.opt_int32 == 3041); + TEST(alltypes.has_opt_int64 == true); + TEST(alltypes.opt_int64 == 3042); + TEST(alltypes.has_opt_uint32 == true); + TEST(alltypes.opt_uint32 == 3043); + TEST(alltypes.has_opt_uint64 == true); + TEST(alltypes.opt_uint64 == 3044); + TEST(alltypes.has_opt_sint32 == true); + TEST(alltypes.opt_sint32 == 3045); + TEST(alltypes.has_opt_sint64 == true); + TEST(alltypes.opt_sint64 == 3046); + TEST(alltypes.has_opt_bool == true); + TEST(alltypes.opt_bool == true); + + TEST(alltypes.has_opt_fixed32 == true); + TEST(alltypes.opt_fixed32 == 3048); + TEST(alltypes.has_opt_sfixed32 == true); + TEST(alltypes.opt_sfixed32 == 3049); + TEST(alltypes.has_opt_float == true); + TEST(alltypes.opt_float == 3050.0f); + + TEST(alltypes.has_opt_fixed64 == true); + TEST(alltypes.opt_fixed64 == 3051); + TEST(alltypes.has_opt_sfixed64 == true); + TEST(alltypes.opt_sfixed64 == 3052); + TEST(alltypes.has_opt_double == true); + TEST(alltypes.opt_double == 3053.0); + + TEST(alltypes.has_opt_string == true); + TEST(strcmp(alltypes.opt_string, "3054") == 0); + TEST(alltypes.has_opt_bytes == true); + TEST(alltypes.opt_bytes.size == 4); + TEST(memcmp(alltypes.opt_bytes.bytes, "3055", 4) == 0); + TEST(alltypes.has_opt_submsg == true); + TEST(strcmp(alltypes.opt_submsg.substuff1, "3056") == 0); + TEST(alltypes.opt_submsg.substuff2 == 3056); + TEST(alltypes.opt_submsg.substuff3 == 3); + TEST(alltypes.has_opt_enum == true); + TEST(alltypes.opt_enum == MyEnum_Truth); + TEST(alltypes.has_opt_emptymsg == true); + TEST(alltypes.has_opt_fbytes == true); + TEST(memcmp(alltypes.opt_fbytes, "3059", 4) == 0); + + TEST(alltypes.which_oneof == AllTypes_oneof_msg1_tag); + TEST(strcmp(alltypes.oneof.oneof_msg1.substuff1, "4059") == 0); + TEST(alltypes.oneof.oneof_msg1.substuff2 == 4059); + } + + TEST(alltypes.req_limits.int32_min == INT32_MIN); + TEST(alltypes.req_limits.int32_max == INT32_MAX); + TEST(alltypes.req_limits.uint32_min == 0); + TEST(alltypes.req_limits.uint32_max == UINT32_MAX); + TEST(alltypes.req_limits.int64_min == INT64_MIN); + TEST(alltypes.req_limits.int64_max == INT64_MAX); + TEST(alltypes.req_limits.uint64_min == 0); + TEST(alltypes.req_limits.uint64_max == UINT64_MAX); + TEST(alltypes.req_limits.enum_min == HugeEnum_Negative); + TEST(alltypes.req_limits.enum_max == HugeEnum_Positive); + + TEST(alltypes.end == 1099); + + return true; +} + +int main(int argc, char **argv) +{ + uint8_t buffer[1024]; + size_t count; + pb_istream_t stream; + + /* Whether to expect the optional values or the default values. */ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Read the data into buffer */ + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + + /* Construct a pb_istream_t for reading from the buffer */ + stream = pb_istream_from_buffer(buffer, count); + + /* Decode and print out the stuff */ + if (!check_alltypes(&stream, mode)) + { + printf("Parsing failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } else { + return 0; + } +} diff --git a/libs/nanopb/tests/alltypes/encode_alltypes.c b/libs/nanopb/tests/alltypes/encode_alltypes.c new file mode 100644 index 00000000..1b863555 --- /dev/null +++ b/libs/nanopb/tests/alltypes/encode_alltypes.c @@ -0,0 +1,155 @@ +/* Attempts to test all the datatypes supported by ProtoBuf. + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +int main(int argc, char **argv) +{ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Initialize the structure with constants */ + AllTypes alltypes = AllTypes_init_zero; + + alltypes.req_int32 = -1001; + alltypes.req_int64 = -1002; + alltypes.req_uint32 = 1003; + alltypes.req_uint64 = 1004; + alltypes.req_sint32 = -1005; + alltypes.req_sint64 = -1006; + alltypes.req_bool = true; + + alltypes.req_fixed32 = 1008; + alltypes.req_sfixed32 = -1009; + alltypes.req_float = 1010.0f; + + alltypes.req_fixed64 = 1011; + alltypes.req_sfixed64 = -1012; + alltypes.req_double = 1013.0; + + strcpy(alltypes.req_string, "1014"); + alltypes.req_bytes.size = 4; + memcpy(alltypes.req_bytes.bytes, "1015", 4); + strcpy(alltypes.req_submsg.substuff1, "1016"); + alltypes.req_submsg.substuff2 = 1016; + alltypes.req_enum = MyEnum_Truth; + memcpy(alltypes.req_fbytes, "1019", 4); + + alltypes.rep_int32_count = 5; alltypes.rep_int32[4] = -2001; + alltypes.rep_int64_count = 5; alltypes.rep_int64[4] = -2002; + alltypes.rep_uint32_count = 5; alltypes.rep_uint32[4] = 2003; + alltypes.rep_uint64_count = 5; alltypes.rep_uint64[4] = 2004; + alltypes.rep_sint32_count = 5; alltypes.rep_sint32[4] = -2005; + alltypes.rep_sint64_count = 5; alltypes.rep_sint64[4] = -2006; + alltypes.rep_bool_count = 5; alltypes.rep_bool[4] = true; + + alltypes.rep_fixed32_count = 5; alltypes.rep_fixed32[4] = 2008; + alltypes.rep_sfixed32_count = 5; alltypes.rep_sfixed32[4] = -2009; + alltypes.rep_float_count = 5; alltypes.rep_float[4] = 2010.0f; + + alltypes.rep_fixed64_count = 5; alltypes.rep_fixed64[4] = 2011; + alltypes.rep_sfixed64_count = 5; alltypes.rep_sfixed64[4] = -2012; + alltypes.rep_double_count = 5; alltypes.rep_double[4] = 2013.0; + + alltypes.rep_string_count = 5; strcpy(alltypes.rep_string[4], "2014"); + alltypes.rep_bytes_count = 5; alltypes.rep_bytes[4].size = 4; + memcpy(alltypes.rep_bytes[4].bytes, "2015", 4); + + alltypes.rep_submsg_count = 5; + strcpy(alltypes.rep_submsg[4].substuff1, "2016"); + alltypes.rep_submsg[4].substuff2 = 2016; + alltypes.rep_submsg[4].has_substuff3 = true; + alltypes.rep_submsg[4].substuff3 = 2016; + + alltypes.rep_enum_count = 5; alltypes.rep_enum[4] = MyEnum_Truth; + alltypes.rep_emptymsg_count = 5; + + alltypes.rep_fbytes_count = 5; + memcpy(alltypes.rep_fbytes[4], "2019", 4); + + alltypes.req_limits.int32_min = INT32_MIN; + alltypes.req_limits.int32_max = INT32_MAX; + alltypes.req_limits.uint32_min = 0; + alltypes.req_limits.uint32_max = UINT32_MAX; + alltypes.req_limits.int64_min = INT64_MIN; + alltypes.req_limits.int64_max = INT64_MAX; + alltypes.req_limits.uint64_min = 0; + alltypes.req_limits.uint64_max = UINT64_MAX; + alltypes.req_limits.enum_min = HugeEnum_Negative; + alltypes.req_limits.enum_max = HugeEnum_Positive; + + if (mode != 0) + { + /* Fill in values for optional fields */ + alltypes.has_opt_int32 = true; + alltypes.opt_int32 = 3041; + alltypes.has_opt_int64 = true; + alltypes.opt_int64 = 3042; + alltypes.has_opt_uint32 = true; + alltypes.opt_uint32 = 3043; + alltypes.has_opt_uint64 = true; + alltypes.opt_uint64 = 3044; + alltypes.has_opt_sint32 = true; + alltypes.opt_sint32 = 3045; + alltypes.has_opt_sint64 = true; + alltypes.opt_sint64 = 3046; + alltypes.has_opt_bool = true; + alltypes.opt_bool = true; + + alltypes.has_opt_fixed32 = true; + alltypes.opt_fixed32 = 3048; + alltypes.has_opt_sfixed32 = true; + alltypes.opt_sfixed32 = 3049; + alltypes.has_opt_float = true; + alltypes.opt_float = 3050.0f; + + alltypes.has_opt_fixed64 = true; + alltypes.opt_fixed64 = 3051; + alltypes.has_opt_sfixed64 = true; + alltypes.opt_sfixed64 = 3052; + alltypes.has_opt_double = true; + alltypes.opt_double = 3053.0; + + alltypes.has_opt_string = true; + strcpy(alltypes.opt_string, "3054"); + alltypes.has_opt_bytes = true; + alltypes.opt_bytes.size = 4; + memcpy(alltypes.opt_bytes.bytes, "3055", 4); + alltypes.has_opt_submsg = true; + strcpy(alltypes.opt_submsg.substuff1, "3056"); + alltypes.opt_submsg.substuff2 = 3056; + alltypes.has_opt_enum = true; + alltypes.opt_enum = MyEnum_Truth; + alltypes.has_opt_emptymsg = true; + alltypes.has_opt_fbytes = true; + memcpy(alltypes.opt_fbytes, "3059", 4); + + alltypes.which_oneof = AllTypes_oneof_msg1_tag; + strcpy(alltypes.oneof.oneof_msg1.substuff1, "4059"); + alltypes.oneof.oneof_msg1.substuff2 = 4059; + } + + alltypes.end = 1099; + + { + uint8_t buffer[AllTypes_size]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Now encode it and check if we succeeded. */ + if (pb_encode(&stream, AllTypes_fields, &alltypes)) + { + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; /* Success */ + } + else + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; /* Failure */ + } + } +} diff --git a/libs/nanopb/tests/alltypes_callback/SConscript b/libs/nanopb/tests/alltypes_callback/SConscript new file mode 100644 index 00000000..8be53908 --- /dev/null +++ b/libs/nanopb/tests/alltypes_callback/SConscript @@ -0,0 +1,28 @@ +# Test the AllTypes encoding & decoding using callbacks for all fields. + +Import("env", "malloc_env") + +c = Copy("$TARGET", "$SOURCE") +env.Command("alltypes.proto", "#alltypes/alltypes.proto", c) + +env.NanopbProto(["alltypes", "alltypes.options"]) +enc = env.Program(["encode_alltypes_callback.c", "alltypes.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) +dec = env.Program(["decode_alltypes_callback.c", "alltypes.pb.c", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) + +refdec = "$BUILD/alltypes/decode_alltypes$PROGSUFFIX" + +# Encode and compare results +env.RunTest(enc) +env.RunTest("decode_alltypes.output", [refdec, "encode_alltypes_callback.output"]) +env.RunTest("decode_alltypes_callback.output", [dec, "encode_alltypes_callback.output"]) + +# Do the same thing with the optional fields present +env.RunTest("optionals.output", enc, ARGS = ['1']) +env.RunTest("optionals.refdecout", [refdec, "optionals.output"], ARGS = ['1']) +env.RunTest("optionals.decout", [dec, "optionals.output"], ARGS = ['1']) + +# Try with malloc support also +mallocbin1 = malloc_env.Object("decode_with_malloc.o", "decode_alltypes_callback.c") +mallocbin2 = malloc_env.Object("alltypes_malloc.pb.o", "alltypes.pb.c") +mallocdec = malloc_env.Program("decode_with_malloc", [mallocbin1, mallocbin2, "$COMMON/pb_decode_with_malloc.o", "$COMMON/pb_common_with_malloc.o", "$COMMON/malloc_wrappers.o"]) +env.RunTest("decode_with_malloc.output", [mallocdec, "encode_alltypes_callback.output"]) diff --git a/libs/nanopb/tests/alltypes_callback/alltypes.options b/libs/nanopb/tests/alltypes_callback/alltypes.options new file mode 100644 index 00000000..74d7a9c0 --- /dev/null +++ b/libs/nanopb/tests/alltypes_callback/alltypes.options @@ -0,0 +1,8 @@ +# Generate all fields as callbacks. +AllTypes.* type:FT_CALLBACK +SubMessage.substuff1 max_size:16 +AllTypes.oneof no_unions:true + +# With FT_CALLBACK, these options should get ignored +*.*fbytes fixed_length:true max_size:4 + diff --git a/libs/nanopb/tests/alltypes_callback/decode_alltypes_callback.c b/libs/nanopb/tests/alltypes_callback/decode_alltypes_callback.c new file mode 100644 index 00000000..576ce307 --- /dev/null +++ b/libs/nanopb/tests/alltypes_callback/decode_alltypes_callback.c @@ -0,0 +1,442 @@ +/* Attempts to test all the datatypes supported by ProtoBuf when used as callback fields. + * Note that normally there would be no reason to use callback fields for this, + * because each encoder defined here only gives a single field. + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +#define TEST(x) if (!(x)) { \ + printf("Test " #x " failed (in field %d).\n", field->tag); \ + return false; \ + } + +static bool read_varint(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint64_t value; + if (!pb_decode_varint(stream, &value)) + return false; + + TEST((int64_t)value == (long)*arg); + return true; +} + +static bool read_svarint(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + int64_t value; + if (!pb_decode_svarint(stream, &value)) + return false; + + TEST(value == (long)*arg); + return true; +} + +static bool read_fixed32(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint32_t value; + if (!pb_decode_fixed32(stream, &value)) + return false; + + TEST(value == *(uint32_t*)*arg); + return true; +} + +static bool read_fixed64(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint64_t value; + if (!pb_decode_fixed64(stream, &value)) + return false; + + TEST(value == *(uint64_t*)*arg); + return true; +} + +static bool read_string(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint8_t buf[16] = {0}; + size_t len = stream->bytes_left; + + if (len > sizeof(buf) - 1 || !pb_read(stream, buf, len)) + return false; + + TEST(strcmp((char*)buf, *arg) == 0); + return true; +} + +static bool read_submsg(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + SubMessage submsg = {""}; + SubMessage *ref = *arg; + + if (!pb_decode(stream, SubMessage_fields, &submsg)) + return false; + + TEST(strcmp(submsg.substuff1, ref->substuff1) == 0); + TEST(submsg.substuff2 == ref->substuff2); + TEST(submsg.has_substuff3 == ref->has_substuff3); + TEST(submsg.substuff3 == ref->substuff3); + return true; +} + +static bool read_emptymsg(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + EmptyMessage emptymsg = {0}; + return pb_decode(stream, EmptyMessage_fields, &emptymsg); +} + +static bool read_repeated_varint(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + int32_t** expected = (int32_t**)arg; + uint64_t value; + if (!pb_decode_varint(stream, &value)) + return false; + + TEST(*(*expected)++ == value); + return true; +} + +static bool read_repeated_svarint(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + int32_t** expected = (int32_t**)arg; + int64_t value; + if (!pb_decode_svarint(stream, &value)) + return false; + + TEST(*(*expected)++ == value); + return true; +} + +static bool read_repeated_fixed32(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint32_t** expected = (uint32_t**)arg; + uint32_t value; + if (!pb_decode_fixed32(stream, &value)) + return false; + + TEST(*(*expected)++ == value); + return true; +} + +static bool read_repeated_fixed64(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint64_t** expected = (uint64_t**)arg; + uint64_t value; + if (!pb_decode_fixed64(stream, &value)) + return false; + + TEST(*(*expected)++ == value); + return true; +} + +static bool read_repeated_string(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint8_t*** expected = (uint8_t***)arg; + uint8_t buf[16] = {0}; + size_t len = stream->bytes_left; + + if (len > sizeof(buf) - 1 || !pb_read(stream, buf, len)) + return false; + + TEST(strcmp((char*)*(*expected)++, (char*)buf) == 0); + return true; +} + +static bool read_repeated_submsg(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + SubMessage** expected = (SubMessage**)arg; + SubMessage submsg = {""}; + if (!pb_decode(stream, SubMessage_fields, &submsg)) + return false; + + TEST(strcmp(submsg.substuff1, (*expected)->substuff1) == 0); + TEST(submsg.substuff2 == (*expected)->substuff2); + TEST(submsg.has_substuff3 == (*expected)->has_substuff3); + TEST(submsg.substuff3 == (*expected)->substuff3); + (*expected)++; + + return true; +} + +static bool read_limits(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + Limits decoded = {0}; + if (!pb_decode(stream, Limits_fields, &decoded)) + return false; + + TEST(decoded.int32_min == INT32_MIN); + TEST(decoded.int32_max == INT32_MAX); + TEST(decoded.uint32_min == 0); + TEST(decoded.uint32_max == UINT32_MAX); + TEST(decoded.int64_min == INT64_MIN); + TEST(decoded.int64_max == INT64_MAX); + TEST(decoded.uint64_min == 0); + TEST(decoded.uint64_max == UINT64_MAX); + TEST(decoded.enum_min == HugeEnum_Negative); + TEST(decoded.enum_max == HugeEnum_Positive); + + return true; +} + +/* This function is called once from main(), it handles + the decoding and checks the fields. */ +bool check_alltypes(pb_istream_t *stream, int mode) +{ + /* Values for use from callbacks through pointers. */ + bool status; + uint32_t req_fixed32 = 1008; + int32_t req_sfixed32 = -1009; + float req_float = 1010.0f; + uint64_t req_fixed64 = 1011; + int64_t req_sfixed64 = -1012; + double req_double = 1013.0; + SubMessage req_submsg = {"1016", 1016, false, 3}; + + int32_t rep_int32[5] = {0, 0, 0, 0, -2001}; + int32_t rep_int64[5] = {0, 0, 0, 0, -2002}; + int32_t rep_uint32[5] = {0, 0, 0, 0, 2003}; + int32_t rep_uint64[5] = {0, 0, 0, 0, 2004}; + int32_t rep_sint32[5] = {0, 0, 0, 0, -2005}; + int32_t rep_sint64[5] = {0, 0, 0, 0, -2006}; + int32_t rep_bool[5] = {false, false, false, false, true}; + uint32_t rep_fixed32[5] = {0, 0, 0, 0, 2008}; + int32_t rep_sfixed32[5] = {0, 0, 0, 0, -2009}; + float rep_float[5] = {0, 0, 0, 0, 2010.0f}; + uint64_t rep_fixed64[5] = {0, 0, 0, 0, 2011}; + int64_t rep_sfixed64[5] = {0, 0, 0, 0, -2012}; + double rep_double[5] = {0, 0, 0, 0, 2013.0}; + char* rep_string[5] = {"", "", "", "", "2014"}; + char* rep_bytes[5] = {"", "", "", "", "2015"}; + SubMessage rep_submsg[5] = {{"", 0, 0, 3}, + {"", 0, 0, 3}, + {"", 0, 0, 3}, + {"", 0, 0, 3}, + {"2016", 2016, true, 2016}}; + int32_t rep_enum[5] = {0, 0, 0, 0, MyEnum_Truth}; + + uint32_t opt_fixed32 = 3048; + int32_t opt_sfixed32 = 3049; + float opt_float = 3050.0f; + uint64_t opt_fixed64 = 3051; + int64_t opt_sfixed64 = 3052; + double opt_double = 3053.0f; + SubMessage opt_submsg = {"3056", 3056, false, 3}; + + SubMessage oneof_msg1 = {"4059", 4059, false, 3}; + + /* Bind callbacks for required fields */ + AllTypes alltypes = AllTypes_init_zero; + + alltypes.req_int32.funcs.decode = &read_varint; + alltypes.req_int32.arg = (void*)-1001; + + alltypes.req_int64.funcs.decode = &read_varint; + alltypes.req_int64.arg = (void*)-1002; + + alltypes.req_uint32.funcs.decode = &read_varint; + alltypes.req_uint32.arg = (void*)1003; + + alltypes.req_uint32.funcs.decode = &read_varint; + alltypes.req_uint32.arg = (void*)1003; + + alltypes.req_uint64.funcs.decode = &read_varint; + alltypes.req_uint64.arg = (void*)1004; + + alltypes.req_sint32.funcs.decode = &read_svarint; + alltypes.req_sint32.arg = (void*)-1005; + + alltypes.req_sint64.funcs.decode = &read_svarint; + alltypes.req_sint64.arg = (void*)-1006; + + alltypes.req_bool.funcs.decode = &read_varint; + alltypes.req_bool.arg = (void*)true; + + alltypes.req_fixed32.funcs.decode = &read_fixed32; + alltypes.req_fixed32.arg = &req_fixed32; + + alltypes.req_sfixed32.funcs.decode = &read_fixed32; + alltypes.req_sfixed32.arg = &req_sfixed32; + + alltypes.req_float.funcs.decode = &read_fixed32; + alltypes.req_float.arg = &req_float; + + alltypes.req_fixed64.funcs.decode = &read_fixed64; + alltypes.req_fixed64.arg = &req_fixed64; + + alltypes.req_sfixed64.funcs.decode = &read_fixed64; + alltypes.req_sfixed64.arg = &req_sfixed64; + + alltypes.req_double.funcs.decode = &read_fixed64; + alltypes.req_double.arg = &req_double; + + alltypes.req_string.funcs.decode = &read_string; + alltypes.req_string.arg = "1014"; + + alltypes.req_bytes.funcs.decode = &read_string; + alltypes.req_bytes.arg = "1015"; + + alltypes.req_submsg.funcs.decode = &read_submsg; + alltypes.req_submsg.arg = &req_submsg; + + alltypes.req_enum.funcs.decode = &read_varint; + alltypes.req_enum.arg = (void*)MyEnum_Truth; + + alltypes.req_emptymsg.funcs.decode = &read_emptymsg; + + /* Bind callbacks for repeated fields */ + alltypes.rep_int32.funcs.decode = &read_repeated_varint; + alltypes.rep_int32.arg = rep_int32; + + alltypes.rep_int64.funcs.decode = &read_repeated_varint; + alltypes.rep_int64.arg = rep_int64; + + alltypes.rep_uint32.funcs.decode = &read_repeated_varint; + alltypes.rep_uint32.arg = rep_uint32; + + alltypes.rep_uint64.funcs.decode = &read_repeated_varint; + alltypes.rep_uint64.arg = rep_uint64; + + alltypes.rep_sint32.funcs.decode = &read_repeated_svarint; + alltypes.rep_sint32.arg = rep_sint32; + + alltypes.rep_sint64.funcs.decode = &read_repeated_svarint; + alltypes.rep_sint64.arg = rep_sint64; + + alltypes.rep_bool.funcs.decode = &read_repeated_varint; + alltypes.rep_bool.arg = rep_bool; + + alltypes.rep_fixed32.funcs.decode = &read_repeated_fixed32; + alltypes.rep_fixed32.arg = rep_fixed32; + + alltypes.rep_sfixed32.funcs.decode = &read_repeated_fixed32; + alltypes.rep_sfixed32.arg = rep_sfixed32; + + alltypes.rep_float.funcs.decode = &read_repeated_fixed32; + alltypes.rep_float.arg = rep_float; + + alltypes.rep_fixed64.funcs.decode = &read_repeated_fixed64; + alltypes.rep_fixed64.arg = rep_fixed64; + + alltypes.rep_sfixed64.funcs.decode = &read_repeated_fixed64; + alltypes.rep_sfixed64.arg = rep_sfixed64; + + alltypes.rep_double.funcs.decode = &read_repeated_fixed64; + alltypes.rep_double.arg = rep_double; + + alltypes.rep_string.funcs.decode = &read_repeated_string; + alltypes.rep_string.arg = rep_string; + + alltypes.rep_bytes.funcs.decode = &read_repeated_string; + alltypes.rep_bytes.arg = rep_bytes; + + alltypes.rep_submsg.funcs.decode = &read_repeated_submsg; + alltypes.rep_submsg.arg = rep_submsg; + + alltypes.rep_enum.funcs.decode = &read_repeated_varint; + alltypes.rep_enum.arg = rep_enum; + + alltypes.rep_emptymsg.funcs.decode = &read_emptymsg; + + alltypes.req_limits.funcs.decode = &read_limits; + + alltypes.end.funcs.decode = &read_varint; + alltypes.end.arg = (void*)1099; + + /* Bind callbacks for optional fields */ + if (mode == 1) + { + alltypes.opt_int32.funcs.decode = &read_varint; + alltypes.opt_int32.arg = (void*)3041; + + alltypes.opt_int64.funcs.decode = &read_varint; + alltypes.opt_int64.arg = (void*)3042; + + alltypes.opt_uint32.funcs.decode = &read_varint; + alltypes.opt_uint32.arg = (void*)3043; + + alltypes.opt_uint64.funcs.decode = &read_varint; + alltypes.opt_uint64.arg = (void*)3044; + + alltypes.opt_sint32.funcs.decode = &read_svarint; + alltypes.opt_sint32.arg = (void*)3045; + + alltypes.opt_sint64.funcs.decode = &read_svarint; + alltypes.opt_sint64.arg = (void*)3046; + + alltypes.opt_bool.funcs.decode = &read_varint; + alltypes.opt_bool.arg = (void*)true; + + alltypes.opt_fixed32.funcs.decode = &read_fixed32; + alltypes.opt_fixed32.arg = &opt_fixed32; + + alltypes.opt_sfixed32.funcs.decode = &read_fixed32; + alltypes.opt_sfixed32.arg = &opt_sfixed32; + + alltypes.opt_float.funcs.decode = &read_fixed32; + alltypes.opt_float.arg = &opt_float; + + alltypes.opt_fixed64.funcs.decode = &read_fixed64; + alltypes.opt_fixed64.arg = &opt_fixed64; + + alltypes.opt_sfixed64.funcs.decode = &read_fixed64; + alltypes.opt_sfixed64.arg = &opt_sfixed64; + + alltypes.opt_double.funcs.decode = &read_fixed64; + alltypes.opt_double.arg = &opt_double; + + alltypes.opt_string.funcs.decode = &read_string; + alltypes.opt_string.arg = "3054"; + + alltypes.opt_bytes.funcs.decode = &read_string; + alltypes.opt_bytes.arg = "3055"; + + alltypes.opt_submsg.funcs.decode = &read_submsg; + alltypes.opt_submsg.arg = &opt_submsg; + + alltypes.opt_enum.funcs.decode = &read_varint; + alltypes.opt_enum.arg = (void*)MyEnum_Truth; + + alltypes.opt_emptymsg.funcs.decode = &read_emptymsg; + + alltypes.oneof_msg1.funcs.decode = &read_submsg; + alltypes.oneof_msg1.arg = &oneof_msg1; + } + + status = pb_decode(stream, AllTypes_fields, &alltypes); + +#ifdef PB_ENABLE_MALLOC + /* Just to check for any interference between pb_release() and callback fields */ + pb_release(AllTypes_fields, &alltypes); +#endif + + return status; +} + +int main(int argc, char **argv) +{ + uint8_t buffer[1024]; + size_t count; + pb_istream_t stream; + + /* Whether to expect the optional values or the default values. */ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Read the data into buffer */ + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + + /* Construct a pb_istream_t for reading from the buffer */ + stream = pb_istream_from_buffer(buffer, count); + + /* Decode and print out the stuff */ + if (!check_alltypes(&stream, mode)) + { + printf("Parsing failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } else { + return 0; + } +} diff --git a/libs/nanopb/tests/alltypes_callback/encode_alltypes_callback.c b/libs/nanopb/tests/alltypes_callback/encode_alltypes_callback.c new file mode 100644 index 00000000..b206783b --- /dev/null +++ b/libs/nanopb/tests/alltypes_callback/encode_alltypes_callback.c @@ -0,0 +1,411 @@ +/* Attempts to test all the datatypes supported by ProtoBuf when used as callback fields. + * Note that normally there would be no reason to use callback fields for this, + * because each encoder defined here only gives a single field. + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +static bool write_varint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, (long)*arg); +} + +static bool write_svarint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, (long)*arg); +} + +static bool write_fixed32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_fixed32(stream, *arg); +} + +static bool write_fixed64(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_fixed64(stream, *arg); +} + +static bool write_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, *arg, strlen(*arg)); +} + +static bool write_submsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, *arg); +} + +static bool write_emptymsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + EmptyMessage emptymsg = {0}; + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg); +} + +static bool write_repeated_varint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, (long)*arg); +} + +static bool write_repeated_svarint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, (long)*arg); +} + +static bool write_repeated_fixed32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + uint32_t dummy = 0; + + /* Make it a packed field */ + return pb_encode_tag(stream, PB_WT_STRING, field->tag) && + pb_encode_varint(stream, 5 * 4) && /* Number of bytes */ + pb_encode_fixed32(stream, &dummy) && + pb_encode_fixed32(stream, &dummy) && + pb_encode_fixed32(stream, &dummy) && + pb_encode_fixed32(stream, &dummy) && + pb_encode_fixed32(stream, *arg); +} + +static bool write_repeated_fixed64(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + uint64_t dummy = 0; + + /* Make it a packed field */ + return pb_encode_tag(stream, PB_WT_STRING, field->tag) && + pb_encode_varint(stream, 5 * 8) && /* Number of bytes */ + pb_encode_fixed64(stream, &dummy) && + pb_encode_fixed64(stream, &dummy) && + pb_encode_fixed64(stream, &dummy) && + pb_encode_fixed64(stream, &dummy) && + pb_encode_fixed64(stream, *arg); +} + +static bool write_repeated_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, 0, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, 0, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, 0, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, 0, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, *arg, strlen(*arg)); +} + +static bool write_repeated_submsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + SubMessage dummy = {""}; + + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, &dummy) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, &dummy) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, &dummy) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, &dummy) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, *arg); +} + +static bool write_limits(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + Limits limits = {0}; + limits.int32_min = INT32_MIN; + limits.int32_max = INT32_MAX; + limits.uint32_min = 0; + limits.uint32_max = UINT32_MAX; + limits.int64_min = INT64_MIN; + limits.int64_max = INT64_MAX; + limits.uint64_min = 0; + limits.uint64_max = UINT64_MAX; + limits.enum_min = HugeEnum_Negative; + limits.enum_max = HugeEnum_Positive; + + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, Limits_fields, &limits); +} + +static bool write_repeated_emptymsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + EmptyMessage emptymsg = {0}; + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg); +} + +int main(int argc, char **argv) +{ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Values for use from callbacks through pointers. */ + uint32_t req_fixed32 = 1008; + int32_t req_sfixed32 = -1009; + float req_float = 1010.0f; + uint64_t req_fixed64 = 1011; + int64_t req_sfixed64 = -1012; + double req_double = 1013.0; + SubMessage req_submsg = {"1016", 1016}; + + uint32_t rep_fixed32 = 2008; + int32_t rep_sfixed32 = -2009; + float rep_float = 2010.0f; + uint64_t rep_fixed64 = 2011; + int64_t rep_sfixed64 = -2012; + double rep_double = 2013.0; + SubMessage rep_submsg = {"2016", 2016, true, 2016}; + + uint32_t opt_fixed32 = 3048; + int32_t opt_sfixed32 = 3049; + float opt_float = 3050.0f; + uint64_t opt_fixed64 = 3051; + int64_t opt_sfixed64 = 3052; + double opt_double = 3053.0f; + SubMessage opt_submsg = {"3056", 3056}; + + SubMessage oneof_msg1 = {"4059", 4059}; + + /* Bind callbacks for required fields */ + AllTypes alltypes = {{{0}}}; + + alltypes.req_int32.funcs.encode = &write_varint; + alltypes.req_int32.arg = (void*)-1001; + + alltypes.req_int64.funcs.encode = &write_varint; + alltypes.req_int64.arg = (void*)-1002; + + alltypes.req_uint32.funcs.encode = &write_varint; + alltypes.req_uint32.arg = (void*)1003; + + alltypes.req_uint32.funcs.encode = &write_varint; + alltypes.req_uint32.arg = (void*)1003; + + alltypes.req_uint64.funcs.encode = &write_varint; + alltypes.req_uint64.arg = (void*)1004; + + alltypes.req_sint32.funcs.encode = &write_svarint; + alltypes.req_sint32.arg = (void*)-1005; + + alltypes.req_sint64.funcs.encode = &write_svarint; + alltypes.req_sint64.arg = (void*)-1006; + + alltypes.req_bool.funcs.encode = &write_varint; + alltypes.req_bool.arg = (void*)true; + + alltypes.req_fixed32.funcs.encode = &write_fixed32; + alltypes.req_fixed32.arg = &req_fixed32; + + alltypes.req_sfixed32.funcs.encode = &write_fixed32; + alltypes.req_sfixed32.arg = &req_sfixed32; + + alltypes.req_float.funcs.encode = &write_fixed32; + alltypes.req_float.arg = &req_float; + + alltypes.req_fixed64.funcs.encode = &write_fixed64; + alltypes.req_fixed64.arg = &req_fixed64; + + alltypes.req_sfixed64.funcs.encode = &write_fixed64; + alltypes.req_sfixed64.arg = &req_sfixed64; + + alltypes.req_double.funcs.encode = &write_fixed64; + alltypes.req_double.arg = &req_double; + + alltypes.req_string.funcs.encode = &write_string; + alltypes.req_string.arg = "1014"; + + alltypes.req_bytes.funcs.encode = &write_string; + alltypes.req_bytes.arg = "1015"; + + alltypes.req_submsg.funcs.encode = &write_submsg; + alltypes.req_submsg.arg = &req_submsg; + + alltypes.req_enum.funcs.encode = &write_varint; + alltypes.req_enum.arg = (void*)MyEnum_Truth; + + alltypes.req_emptymsg.funcs.encode = &write_emptymsg; + + alltypes.req_fbytes.funcs.encode = &write_string; + alltypes.req_fbytes.arg = "1019"; + + /* Bind callbacks for repeated fields */ + alltypes.rep_int32.funcs.encode = &write_repeated_varint; + alltypes.rep_int32.arg = (void*)-2001; + + alltypes.rep_int64.funcs.encode = &write_repeated_varint; + alltypes.rep_int64.arg = (void*)-2002; + + alltypes.rep_uint32.funcs.encode = &write_repeated_varint; + alltypes.rep_uint32.arg = (void*)2003; + + alltypes.rep_uint64.funcs.encode = &write_repeated_varint; + alltypes.rep_uint64.arg = (void*)2004; + + alltypes.rep_sint32.funcs.encode = &write_repeated_svarint; + alltypes.rep_sint32.arg = (void*)-2005; + + alltypes.rep_sint64.funcs.encode = &write_repeated_svarint; + alltypes.rep_sint64.arg = (void*)-2006; + + alltypes.rep_bool.funcs.encode = &write_repeated_varint; + alltypes.rep_bool.arg = (void*)true; + + alltypes.rep_fixed32.funcs.encode = &write_repeated_fixed32; + alltypes.rep_fixed32.arg = &rep_fixed32; + + alltypes.rep_sfixed32.funcs.encode = &write_repeated_fixed32; + alltypes.rep_sfixed32.arg = &rep_sfixed32; + + alltypes.rep_float.funcs.encode = &write_repeated_fixed32; + alltypes.rep_float.arg = &rep_float; + + alltypes.rep_fixed64.funcs.encode = &write_repeated_fixed64; + alltypes.rep_fixed64.arg = &rep_fixed64; + + alltypes.rep_sfixed64.funcs.encode = &write_repeated_fixed64; + alltypes.rep_sfixed64.arg = &rep_sfixed64; + + alltypes.rep_double.funcs.encode = &write_repeated_fixed64; + alltypes.rep_double.arg = &rep_double; + + alltypes.rep_string.funcs.encode = &write_repeated_string; + alltypes.rep_string.arg = "2014"; + + alltypes.rep_bytes.funcs.encode = &write_repeated_string; + alltypes.rep_bytes.arg = "2015"; + + alltypes.rep_submsg.funcs.encode = &write_repeated_submsg; + alltypes.rep_submsg.arg = &rep_submsg; + + alltypes.rep_enum.funcs.encode = &write_repeated_varint; + alltypes.rep_enum.arg = (void*)MyEnum_Truth; + + alltypes.rep_emptymsg.funcs.encode = &write_repeated_emptymsg; + + alltypes.rep_fbytes.funcs.encode = &write_repeated_string; + alltypes.rep_fbytes.arg = "2019"; + + alltypes.req_limits.funcs.encode = &write_limits; + + /* Bind callbacks for optional fields */ + if (mode != 0) + { + alltypes.opt_int32.funcs.encode = &write_varint; + alltypes.opt_int32.arg = (void*)3041; + + alltypes.opt_int64.funcs.encode = &write_varint; + alltypes.opt_int64.arg = (void*)3042; + + alltypes.opt_uint32.funcs.encode = &write_varint; + alltypes.opt_uint32.arg = (void*)3043; + + alltypes.opt_uint64.funcs.encode = &write_varint; + alltypes.opt_uint64.arg = (void*)3044; + + alltypes.opt_sint32.funcs.encode = &write_svarint; + alltypes.opt_sint32.arg = (void*)3045; + + alltypes.opt_sint64.funcs.encode = &write_svarint; + alltypes.opt_sint64.arg = (void*)3046; + + alltypes.opt_bool.funcs.encode = &write_varint; + alltypes.opt_bool.arg = (void*)true; + + alltypes.opt_fixed32.funcs.encode = &write_fixed32; + alltypes.opt_fixed32.arg = &opt_fixed32; + + alltypes.opt_sfixed32.funcs.encode = &write_fixed32; + alltypes.opt_sfixed32.arg = &opt_sfixed32; + + alltypes.opt_float.funcs.encode = &write_fixed32; + alltypes.opt_float.arg = &opt_float; + + alltypes.opt_fixed64.funcs.encode = &write_fixed64; + alltypes.opt_fixed64.arg = &opt_fixed64; + + alltypes.opt_sfixed64.funcs.encode = &write_fixed64; + alltypes.opt_sfixed64.arg = &opt_sfixed64; + + alltypes.opt_double.funcs.encode = &write_fixed64; + alltypes.opt_double.arg = &opt_double; + + alltypes.opt_string.funcs.encode = &write_string; + alltypes.opt_string.arg = "3054"; + + alltypes.opt_bytes.funcs.encode = &write_string; + alltypes.opt_bytes.arg = "3055"; + + alltypes.opt_submsg.funcs.encode = &write_submsg; + alltypes.opt_submsg.arg = &opt_submsg; + + alltypes.opt_enum.funcs.encode = &write_varint; + alltypes.opt_enum.arg = (void*)MyEnum_Truth; + + alltypes.opt_emptymsg.funcs.encode = &write_emptymsg; + + alltypes.opt_fbytes.funcs.encode = &write_string; + alltypes.opt_fbytes.arg = "3059"; + + alltypes.oneof_msg1.funcs.encode = &write_submsg; + alltypes.oneof_msg1.arg = &oneof_msg1; + } + + alltypes.end.funcs.encode = &write_varint; + alltypes.end.arg = (void*)1099; + + { + uint8_t buffer[2048]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Now encode it and check if we succeeded. */ + if (pb_encode(&stream, AllTypes_fields, &alltypes)) + { + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; /* Success */ + } + else + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; /* Failure */ + } + } +} diff --git a/libs/nanopb/tests/alltypes_pointer/SConscript b/libs/nanopb/tests/alltypes_pointer/SConscript new file mode 100644 index 00000000..b095ae03 --- /dev/null +++ b/libs/nanopb/tests/alltypes_pointer/SConscript @@ -0,0 +1,40 @@ +# Encode the AllTypes message using pointers for all fields, and verify the +# output against the normal AllTypes test case. + +Import("env", "malloc_env") + +c = Copy("$TARGET", "$SOURCE") +env.Command("alltypes.proto", "#alltypes/alltypes.proto", c) + +env.NanopbProto(["alltypes", "alltypes.options"]) +enc = malloc_env.Program(["encode_alltypes_pointer.c", + "alltypes.pb.c", + "$COMMON/pb_encode_with_malloc.o", + "$COMMON/pb_common_with_malloc.o", + "$COMMON/malloc_wrappers.o"]) +dec = malloc_env.Program(["decode_alltypes_pointer.c", + "alltypes.pb.c", + "$COMMON/pb_decode_with_malloc.o", + "$COMMON/pb_common_with_malloc.o", + "$COMMON/malloc_wrappers.o"]) + +# Encode and compare results to non-pointer alltypes test case +env.RunTest(enc) +env.Compare(["encode_alltypes_pointer.output", "$BUILD/alltypes/encode_alltypes.output"]) + +# Decode (under valgrind if available) +valgrind = env.WhereIs('valgrind') +kwargs = {} +if valgrind: + kwargs['COMMAND'] = valgrind + kwargs['ARGS'] = ["-q", "--error-exitcode=99", dec[0].abspath] + +env.RunTest("decode_alltypes.output", [dec, "encode_alltypes_pointer.output"], **kwargs) + +# Do the same thing with the optional fields present +env.RunTest("optionals.output", enc, ARGS = ['1']) +env.Compare(["optionals.output", "$BUILD/alltypes/optionals.output"]) + +kwargs['ARGS'] = kwargs.get('ARGS', []) + ['1'] +env.RunTest("optionals.decout", [dec, "optionals.output"], **kwargs) + diff --git a/libs/nanopb/tests/alltypes_pointer/alltypes.options b/libs/nanopb/tests/alltypes_pointer/alltypes.options new file mode 100644 index 00000000..8699fe27 --- /dev/null +++ b/libs/nanopb/tests/alltypes_pointer/alltypes.options @@ -0,0 +1,4 @@ +# Generate all fields as pointers. +* type:FT_POINTER +*.*fbytes fixed_length:true max_size:4 + diff --git a/libs/nanopb/tests/alltypes_pointer/decode_alltypes_pointer.c b/libs/nanopb/tests/alltypes_pointer/decode_alltypes_pointer.c new file mode 100644 index 00000000..4ee6f8bf --- /dev/null +++ b/libs/nanopb/tests/alltypes_pointer/decode_alltypes_pointer.c @@ -0,0 +1,186 @@ +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +#define TEST(x) if (!(x)) { \ + fprintf(stderr, "Test " #x " failed.\n"); \ + status = false; \ + } + +/* This function is called once from main(), it handles + the decoding and checks the fields. */ +bool check_alltypes(pb_istream_t *stream, int mode) +{ + bool status = true; + AllTypes alltypes; + + /* Fill with garbage to better detect initialization errors */ + memset(&alltypes, 0xAA, sizeof(alltypes)); + alltypes.extensions = 0; + + if (!pb_decode(stream, AllTypes_fields, &alltypes)) + return false; + + TEST(alltypes.req_int32 && *alltypes.req_int32 == -1001); + TEST(alltypes.req_int64 && *alltypes.req_int64 == -1002); + TEST(alltypes.req_uint32 && *alltypes.req_uint32 == 1003); + TEST(alltypes.req_uint64 && *alltypes.req_uint64 == 1004); + TEST(alltypes.req_sint32 && *alltypes.req_sint32 == -1005); + TEST(alltypes.req_sint64 && *alltypes.req_sint64 == -1006); + TEST(alltypes.req_bool && *alltypes.req_bool == true); + + TEST(alltypes.req_fixed32 && *alltypes.req_fixed32 == 1008); + TEST(alltypes.req_sfixed32 && *alltypes.req_sfixed32 == -1009); + TEST(alltypes.req_float && *alltypes.req_float == 1010.0f); + + TEST(alltypes.req_fixed64 && *alltypes.req_fixed64 == 1011); + TEST(alltypes.req_sfixed64 && *alltypes.req_sfixed64 == -1012); + TEST(alltypes.req_double && *alltypes.req_double == 1013.0f); + + TEST(alltypes.req_string && strcmp(alltypes.req_string, "1014") == 0); + TEST(alltypes.req_bytes && alltypes.req_bytes->size == 4); + TEST(alltypes.req_bytes && memcmp(&alltypes.req_bytes->bytes, "1015", 4) == 0); + TEST(alltypes.req_submsg && alltypes.req_submsg->substuff1 + && strcmp(alltypes.req_submsg->substuff1, "1016") == 0); + TEST(alltypes.req_submsg && alltypes.req_submsg->substuff2 + && *alltypes.req_submsg->substuff2 == 1016); + TEST(alltypes.req_enum && *alltypes.req_enum == MyEnum_Truth); + TEST(alltypes.req_fbytes && memcmp(alltypes.req_fbytes, "1019", 4) == 0); + + TEST(alltypes.rep_int32_count == 5 && alltypes.rep_int32[4] == -2001 && alltypes.rep_int32[0] == 0); + TEST(alltypes.rep_int64_count == 5 && alltypes.rep_int64[4] == -2002 && alltypes.rep_int64[0] == 0); + TEST(alltypes.rep_uint32_count == 5 && alltypes.rep_uint32[4] == 2003 && alltypes.rep_uint32[0] == 0); + TEST(alltypes.rep_uint64_count == 5 && alltypes.rep_uint64[4] == 2004 && alltypes.rep_uint64[0] == 0); + TEST(alltypes.rep_sint32_count == 5 && alltypes.rep_sint32[4] == -2005 && alltypes.rep_sint32[0] == 0); + TEST(alltypes.rep_sint64_count == 5 && alltypes.rep_sint64[4] == -2006 && alltypes.rep_sint64[0] == 0); + TEST(alltypes.rep_bool_count == 5 && alltypes.rep_bool[4] == true && alltypes.rep_bool[0] == false); + + TEST(alltypes.rep_fixed32_count == 5 && alltypes.rep_fixed32[4] == 2008 && alltypes.rep_fixed32[0] == 0); + TEST(alltypes.rep_sfixed32_count == 5 && alltypes.rep_sfixed32[4] == -2009 && alltypes.rep_sfixed32[0] == 0); + TEST(alltypes.rep_float_count == 5 && alltypes.rep_float[4] == 2010.0f && alltypes.rep_float[0] == 0.0f); + + TEST(alltypes.rep_fixed64_count == 5 && alltypes.rep_fixed64[4] == 2011 && alltypes.rep_fixed64[0] == 0); + TEST(alltypes.rep_sfixed64_count == 5 && alltypes.rep_sfixed64[4] == -2012 && alltypes.rep_sfixed64[0] == 0); + TEST(alltypes.rep_double_count == 5 && alltypes.rep_double[4] == 2013.0 && alltypes.rep_double[0] == 0.0); + + TEST(alltypes.rep_string_count == 5 && strcmp(alltypes.rep_string[4], "2014") == 0 && alltypes.rep_string[0][0] == '\0'); + TEST(alltypes.rep_bytes_count == 5 && alltypes.rep_bytes[4]->size == 4 && alltypes.rep_bytes[0]->size == 0); + TEST(memcmp(&alltypes.rep_bytes[4]->bytes, "2015", 4) == 0); + + TEST(alltypes.rep_submsg_count == 5); + TEST(strcmp(alltypes.rep_submsg[4].substuff1, "2016") == 0 && alltypes.rep_submsg[0].substuff1[0] == '\0'); + TEST(*alltypes.rep_submsg[4].substuff2 == 2016 && *alltypes.rep_submsg[0].substuff2 == 0); + TEST(*alltypes.rep_submsg[4].substuff3 == 2016 && alltypes.rep_submsg[0].substuff3 == NULL); + + TEST(alltypes.rep_enum_count == 5 && alltypes.rep_enum[4] == MyEnum_Truth && alltypes.rep_enum[0] == MyEnum_Zero); + TEST(alltypes.rep_emptymsg_count == 5); + TEST(alltypes.rep_fbytes_count == 5); + TEST(alltypes.rep_fbytes[0][0] == 0 && alltypes.rep_fbytes[0][3] == 0); + TEST(memcmp(alltypes.rep_fbytes[4], "2019", 4) == 0); + + if (mode == 0) + { + /* Expect that optional values are not present */ + TEST(alltypes.opt_int32 == NULL); + TEST(alltypes.opt_int64 == NULL); + TEST(alltypes.opt_uint32 == NULL); + TEST(alltypes.opt_uint64 == NULL); + TEST(alltypes.opt_sint32 == NULL); + TEST(alltypes.opt_sint64 == NULL); + TEST(alltypes.opt_bool == NULL); + + TEST(alltypes.opt_fixed32 == NULL); + TEST(alltypes.opt_sfixed32 == NULL); + TEST(alltypes.opt_float == NULL); + TEST(alltypes.opt_fixed64 == NULL); + TEST(alltypes.opt_sfixed64 == NULL); + TEST(alltypes.opt_double == NULL); + + TEST(alltypes.opt_string == NULL); + TEST(alltypes.opt_bytes == NULL); + TEST(alltypes.opt_submsg == NULL); + TEST(alltypes.opt_enum == NULL); + TEST(alltypes.opt_fbytes == NULL); + + TEST(alltypes.which_oneof == 0); + } + else + { + /* Expect filled-in values */ + TEST(alltypes.opt_int32 && *alltypes.opt_int32 == 3041); + TEST(alltypes.opt_int64 && *alltypes.opt_int64 == 3042); + TEST(alltypes.opt_uint32 && *alltypes.opt_uint32 == 3043); + TEST(alltypes.opt_uint64 && *alltypes.opt_uint64 == 3044); + TEST(alltypes.opt_sint32 && *alltypes.opt_sint32 == 3045); + TEST(alltypes.opt_sint64 && *alltypes.opt_sint64 == 3046); + TEST(alltypes.opt_bool && *alltypes.opt_bool == true); + + TEST(alltypes.opt_fixed32 && *alltypes.opt_fixed32 == 3048); + TEST(alltypes.opt_sfixed32 && *alltypes.opt_sfixed32== 3049); + TEST(alltypes.opt_float && *alltypes.opt_float == 3050.0f); + TEST(alltypes.opt_fixed64 && *alltypes.opt_fixed64 == 3051); + TEST(alltypes.opt_sfixed64 && *alltypes.opt_sfixed64== 3052); + TEST(alltypes.opt_double && *alltypes.opt_double == 3053.0); + + TEST(alltypes.opt_string && strcmp(alltypes.opt_string, "3054") == 0); + TEST(alltypes.opt_bytes && alltypes.opt_bytes->size == 4); + TEST(alltypes.opt_bytes && memcmp(&alltypes.opt_bytes->bytes, "3055", 4) == 0); + TEST(alltypes.opt_submsg && strcmp(alltypes.opt_submsg->substuff1, "3056") == 0); + TEST(alltypes.opt_submsg && *alltypes.opt_submsg->substuff2 == 3056); + TEST(alltypes.opt_enum && *alltypes.opt_enum == MyEnum_Truth); + TEST(alltypes.opt_emptymsg); + TEST(alltypes.opt_fbytes && memcmp(alltypes.opt_fbytes, "3059", 4) == 0); + + TEST(alltypes.which_oneof == AllTypes_oneof_msg1_tag); + TEST(alltypes.oneof.oneof_msg1 && strcmp(alltypes.oneof.oneof_msg1->substuff1, "4059") == 0); + TEST(alltypes.oneof.oneof_msg1->substuff2 && *alltypes.oneof.oneof_msg1->substuff2 == 4059); + } + + TEST(alltypes.req_limits->int32_min && *alltypes.req_limits->int32_min == INT32_MIN); + TEST(alltypes.req_limits->int32_max && *alltypes.req_limits->int32_max == INT32_MAX); + TEST(alltypes.req_limits->uint32_min && *alltypes.req_limits->uint32_min == 0); + TEST(alltypes.req_limits->uint32_max && *alltypes.req_limits->uint32_max == UINT32_MAX); + TEST(alltypes.req_limits->int64_min && *alltypes.req_limits->int64_min == INT64_MIN); + TEST(alltypes.req_limits->int64_max && *alltypes.req_limits->int64_max == INT64_MAX); + TEST(alltypes.req_limits->uint64_min && *alltypes.req_limits->uint64_min == 0); + TEST(alltypes.req_limits->uint64_max && *alltypes.req_limits->uint64_max == UINT64_MAX); + TEST(alltypes.req_limits->enum_min && *alltypes.req_limits->enum_min == HugeEnum_Negative); + TEST(alltypes.req_limits->enum_max && *alltypes.req_limits->enum_max == HugeEnum_Positive); + + TEST(alltypes.end && *alltypes.end == 1099); + + pb_release(AllTypes_fields, &alltypes); + + return status; +} + +int main(int argc, char **argv) +{ + uint8_t buffer[1024]; + size_t count; + pb_istream_t stream; + + /* Whether to expect the optional values or the default values. */ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Read the data into buffer */ + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + + /* Construct a pb_istream_t for reading from the buffer */ + stream = pb_istream_from_buffer(buffer, count); + + /* Decode and verify the message */ + if (!check_alltypes(&stream, mode)) + { + fprintf(stderr, "Test failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } + else + { + return 0; + } +} diff --git a/libs/nanopb/tests/alltypes_pointer/encode_alltypes_pointer.c b/libs/nanopb/tests/alltypes_pointer/encode_alltypes_pointer.c new file mode 100644 index 00000000..a39af6fa --- /dev/null +++ b/libs/nanopb/tests/alltypes_pointer/encode_alltypes_pointer.c @@ -0,0 +1,200 @@ +/* Attempts to test all the datatypes supported by ProtoBuf. + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +int main(int argc, char **argv) +{ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Values for required fields */ + int32_t req_int32 = -1001; + int64_t req_int64 = -1002; + uint32_t req_uint32 = 1003; + uint64_t req_uint64 = 1004; + int32_t req_sint32 = -1005; + int64_t req_sint64 = -1006; + bool req_bool = true; + uint32_t req_fixed32 = 1008; + int32_t req_sfixed32 = -1009; + float req_float = 1010.0f; + uint64_t req_fixed64 = 1011; + int64_t req_sfixed64 = -1012; + double req_double = 1013.0; + char* req_string = "1014"; + PB_BYTES_ARRAY_T(4) req_bytes = {4, {'1', '0', '1', '5'}}; + static int32_t req_substuff = 1016; + SubMessage req_submsg = {"1016", &req_substuff}; + MyEnum req_enum = MyEnum_Truth; + EmptyMessage req_emptymsg = {0}; + pb_byte_t req_fbytes[4] = {'1', '0', '1', '9'}; + + int32_t end = 1099; + + /* Values for repeated fields */ + int32_t rep_int32[5] = {0, 0, 0, 0, -2001}; + int64_t rep_int64[5] = {0, 0, 0, 0, -2002}; + uint32_t rep_uint32[5] = {0, 0, 0, 0, 2003}; + uint64_t rep_uint64[5] = {0, 0, 0, 0, 2004}; + int32_t rep_sint32[5] = {0, 0, 0, 0, -2005}; + int64_t rep_sint64[5] = {0, 0, 0, 0, -2006}; + bool rep_bool[5] = {false, false, false, false, true}; + uint32_t rep_fixed32[5] = {0, 0, 0, 0, 2008}; + int32_t rep_sfixed32[5] = {0, 0, 0, 0, -2009}; + float rep_float[5] = {0, 0, 0, 0, 2010.0f}; + uint64_t rep_fixed64[5] = {0, 0, 0, 0, 2011}; + int64_t rep_sfixed64[5] = {0, 0, 0, 0, -2012}; + double rep_double[5] = {0, 0, 0, 0, 2013.0f}; + char* rep_string[5] = {"", "", "", "", "2014"}; + static PB_BYTES_ARRAY_T(4) rep_bytes_4 = {4, {'2', '0', '1', '5'}}; + pb_bytes_array_t *rep_bytes[5]= {NULL, NULL, NULL, NULL, (pb_bytes_array_t*)&rep_bytes_4}; + static int32_t rep_sub2zero = 0; + static int32_t rep_substuff2 = 2016; + static uint32_t rep_substuff3 = 2016; + SubMessage rep_submsg[5] = {{"", &rep_sub2zero}, + {"", &rep_sub2zero}, + {"", &rep_sub2zero}, + {"", &rep_sub2zero}, + {"2016", &rep_substuff2, &rep_substuff3}}; + MyEnum rep_enum[5] = {0, 0, 0, 0, MyEnum_Truth}; + EmptyMessage rep_emptymsg[5] = {{0}, {0}, {0}, {0}, {0}}; + pb_byte_t rep_fbytes[5][4] = {{0}, {0}, {0}, {0}, {'2', '0', '1', '9'}}; + + /* Values for optional fields */ + int32_t opt_int32 = 3041; + int64_t opt_int64 = 3042; + uint32_t opt_uint32 = 3043; + uint64_t opt_uint64 = 3044; + int32_t opt_sint32 = 3045; + int64_t opt_sint64 = 3046; + bool opt_bool = true; + uint32_t opt_fixed32 = 3048; + int32_t opt_sfixed32 = 3049; + float opt_float = 3050.0f; + uint64_t opt_fixed64 = 3051; + int64_t opt_sfixed64 = 3052; + double opt_double = 3053.0; + char* opt_string = "3054"; + PB_BYTES_ARRAY_T(4) opt_bytes = {4, {'3', '0', '5', '5'}}; + static int32_t opt_substuff = 3056; + SubMessage opt_submsg = {"3056", &opt_substuff}; + MyEnum opt_enum = MyEnum_Truth; + EmptyMessage opt_emptymsg = {0}; + pb_byte_t opt_fbytes[4] = {'3', '0', '5', '9'}; + + static int32_t oneof_substuff = 4059; + SubMessage oneof_msg1 = {"4059", &oneof_substuff}; + + /* Values for the Limits message. */ + static int32_t int32_min = INT32_MIN; + static int32_t int32_max = INT32_MAX; + static uint32_t uint32_min = 0; + static uint32_t uint32_max = UINT32_MAX; + static int64_t int64_min = INT64_MIN; + static int64_t int64_max = INT64_MAX; + static uint64_t uint64_min = 0; + static uint64_t uint64_max = UINT64_MAX; + static HugeEnum enum_min = HugeEnum_Negative; + static HugeEnum enum_max = HugeEnum_Positive; + Limits req_limits = {&int32_min, &int32_max, + &uint32_min, &uint32_max, + &int64_min, &int64_max, + &uint64_min, &uint64_max, + &enum_min, &enum_max}; + + /* Initialize the message struct with pointers to the fields. */ + AllTypes alltypes = {0}; + + alltypes.req_int32 = &req_int32; + alltypes.req_int64 = &req_int64; + alltypes.req_uint32 = &req_uint32; + alltypes.req_uint64 = &req_uint64; + alltypes.req_sint32 = &req_sint32; + alltypes.req_sint64 = &req_sint64; + alltypes.req_bool = &req_bool; + alltypes.req_fixed32 = &req_fixed32; + alltypes.req_sfixed32 = &req_sfixed32; + alltypes.req_float = &req_float; + alltypes.req_fixed64 = &req_fixed64; + alltypes.req_sfixed64 = &req_sfixed64; + alltypes.req_double = &req_double; + alltypes.req_string = req_string; + alltypes.req_bytes = (pb_bytes_array_t*)&req_bytes; + alltypes.req_submsg = &req_submsg; + alltypes.req_enum = &req_enum; + alltypes.req_emptymsg = &req_emptymsg; + alltypes.req_fbytes = &req_fbytes; + alltypes.req_limits = &req_limits; + + alltypes.rep_int32_count = 5; alltypes.rep_int32 = rep_int32; + alltypes.rep_int64_count = 5; alltypes.rep_int64 = rep_int64; + alltypes.rep_uint32_count = 5; alltypes.rep_uint32 = rep_uint32; + alltypes.rep_uint64_count = 5; alltypes.rep_uint64 = rep_uint64; + alltypes.rep_sint32_count = 5; alltypes.rep_sint32 = rep_sint32; + alltypes.rep_sint64_count = 5; alltypes.rep_sint64 = rep_sint64; + alltypes.rep_bool_count = 5; alltypes.rep_bool = rep_bool; + alltypes.rep_fixed32_count = 5; alltypes.rep_fixed32 = rep_fixed32; + alltypes.rep_sfixed32_count = 5; alltypes.rep_sfixed32 = rep_sfixed32; + alltypes.rep_float_count = 5; alltypes.rep_float = rep_float; + alltypes.rep_fixed64_count = 5; alltypes.rep_fixed64 = rep_fixed64; + alltypes.rep_sfixed64_count = 5; alltypes.rep_sfixed64 = rep_sfixed64; + alltypes.rep_double_count = 5; alltypes.rep_double = rep_double; + alltypes.rep_string_count = 5; alltypes.rep_string = rep_string; + alltypes.rep_bytes_count = 5; alltypes.rep_bytes = rep_bytes; + alltypes.rep_submsg_count = 5; alltypes.rep_submsg = rep_submsg; + alltypes.rep_enum_count = 5; alltypes.rep_enum = rep_enum; + alltypes.rep_emptymsg_count = 5; alltypes.rep_emptymsg = rep_emptymsg; + alltypes.rep_fbytes_count = 5; alltypes.rep_fbytes = rep_fbytes; + + if (mode != 0) + { + /* Fill in values for optional fields */ + alltypes.opt_int32 = &opt_int32; + alltypes.opt_int64 = &opt_int64; + alltypes.opt_uint32 = &opt_uint32; + alltypes.opt_uint64 = &opt_uint64; + alltypes.opt_sint32 = &opt_sint32; + alltypes.opt_sint64 = &opt_sint64; + alltypes.opt_bool = &opt_bool; + alltypes.opt_fixed32 = &opt_fixed32; + alltypes.opt_sfixed32 = &opt_sfixed32; + alltypes.opt_float = &opt_float; + alltypes.opt_fixed64 = &opt_fixed64; + alltypes.opt_sfixed64 = &opt_sfixed64; + alltypes.opt_double = &opt_double; + alltypes.opt_string = opt_string; + alltypes.opt_bytes = (pb_bytes_array_t*)&opt_bytes; + alltypes.opt_submsg = &opt_submsg; + alltypes.opt_enum = &opt_enum; + alltypes.opt_emptymsg = &opt_emptymsg; + alltypes.opt_fbytes = &opt_fbytes; + + alltypes.which_oneof = AllTypes_oneof_msg1_tag; + alltypes.oneof.oneof_msg1 = &oneof_msg1; + } + + alltypes.end = &end; + + { + uint8_t buffer[4096]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Now encode it and check if we succeeded. */ + if (pb_encode(&stream, AllTypes_fields, &alltypes)) + { + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; /* Success */ + } + else + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; /* Failure */ + } + } +} diff --git a/libs/nanopb/tests/alltypes_proto3/SConscript b/libs/nanopb/tests/alltypes_proto3/SConscript new file mode 100644 index 00000000..c0b2fc1b --- /dev/null +++ b/libs/nanopb/tests/alltypes_proto3/SConscript @@ -0,0 +1,45 @@ +# Version of AllTypes test case for protobuf 3 file format. + +Import("env") + +import re +match = None +if 'PROTOC_VERSION' in env: + match = re.search('([0-9]+).([0-9]+).([0-9]+)', env['PROTOC_VERSION']) + +if match: + version = map(int, match.groups()) + +# proto3 syntax is supported by protoc >= 3.0.0 +if env.GetOption('clean') or (match and version[0] >= 3): + + env.NanopbProto(["alltypes", "alltypes.options"]) + enc = env.Program(["encode_alltypes.c", "alltypes.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) + dec = env.Program(["decode_alltypes.c", "alltypes.pb.c", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) + + # Test the round-trip from nanopb encoder to nanopb decoder + env.RunTest(enc) + env.RunTest([dec, "encode_alltypes.output"]) + + # Re-encode the data using protoc, and check that the results from nanopb + # match byte-per-byte to the protoc output. + env.Decode("encode_alltypes.output.decoded", + ["encode_alltypes.output", "alltypes.proto"], + MESSAGE='AllTypes') + env.Encode("encode_alltypes.output.recoded", + ["encode_alltypes.output.decoded", "alltypes.proto"], + MESSAGE='AllTypes') + env.Compare(["encode_alltypes.output", "encode_alltypes.output.recoded"]) + + # Do the same checks with the optional fields present. + env.RunTest("optionals.output", enc, ARGS = ['1']) + env.RunTest("optionals.decout", [dec, "optionals.output"], ARGS = ['1']) + env.Decode("optionals.output.decoded", + ["optionals.output", "alltypes.proto"], + MESSAGE='AllTypes') + env.Encode("optionals.output.recoded", + ["optionals.output.decoded", "alltypes.proto"], + MESSAGE='AllTypes') + env.Compare(["optionals.output", "optionals.output.recoded"]) + + diff --git a/libs/nanopb/tests/alltypes_proto3/alltypes.options b/libs/nanopb/tests/alltypes_proto3/alltypes.options new file mode 100644 index 00000000..78dd08d1 --- /dev/null +++ b/libs/nanopb/tests/alltypes_proto3/alltypes.options @@ -0,0 +1,4 @@ +* max_size:16 +* max_count:5 +*.*fbytes fixed_length:true max_size:4 + diff --git a/libs/nanopb/tests/alltypes_proto3/alltypes.proto b/libs/nanopb/tests/alltypes_proto3/alltypes.proto new file mode 100644 index 00000000..f66109ec --- /dev/null +++ b/libs/nanopb/tests/alltypes_proto3/alltypes.proto @@ -0,0 +1,100 @@ +syntax = "proto3"; +// package name placeholder + +message SubMessage { + string substuff1 = 1; + int32 substuff2 = 2; + fixed32 substuff3 = 3; +} + +message EmptyMessage { + +} + +enum HugeEnum { + HE_Zero = 0; + Negative = -2147483647; /* protoc doesn't accept -2147483648 here */ + Positive = 2147483647; +} + +message Limits { + int32 int32_min = 1; + int32 int32_max = 2; + uint32 uint32_min = 3; + uint32 uint32_max = 4; + int64 int64_min = 5; + int64 int64_max = 6; + uint64 uint64_min = 7; + uint64 uint64_max = 8; + HugeEnum enum_min = 9; + HugeEnum enum_max = 10; +} + +enum MyEnum { + Zero = 0; + First = 1; + Second = 2; + Truth = 42; +} + +message AllTypes { + int32 sng_int32 = 1; + int64 sng_int64 = 2; + uint32 sng_uint32 = 3; + uint64 sng_uint64 = 4; + sint32 sng_sint32 = 5; + sint64 sng_sint64 = 6; + bool sng_bool = 7; + + fixed32 sng_fixed32 = 8; + sfixed32 sng_sfixed32= 9; + float sng_float = 10; + + fixed64 sng_fixed64 = 11; + sfixed64 sng_sfixed64= 12; + double sng_double = 13; + + string sng_string = 14; + bytes sng_bytes = 15; + SubMessage sng_submsg = 16; + MyEnum sng_enum = 17; + EmptyMessage sng_emptymsg = 18; + bytes sng_fbytes = 19; + + repeated int32 rep_int32 = 21 [packed = true]; + repeated int64 rep_int64 = 22 [packed = true]; + repeated uint32 rep_uint32 = 23 [packed = true]; + repeated uint64 rep_uint64 = 24 [packed = true]; + repeated sint32 rep_sint32 = 25 [packed = true]; + repeated sint64 rep_sint64 = 26 [packed = true]; + repeated bool rep_bool = 27 [packed = true]; + + repeated fixed32 rep_fixed32 = 28 [packed = true]; + repeated sfixed32 rep_sfixed32= 29 [packed = true]; + repeated float rep_float = 30 [packed = true]; + + repeated fixed64 rep_fixed64 = 31 [packed = true]; + repeated sfixed64 rep_sfixed64= 32 [packed = true]; + repeated double rep_double = 33 [packed = true]; + + repeated string rep_string = 34; + repeated bytes rep_bytes = 35; + repeated SubMessage rep_submsg = 36; + repeated MyEnum rep_enum = 37 [packed = true]; + repeated EmptyMessage rep_emptymsg = 38; + repeated bytes rep_fbytes = 39; + + oneof oneof + { + SubMessage oneof_msg1 = 59; + EmptyMessage oneof_msg2 = 60; + } + + // Check that extreme integer values are handled correctly + Limits req_limits = 98; + + // Just to make sure that the size of the fields has been calculated + // properly, i.e. otherwise a bug in last field might not be detected. + int32 end = 99; +} + diff --git a/libs/nanopb/tests/alltypes_proto3/decode_alltypes.c b/libs/nanopb/tests/alltypes_proto3/decode_alltypes.c new file mode 100644 index 00000000..51c1c41e --- /dev/null +++ b/libs/nanopb/tests/alltypes_proto3/decode_alltypes.c @@ -0,0 +1,167 @@ +/* Tests the decoding of all types. + * This is the counterpart of test_encode3. + * Run e.g. ./test_encode3 | ./test_decode3 + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +#define TEST(x) if (!(x)) { \ + printf("Test " #x " failed.\n"); \ + return false; \ + } + +/* This function is called once from main(), it handles + the decoding and checks the fields. */ +bool check_alltypes(pb_istream_t *stream, int mode) +{ + AllTypes alltypes = AllTypes_init_zero; + + /* Fill with garbage to better detect initialization errors */ + memset(&alltypes, 0xAA, sizeof(alltypes)); + + if (!pb_decode(stream, AllTypes_fields, &alltypes)) + return false; + + TEST(alltypes.rep_int32_count == 5 && alltypes.rep_int32[4] == -2001 && alltypes.rep_int32[0] == 0); + TEST(alltypes.rep_int64_count == 5 && alltypes.rep_int64[4] == -2002 && alltypes.rep_int64[0] == 0); + TEST(alltypes.rep_uint32_count == 5 && alltypes.rep_uint32[4] == 2003 && alltypes.rep_uint32[0] == 0); + TEST(alltypes.rep_uint64_count == 5 && alltypes.rep_uint64[4] == 2004 && alltypes.rep_uint64[0] == 0); + TEST(alltypes.rep_sint32_count == 5 && alltypes.rep_sint32[4] == -2005 && alltypes.rep_sint32[0] == 0); + TEST(alltypes.rep_sint64_count == 5 && alltypes.rep_sint64[4] == -2006 && alltypes.rep_sint64[0] == 0); + TEST(alltypes.rep_bool_count == 5 && alltypes.rep_bool[4] == true && alltypes.rep_bool[0] == false); + + TEST(alltypes.rep_fixed32_count == 5 && alltypes.rep_fixed32[4] == 2008 && alltypes.rep_fixed32[0] == 0); + TEST(alltypes.rep_sfixed32_count == 5 && alltypes.rep_sfixed32[4] == -2009 && alltypes.rep_sfixed32[0] == 0); + TEST(alltypes.rep_float_count == 5 && alltypes.rep_float[4] == 2010.0f && alltypes.rep_float[0] == 0.0f); + + TEST(alltypes.rep_fixed64_count == 5 && alltypes.rep_fixed64[4] == 2011 && alltypes.rep_fixed64[0] == 0); + TEST(alltypes.rep_sfixed64_count == 5 && alltypes.rep_sfixed64[4] == -2012 && alltypes.rep_sfixed64[0] == 0); + TEST(alltypes.rep_double_count == 5 && alltypes.rep_double[4] == 2013.0 && alltypes.rep_double[0] == 0.0); + + TEST(alltypes.rep_string_count == 5 && strcmp(alltypes.rep_string[4], "2014") == 0 && alltypes.rep_string[0][0] == '\0'); + TEST(alltypes.rep_bytes_count == 5 && alltypes.rep_bytes[4].size == 4 && alltypes.rep_bytes[0].size == 0); + TEST(memcmp(alltypes.rep_bytes[4].bytes, "2015", 4) == 0); + + TEST(alltypes.rep_submsg_count == 5); + TEST(strcmp(alltypes.rep_submsg[4].substuff1, "2016") == 0 && alltypes.rep_submsg[0].substuff1[0] == '\0'); + TEST(alltypes.rep_submsg[4].substuff2 == 2016 && alltypes.rep_submsg[0].substuff2 == 0); + TEST(alltypes.rep_submsg[4].substuff3 == 2016 && alltypes.rep_submsg[0].substuff3 == 0); + + TEST(alltypes.rep_enum_count == 5 && alltypes.rep_enum[4] == MyEnum_Truth && alltypes.rep_enum[0] == MyEnum_Zero); + TEST(alltypes.rep_emptymsg_count == 5); + + TEST(alltypes.rep_fbytes_count == 5); + TEST(alltypes.rep_fbytes[0][0] == 0 && alltypes.rep_fbytes[0][3] == 0); + TEST(memcmp(alltypes.rep_fbytes[4], "2019", 4) == 0); + + if (mode == 0) + { + /* Expect default values */ + TEST(alltypes.sng_int32 == 0); + TEST(alltypes.sng_int64 == 0); + TEST(alltypes.sng_uint32 == 0); + TEST(alltypes.sng_uint64 == 0); + TEST(alltypes.sng_sint32 == 0); + TEST(alltypes.sng_sint64 == 0); + TEST(alltypes.sng_bool == false); + + TEST(alltypes.sng_fixed32 == 0); + TEST(alltypes.sng_sfixed32 == 0); + TEST(alltypes.sng_float == 0.0f); + + TEST(alltypes.sng_fixed64 == 0); + TEST(alltypes.sng_sfixed64 == 0); + TEST(alltypes.sng_double == 0.0); + + TEST(strcmp(alltypes.sng_string, "") == 0); + TEST(alltypes.sng_bytes.size == 0); + TEST(strcmp(alltypes.sng_submsg.substuff1, "") == 0); + TEST(alltypes.sng_submsg.substuff2 == 0); + TEST(alltypes.sng_submsg.substuff3 == 0); + TEST(alltypes.sng_enum == MyEnum_Zero); + TEST(alltypes.sng_fbytes[0] == 0 && + alltypes.sng_fbytes[1] == 0 && + alltypes.sng_fbytes[2] == 0 && + alltypes.sng_fbytes[3] == 0); + + TEST(alltypes.which_oneof == 0); + } + else + { + /* Expect filled-in values */ + TEST(alltypes.sng_int32 == 3041); + TEST(alltypes.sng_int64 == 3042); + TEST(alltypes.sng_uint32 == 3043); + TEST(alltypes.sng_uint64 == 3044); + TEST(alltypes.sng_sint32 == 3045); + TEST(alltypes.sng_sint64 == 3046); + TEST(alltypes.sng_bool == true); + + TEST(alltypes.sng_fixed32 == 3048); + TEST(alltypes.sng_sfixed32 == 3049); + TEST(alltypes.sng_float == 3050.0f); + + TEST(alltypes.sng_fixed64 == 3051); + TEST(alltypes.sng_sfixed64 == 3052); + TEST(alltypes.sng_double == 3053.0); + + TEST(strcmp(alltypes.sng_string, "3054") == 0); + TEST(alltypes.sng_bytes.size == 4); + TEST(memcmp(alltypes.sng_bytes.bytes, "3055", 4) == 0); + TEST(strcmp(alltypes.sng_submsg.substuff1, "3056") == 0); + TEST(alltypes.sng_submsg.substuff2 == 3056); + TEST(alltypes.sng_submsg.substuff3 == 0); + TEST(alltypes.sng_enum == MyEnum_Truth); + TEST(memcmp(alltypes.sng_fbytes, "3059", 4) == 0); + + TEST(alltypes.which_oneof == AllTypes_oneof_msg1_tag); + TEST(strcmp(alltypes.oneof.oneof_msg1.substuff1, "4059") == 0); + TEST(alltypes.oneof.oneof_msg1.substuff2 == 4059); + } + + TEST(alltypes.req_limits.int32_min == INT32_MIN); + TEST(alltypes.req_limits.int32_max == INT32_MAX); + TEST(alltypes.req_limits.uint32_min == 0); + TEST(alltypes.req_limits.uint32_max == UINT32_MAX); + TEST(alltypes.req_limits.int64_min == INT64_MIN); + TEST(alltypes.req_limits.int64_max == INT64_MAX); + TEST(alltypes.req_limits.uint64_min == 0); + TEST(alltypes.req_limits.uint64_max == UINT64_MAX); + TEST(alltypes.req_limits.enum_min == HugeEnum_Negative); + TEST(alltypes.req_limits.enum_max == HugeEnum_Positive); + + TEST(alltypes.end == 1099); + + return true; +} + +int main(int argc, char **argv) +{ + uint8_t buffer[1024]; + size_t count; + pb_istream_t stream; + + /* Whether to expect the optional values or the default values. */ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Read the data into buffer */ + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + + /* Construct a pb_istream_t for reading from the buffer */ + stream = pb_istream_from_buffer(buffer, count); + + /* Decode and print out the stuff */ + if (!check_alltypes(&stream, mode)) + { + printf("Parsing failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } else { + return 0; + } +} diff --git a/libs/nanopb/tests/alltypes_proto3/encode_alltypes.c b/libs/nanopb/tests/alltypes_proto3/encode_alltypes.c new file mode 100644 index 00000000..1da06688 --- /dev/null +++ b/libs/nanopb/tests/alltypes_proto3/encode_alltypes.c @@ -0,0 +1,111 @@ +/* Attempts to test all the datatypes supported by ProtoBuf3. + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +int main(int argc, char **argv) +{ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Initialize the structure with constants */ + AllTypes alltypes = AllTypes_init_zero; + + alltypes.rep_int32_count = 5; alltypes.rep_int32[4] = -2001; + alltypes.rep_int64_count = 5; alltypes.rep_int64[4] = -2002; + alltypes.rep_uint32_count = 5; alltypes.rep_uint32[4] = 2003; + alltypes.rep_uint64_count = 5; alltypes.rep_uint64[4] = 2004; + alltypes.rep_sint32_count = 5; alltypes.rep_sint32[4] = -2005; + alltypes.rep_sint64_count = 5; alltypes.rep_sint64[4] = -2006; + alltypes.rep_bool_count = 5; alltypes.rep_bool[4] = true; + + alltypes.rep_fixed32_count = 5; alltypes.rep_fixed32[4] = 2008; + alltypes.rep_sfixed32_count = 5; alltypes.rep_sfixed32[4] = -2009; + alltypes.rep_float_count = 5; alltypes.rep_float[4] = 2010.0f; + + alltypes.rep_fixed64_count = 5; alltypes.rep_fixed64[4] = 2011; + alltypes.rep_sfixed64_count = 5; alltypes.rep_sfixed64[4] = -2012; + alltypes.rep_double_count = 5; alltypes.rep_double[4] = 2013.0; + + alltypes.rep_string_count = 5; strcpy(alltypes.rep_string[4], "2014"); + alltypes.rep_bytes_count = 5; alltypes.rep_bytes[4].size = 4; + memcpy(alltypes.rep_bytes[4].bytes, "2015", 4); + + alltypes.rep_submsg_count = 5; + strcpy(alltypes.rep_submsg[4].substuff1, "2016"); + alltypes.rep_submsg[4].substuff2 = 2016; + alltypes.rep_submsg[4].substuff3 = 2016; + + alltypes.rep_enum_count = 5; alltypes.rep_enum[4] = MyEnum_Truth; + alltypes.rep_emptymsg_count = 5; + + alltypes.rep_fbytes_count = 5; + memcpy(alltypes.rep_fbytes[4], "2019", 4); + + alltypes.req_limits.int32_min = INT32_MIN; + alltypes.req_limits.int32_max = INT32_MAX; + alltypes.req_limits.uint32_min = 0; + alltypes.req_limits.uint32_max = UINT32_MAX; + alltypes.req_limits.int64_min = INT64_MIN; + alltypes.req_limits.int64_max = INT64_MAX; + alltypes.req_limits.uint64_min = 0; + alltypes.req_limits.uint64_max = UINT64_MAX; + alltypes.req_limits.enum_min = HugeEnum_Negative; + alltypes.req_limits.enum_max = HugeEnum_Positive; + + if (mode != 0) + { + /* Fill in values for singular fields */ + alltypes.sng_int32 = 3041; + alltypes.sng_int64 = 3042; + alltypes.sng_uint32 = 3043; + alltypes.sng_uint64 = 3044; + alltypes.sng_sint32 = 3045; + alltypes.sng_sint64 = 3046; + alltypes.sng_bool = true; + + alltypes.sng_fixed32 = 3048; + alltypes.sng_sfixed32 = 3049; + alltypes.sng_float = 3050.0f; + + alltypes.sng_fixed64 = 3051; + alltypes.sng_sfixed64 = 3052; + alltypes.sng_double = 3053.0; + + strcpy(alltypes.sng_string, "3054"); + alltypes.sng_bytes.size = 4; + memcpy(alltypes.sng_bytes.bytes, "3055", 4); + strcpy(alltypes.sng_submsg.substuff1, "3056"); + alltypes.sng_submsg.substuff2 = 3056; + alltypes.sng_enum = MyEnum_Truth; + memcpy(alltypes.sng_fbytes, "3059", 4); + + alltypes.which_oneof = AllTypes_oneof_msg1_tag; + strcpy(alltypes.oneof.oneof_msg1.substuff1, "4059"); + alltypes.oneof.oneof_msg1.substuff2 = 4059; + } + + alltypes.end = 1099; + + { + uint8_t buffer[AllTypes_size]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Now encode it and check if we succeeded. */ + if (pb_encode(&stream, AllTypes_fields, &alltypes)) + { + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; /* Success */ + } + else + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; /* Failure */ + } + } +} diff --git a/libs/nanopb/tests/alltypes_proto3_callback/SConscript b/libs/nanopb/tests/alltypes_proto3_callback/SConscript new file mode 100644 index 00000000..183a138a --- /dev/null +++ b/libs/nanopb/tests/alltypes_proto3_callback/SConscript @@ -0,0 +1,23 @@ +# Test the AllTypes encoding & decoding using callbacks for all fields. + +Import("env", "malloc_env") + +c = Copy("$TARGET", "$SOURCE") +env.Command("alltypes.proto", "#alltypes_proto3/alltypes.proto", c) + +env.NanopbProto(["alltypes", "alltypes.options"]) +enc = env.Program(["encode_alltypes_callback.c", "alltypes.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) +dec = env.Program(["decode_alltypes_callback.c", "alltypes.pb.c", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) + +refdec = "$BUILD/alltypes_proto3/decode_alltypes$PROGSUFFIX" + +# Encode and compare results +env.RunTest(enc) +env.RunTest("decode_alltypes.output", [refdec, "encode_alltypes_callback.output"]) +env.RunTest("decode_alltypes_callback.output", [dec, "encode_alltypes_callback.output"]) + +# Do the same thing with the optional fields present +env.RunTest("optionals.output", enc, ARGS = ['1']) +env.RunTest("optionals.refdecout", [refdec, "optionals.output"], ARGS = ['1']) +env.RunTest("optionals.decout", [dec, "optionals.output"], ARGS = ['1']) + diff --git a/libs/nanopb/tests/alltypes_proto3_callback/alltypes.options b/libs/nanopb/tests/alltypes_proto3_callback/alltypes.options new file mode 100644 index 00000000..74d7a9c0 --- /dev/null +++ b/libs/nanopb/tests/alltypes_proto3_callback/alltypes.options @@ -0,0 +1,8 @@ +# Generate all fields as callbacks. +AllTypes.* type:FT_CALLBACK +SubMessage.substuff1 max_size:16 +AllTypes.oneof no_unions:true + +# With FT_CALLBACK, these options should get ignored +*.*fbytes fixed_length:true max_size:4 + diff --git a/libs/nanopb/tests/alltypes_proto3_callback/decode_alltypes_callback.c b/libs/nanopb/tests/alltypes_proto3_callback/decode_alltypes_callback.c new file mode 100644 index 00000000..2b3c2f32 --- /dev/null +++ b/libs/nanopb/tests/alltypes_proto3_callback/decode_alltypes_callback.c @@ -0,0 +1,376 @@ +/* Attempts to test all the datatypes supported by ProtoBuf when used as callback fields. + * Note that normally there would be no reason to use callback fields for this, + * because each encoder defined here only gives a single field. + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +#define TEST(x) if (!(x)) { \ + printf("Test " #x " failed (in field %d).\n", field->tag); \ + return false; \ + } + +static bool read_varint(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint64_t value; + if (!pb_decode_varint(stream, &value)) + return false; + + TEST((int64_t)value == (long)*arg); + return true; +} + +static bool read_svarint(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + int64_t value; + if (!pb_decode_svarint(stream, &value)) + return false; + + TEST(value == (long)*arg); + return true; +} + +static bool read_fixed32(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint32_t value; + if (!pb_decode_fixed32(stream, &value)) + return false; + + TEST(value == *(uint32_t*)*arg); + return true; +} + +static bool read_fixed64(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint64_t value; + if (!pb_decode_fixed64(stream, &value)) + return false; + + TEST(value == *(uint64_t*)*arg); + return true; +} + +static bool read_string(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint8_t buf[16] = {0}; + size_t len = stream->bytes_left; + + if (len > sizeof(buf) - 1 || !pb_read(stream, buf, len)) + return false; + + TEST(strcmp((char*)buf, *arg) == 0); + return true; +} + +static bool read_submsg(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + SubMessage submsg = {""}; + SubMessage *ref = *arg; + + if (!pb_decode(stream, SubMessage_fields, &submsg)) + return false; + + TEST(strcmp(submsg.substuff1, ref->substuff1) == 0); + TEST(submsg.substuff2 == ref->substuff2); + TEST(submsg.substuff3 == ref->substuff3); + return true; +} + +static bool read_emptymsg(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + EmptyMessage emptymsg = {0}; + return pb_decode(stream, EmptyMessage_fields, &emptymsg); +} + +static bool read_repeated_varint(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + int32_t** expected = (int32_t**)arg; + uint64_t value; + if (!pb_decode_varint(stream, &value)) + return false; + + TEST(*(*expected)++ == value); + return true; +} + +static bool read_repeated_svarint(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + int32_t** expected = (int32_t**)arg; + int64_t value; + if (!pb_decode_svarint(stream, &value)) + return false; + + TEST(*(*expected)++ == value); + return true; +} + +static bool read_repeated_fixed32(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint32_t** expected = (uint32_t**)arg; + uint32_t value; + if (!pb_decode_fixed32(stream, &value)) + return false; + + TEST(*(*expected)++ == value); + return true; +} + +static bool read_repeated_fixed64(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint64_t** expected = (uint64_t**)arg; + uint64_t value; + if (!pb_decode_fixed64(stream, &value)) + return false; + + TEST(*(*expected)++ == value); + return true; +} + +static bool read_repeated_string(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint8_t*** expected = (uint8_t***)arg; + uint8_t buf[16] = {0}; + size_t len = stream->bytes_left; + + if (len > sizeof(buf) - 1 || !pb_read(stream, buf, len)) + return false; + + TEST(strcmp((char*)*(*expected)++, (char*)buf) == 0); + return true; +} + +static bool read_repeated_submsg(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + SubMessage** expected = (SubMessage**)arg; + SubMessage submsg = {""}; + if (!pb_decode(stream, SubMessage_fields, &submsg)) + return false; + + TEST(strcmp(submsg.substuff1, (*expected)->substuff1) == 0); + TEST(submsg.substuff2 == (*expected)->substuff2); + TEST(submsg.substuff3 == (*expected)->substuff3); + (*expected)++; + + return true; +} + +static bool read_limits(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + Limits decoded = {0}; + if (!pb_decode(stream, Limits_fields, &decoded)) + return false; + + TEST(decoded.int32_min == INT32_MIN); + TEST(decoded.int32_max == INT32_MAX); + TEST(decoded.uint32_min == 0); + TEST(decoded.uint32_max == UINT32_MAX); + TEST(decoded.int64_min == INT64_MIN); + TEST(decoded.int64_max == INT64_MAX); + TEST(decoded.uint64_min == 0); + TEST(decoded.uint64_max == UINT64_MAX); + TEST(decoded.enum_min == HugeEnum_Negative); + TEST(decoded.enum_max == HugeEnum_Positive); + + return true; +} + +/* This function is called once from main(), it handles + the decoding and checks the fields. */ +bool check_alltypes(pb_istream_t *stream, int mode) +{ + /* Values for use from callbacks through pointers. */ + bool status; + + int32_t rep_int32[5] = {0, 0, 0, 0, -2001}; + int32_t rep_int64[5] = {0, 0, 0, 0, -2002}; + int32_t rep_uint32[5] = {0, 0, 0, 0, 2003}; + int32_t rep_uint64[5] = {0, 0, 0, 0, 2004}; + int32_t rep_sint32[5] = {0, 0, 0, 0, -2005}; + int32_t rep_sint64[5] = {0, 0, 0, 0, -2006}; + int32_t rep_bool[5] = {false, false, false, false, true}; + uint32_t rep_fixed32[5] = {0, 0, 0, 0, 2008}; + int32_t rep_sfixed32[5] = {0, 0, 0, 0, -2009}; + float rep_float[5] = {0, 0, 0, 0, 2010.0f}; + uint64_t rep_fixed64[5] = {0, 0, 0, 0, 2011}; + int64_t rep_sfixed64[5] = {0, 0, 0, 0, -2012}; + double rep_double[5] = {0, 0, 0, 0, 2013.0}; + char* rep_string[5] = {"", "", "", "", "2014"}; + char* rep_bytes[5] = {"", "", "", "", "2015"}; + SubMessage rep_submsg[5] = {{"", 0, 0}, + {"", 0, 0}, + {"", 0, 0}, + {"", 0, 0}, + {"2016", 2016, 2016}}; + int32_t rep_enum[5] = {0, 0, 0, 0, MyEnum_Truth}; + + uint32_t sng_fixed32 = 3048; + int32_t sng_sfixed32 = 3049; + float sng_float = 3050.0f; + uint64_t sng_fixed64 = 3051; + int64_t sng_sfixed64 = 3052; + double sng_double = 3053.0f; + SubMessage sng_submsg = {"3056", 3056}; + + SubMessage oneof_msg1 = {"4059", 4059}; + + AllTypes alltypes = AllTypes_init_zero; + + /* Bind callbacks for repeated fields */ + alltypes.rep_int32.funcs.decode = &read_repeated_varint; + alltypes.rep_int32.arg = rep_int32; + + alltypes.rep_int64.funcs.decode = &read_repeated_varint; + alltypes.rep_int64.arg = rep_int64; + + alltypes.rep_uint32.funcs.decode = &read_repeated_varint; + alltypes.rep_uint32.arg = rep_uint32; + + alltypes.rep_uint64.funcs.decode = &read_repeated_varint; + alltypes.rep_uint64.arg = rep_uint64; + + alltypes.rep_sint32.funcs.decode = &read_repeated_svarint; + alltypes.rep_sint32.arg = rep_sint32; + + alltypes.rep_sint64.funcs.decode = &read_repeated_svarint; + alltypes.rep_sint64.arg = rep_sint64; + + alltypes.rep_bool.funcs.decode = &read_repeated_varint; + alltypes.rep_bool.arg = rep_bool; + + alltypes.rep_fixed32.funcs.decode = &read_repeated_fixed32; + alltypes.rep_fixed32.arg = rep_fixed32; + + alltypes.rep_sfixed32.funcs.decode = &read_repeated_fixed32; + alltypes.rep_sfixed32.arg = rep_sfixed32; + + alltypes.rep_float.funcs.decode = &read_repeated_fixed32; + alltypes.rep_float.arg = rep_float; + + alltypes.rep_fixed64.funcs.decode = &read_repeated_fixed64; + alltypes.rep_fixed64.arg = rep_fixed64; + + alltypes.rep_sfixed64.funcs.decode = &read_repeated_fixed64; + alltypes.rep_sfixed64.arg = rep_sfixed64; + + alltypes.rep_double.funcs.decode = &read_repeated_fixed64; + alltypes.rep_double.arg = rep_double; + + alltypes.rep_string.funcs.decode = &read_repeated_string; + alltypes.rep_string.arg = rep_string; + + alltypes.rep_bytes.funcs.decode = &read_repeated_string; + alltypes.rep_bytes.arg = rep_bytes; + + alltypes.rep_submsg.funcs.decode = &read_repeated_submsg; + alltypes.rep_submsg.arg = rep_submsg; + + alltypes.rep_enum.funcs.decode = &read_repeated_varint; + alltypes.rep_enum.arg = rep_enum; + + alltypes.rep_emptymsg.funcs.decode = &read_emptymsg; + + alltypes.req_limits.funcs.decode = &read_limits; + + alltypes.end.funcs.decode = &read_varint; + alltypes.end.arg = (void*)1099; + + /* Bind callbacks for optional fields */ + if (mode == 1) + { + alltypes.sng_int32.funcs.decode = &read_varint; + alltypes.sng_int32.arg = (void*)3041; + + alltypes.sng_int64.funcs.decode = &read_varint; + alltypes.sng_int64.arg = (void*)3042; + + alltypes.sng_uint32.funcs.decode = &read_varint; + alltypes.sng_uint32.arg = (void*)3043; + + alltypes.sng_uint64.funcs.decode = &read_varint; + alltypes.sng_uint64.arg = (void*)3044; + + alltypes.sng_sint32.funcs.decode = &read_svarint; + alltypes.sng_sint32.arg = (void*)3045; + + alltypes.sng_sint64.funcs.decode = &read_svarint; + alltypes.sng_sint64.arg = (void*)3046; + + alltypes.sng_bool.funcs.decode = &read_varint; + alltypes.sng_bool.arg = (void*)true; + + alltypes.sng_fixed32.funcs.decode = &read_fixed32; + alltypes.sng_fixed32.arg = &sng_fixed32; + + alltypes.sng_sfixed32.funcs.decode = &read_fixed32; + alltypes.sng_sfixed32.arg = &sng_sfixed32; + + alltypes.sng_float.funcs.decode = &read_fixed32; + alltypes.sng_float.arg = &sng_float; + + alltypes.sng_fixed64.funcs.decode = &read_fixed64; + alltypes.sng_fixed64.arg = &sng_fixed64; + + alltypes.sng_sfixed64.funcs.decode = &read_fixed64; + alltypes.sng_sfixed64.arg = &sng_sfixed64; + + alltypes.sng_double.funcs.decode = &read_fixed64; + alltypes.sng_double.arg = &sng_double; + + alltypes.sng_string.funcs.decode = &read_string; + alltypes.sng_string.arg = "3054"; + + alltypes.sng_bytes.funcs.decode = &read_string; + alltypes.sng_bytes.arg = "3055"; + + alltypes.sng_submsg.funcs.decode = &read_submsg; + alltypes.sng_submsg.arg = &sng_submsg; + + alltypes.sng_enum.funcs.decode = &read_varint; + alltypes.sng_enum.arg = (void*)MyEnum_Truth; + + alltypes.sng_emptymsg.funcs.decode = &read_emptymsg; + + alltypes.oneof_msg1.funcs.decode = &read_submsg; + alltypes.oneof_msg1.arg = &oneof_msg1; + } + + status = pb_decode(stream, AllTypes_fields, &alltypes); + +#ifdef PB_ENABLE_MALLOC + /* Just to check for any interference between pb_release() and callback fields */ + pb_release(AllTypes_fields, &alltypes); +#endif + + return status; +} + +int main(int argc, char **argv) +{ + uint8_t buffer[1024]; + size_t count; + pb_istream_t stream; + + /* Whether to expect the optional values or the default values. */ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Read the data into buffer */ + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + + /* Construct a pb_istream_t for reading from the buffer */ + stream = pb_istream_from_buffer(buffer, count); + + /* Decode and print out the stuff */ + if (!check_alltypes(&stream, mode)) + { + printf("Parsing failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } else { + return 0; + } +} diff --git a/libs/nanopb/tests/alltypes_proto3_callback/encode_alltypes_callback.c b/libs/nanopb/tests/alltypes_proto3_callback/encode_alltypes_callback.c new file mode 100644 index 00000000..8c7bdd66 --- /dev/null +++ b/libs/nanopb/tests/alltypes_proto3_callback/encode_alltypes_callback.c @@ -0,0 +1,343 @@ +/* Attempts to test all the datatypes supported by ProtoBuf when used as callback fields. + * Note that normally there would be no reason to use callback fields for this, + * because each encoder defined here only gives a single field. + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +static bool write_varint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, (long)*arg); +} + +static bool write_svarint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, (long)*arg); +} + +static bool write_fixed32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_fixed32(stream, *arg); +} + +static bool write_fixed64(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_fixed64(stream, *arg); +} + +static bool write_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, *arg, strlen(*arg)); +} + +static bool write_submsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, *arg); +} + +static bool write_emptymsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + EmptyMessage emptymsg = {0}; + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg); +} + +static bool write_repeated_varint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_varint(stream, (long)*arg); +} + +static bool write_repeated_svarint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_svarint(stream, (long)*arg); +} + +static bool write_repeated_fixed32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + uint32_t dummy = 0; + + /* Make it a packed field */ + return pb_encode_tag(stream, PB_WT_STRING, field->tag) && + pb_encode_varint(stream, 5 * 4) && /* Number of bytes */ + pb_encode_fixed32(stream, &dummy) && + pb_encode_fixed32(stream, &dummy) && + pb_encode_fixed32(stream, &dummy) && + pb_encode_fixed32(stream, &dummy) && + pb_encode_fixed32(stream, *arg); +} + +static bool write_repeated_fixed64(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + uint64_t dummy = 0; + + /* Make it a packed field */ + return pb_encode_tag(stream, PB_WT_STRING, field->tag) && + pb_encode_varint(stream, 5 * 8) && /* Number of bytes */ + pb_encode_fixed64(stream, &dummy) && + pb_encode_fixed64(stream, &dummy) && + pb_encode_fixed64(stream, &dummy) && + pb_encode_fixed64(stream, &dummy) && + pb_encode_fixed64(stream, *arg); +} + +static bool write_repeated_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + return pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, 0, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, 0, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, 0, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, 0, 0) && + pb_encode_tag_for_field(stream, field) && + pb_encode_string(stream, *arg, strlen(*arg)); +} + +static bool write_repeated_submsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + SubMessage dummy = {""}; + + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, &dummy) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, &dummy) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, &dummy) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, &dummy) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, SubMessage_fields, *arg); +} + +static bool write_limits(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + Limits limits = {0}; + limits.int32_min = INT32_MIN; + limits.int32_max = INT32_MAX; + limits.uint32_min = 0; + limits.uint32_max = UINT32_MAX; + limits.int64_min = INT64_MIN; + limits.int64_max = INT64_MAX; + limits.uint64_min = 0; + limits.uint64_max = UINT64_MAX; + limits.enum_min = HugeEnum_Negative; + limits.enum_max = HugeEnum_Positive; + + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, Limits_fields, &limits); +} + +static bool write_repeated_emptymsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + EmptyMessage emptymsg = {0}; + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) && + pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg); +} + +int main(int argc, char **argv) +{ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Values for use from callbacks through pointers. */ + uint32_t rep_fixed32 = 2008; + int32_t rep_sfixed32 = -2009; + float rep_float = 2010.0f; + uint64_t rep_fixed64 = 2011; + int64_t rep_sfixed64 = -2012; + double rep_double = 2013.0; + SubMessage rep_submsg = {"2016", 2016, 2016}; + + uint32_t sng_fixed32 = 3048; + int32_t sng_sfixed32 = 3049; + float sng_float = 3050.0f; + uint64_t sng_fixed64 = 3051; + int64_t sng_sfixed64 = 3052; + double sng_double = 3053.0f; + SubMessage sng_submsg = {"3056", 3056}; + + SubMessage oneof_msg1 = {"4059", 4059}; + + AllTypes alltypes = AllTypes_init_zero; + + /* Bind callbacks for repeated fields */ + alltypes.rep_int32.funcs.encode = &write_repeated_varint; + alltypes.rep_int32.arg = (void*)-2001; + + alltypes.rep_int64.funcs.encode = &write_repeated_varint; + alltypes.rep_int64.arg = (void*)-2002; + + alltypes.rep_uint32.funcs.encode = &write_repeated_varint; + alltypes.rep_uint32.arg = (void*)2003; + + alltypes.rep_uint64.funcs.encode = &write_repeated_varint; + alltypes.rep_uint64.arg = (void*)2004; + + alltypes.rep_sint32.funcs.encode = &write_repeated_svarint; + alltypes.rep_sint32.arg = (void*)-2005; + + alltypes.rep_sint64.funcs.encode = &write_repeated_svarint; + alltypes.rep_sint64.arg = (void*)-2006; + + alltypes.rep_bool.funcs.encode = &write_repeated_varint; + alltypes.rep_bool.arg = (void*)true; + + alltypes.rep_fixed32.funcs.encode = &write_repeated_fixed32; + alltypes.rep_fixed32.arg = &rep_fixed32; + + alltypes.rep_sfixed32.funcs.encode = &write_repeated_fixed32; + alltypes.rep_sfixed32.arg = &rep_sfixed32; + + alltypes.rep_float.funcs.encode = &write_repeated_fixed32; + alltypes.rep_float.arg = &rep_float; + + alltypes.rep_fixed64.funcs.encode = &write_repeated_fixed64; + alltypes.rep_fixed64.arg = &rep_fixed64; + + alltypes.rep_sfixed64.funcs.encode = &write_repeated_fixed64; + alltypes.rep_sfixed64.arg = &rep_sfixed64; + + alltypes.rep_double.funcs.encode = &write_repeated_fixed64; + alltypes.rep_double.arg = &rep_double; + + alltypes.rep_string.funcs.encode = &write_repeated_string; + alltypes.rep_string.arg = "2014"; + + alltypes.rep_bytes.funcs.encode = &write_repeated_string; + alltypes.rep_bytes.arg = "2015"; + + alltypes.rep_submsg.funcs.encode = &write_repeated_submsg; + alltypes.rep_submsg.arg = &rep_submsg; + + alltypes.rep_enum.funcs.encode = &write_repeated_varint; + alltypes.rep_enum.arg = (void*)MyEnum_Truth; + + alltypes.rep_emptymsg.funcs.encode = &write_repeated_emptymsg; + + alltypes.rep_fbytes.funcs.encode = &write_repeated_string; + alltypes.rep_fbytes.arg = "2019"; + + alltypes.req_limits.funcs.encode = &write_limits; + + /* Bind callbacks for singular fields */ + if (mode != 0) + { + alltypes.sng_int32.funcs.encode = &write_varint; + alltypes.sng_int32.arg = (void*)3041; + + alltypes.sng_int64.funcs.encode = &write_varint; + alltypes.sng_int64.arg = (void*)3042; + + alltypes.sng_uint32.funcs.encode = &write_varint; + alltypes.sng_uint32.arg = (void*)3043; + + alltypes.sng_uint64.funcs.encode = &write_varint; + alltypes.sng_uint64.arg = (void*)3044; + + alltypes.sng_sint32.funcs.encode = &write_svarint; + alltypes.sng_sint32.arg = (void*)3045; + + alltypes.sng_sint64.funcs.encode = &write_svarint; + alltypes.sng_sint64.arg = (void*)3046; + + alltypes.sng_bool.funcs.encode = &write_varint; + alltypes.sng_bool.arg = (void*)true; + + alltypes.sng_fixed32.funcs.encode = &write_fixed32; + alltypes.sng_fixed32.arg = &sng_fixed32; + + alltypes.sng_sfixed32.funcs.encode = &write_fixed32; + alltypes.sng_sfixed32.arg = &sng_sfixed32; + + alltypes.sng_float.funcs.encode = &write_fixed32; + alltypes.sng_float.arg = &sng_float; + + alltypes.sng_fixed64.funcs.encode = &write_fixed64; + alltypes.sng_fixed64.arg = &sng_fixed64; + + alltypes.sng_sfixed64.funcs.encode = &write_fixed64; + alltypes.sng_sfixed64.arg = &sng_sfixed64; + + alltypes.sng_double.funcs.encode = &write_fixed64; + alltypes.sng_double.arg = &sng_double; + + alltypes.sng_string.funcs.encode = &write_string; + alltypes.sng_string.arg = "3054"; + + alltypes.sng_bytes.funcs.encode = &write_string; + alltypes.sng_bytes.arg = "3055"; + + alltypes.sng_submsg.funcs.encode = &write_submsg; + alltypes.sng_submsg.arg = &sng_submsg; + + alltypes.sng_enum.funcs.encode = &write_varint; + alltypes.sng_enum.arg = (void*)MyEnum_Truth; + + alltypes.sng_emptymsg.funcs.encode = &write_emptymsg; + + alltypes.sng_fbytes.funcs.encode = &write_string; + alltypes.sng_fbytes.arg = "3059"; + + alltypes.oneof_msg1.funcs.encode = &write_submsg; + alltypes.oneof_msg1.arg = &oneof_msg1; + } + + alltypes.end.funcs.encode = &write_varint; + alltypes.end.arg = (void*)1099; + + { + uint8_t buffer[2048]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Now encode it and check if we succeeded. */ + if (pb_encode(&stream, AllTypes_fields, &alltypes)) + { + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; /* Success */ + } + else + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; /* Failure */ + } + } +} diff --git a/libs/nanopb/tests/anonymous_oneof/SConscript b/libs/nanopb/tests/anonymous_oneof/SConscript new file mode 100644 index 00000000..10672287 --- /dev/null +++ b/libs/nanopb/tests/anonymous_oneof/SConscript @@ -0,0 +1,30 @@ +# Test anonymous_oneof generator option + +Import('env') + +import re + +match = None +if 'PROTOC_VERSION' in env: + match = re.search('([0-9]+).([0-9]+).([0-9]+)', env['PROTOC_VERSION']) + +if match: + version = map(int, match.groups()) + +# Oneof is supported by protoc >= 2.6.0 +if env.GetOption('clean') or (match and (version[0] > 2 or (version[0] == 2 and version[1] >= 6))): + # Anonymous oneofs are supported by clang and gcc + if 'clang' in env['CC'] or 'gcc' in env['CC']: + env2 = env.Clone() + if '-pedantic' in env2['CFLAGS']: + env2['CFLAGS'].remove('-pedantic') + env2.NanopbProto('oneof') + + dec = env2.Program(['decode_oneof.c', + 'oneof.pb.c', + '$COMMON/pb_decode.o', + '$COMMON/pb_common.o']) + + env2.RunTest("message1.txt", [dec, '$BUILD/oneof/message1.pb'], ARGS = ['1']) + env2.RunTest("message2.txt", [dec, '$BUILD/oneof/message2.pb'], ARGS = ['2']) + env2.RunTest("message3.txt", [dec, '$BUILD/oneof/message3.pb'], ARGS = ['3']) diff --git a/libs/nanopb/tests/anonymous_oneof/decode_oneof.c b/libs/nanopb/tests/anonymous_oneof/decode_oneof.c new file mode 100644 index 00000000..0f774dbc --- /dev/null +++ b/libs/nanopb/tests/anonymous_oneof/decode_oneof.c @@ -0,0 +1,88 @@ +/* Decode a message using oneof fields */ + +#include +#include +#include +#include +#include "oneof.pb.h" +#include "test_helpers.h" +#include "unittests.h" + +/* Test the 'AnonymousOneOfMessage' */ +int test_oneof_1(pb_istream_t *stream, int option) +{ + AnonymousOneOfMessage msg; + int status = 0; + + /* To better catch initialization errors */ + memset(&msg, 0xAA, sizeof(msg)); + + if (!pb_decode(stream, AnonymousOneOfMessage_fields, &msg)) + { + printf("Decoding failed: %s\n", PB_GET_ERROR(stream)); + return 1; + } + + /* Check that the basic fields work normally */ + TEST(msg.prefix == 123); + TEST(msg.suffix == 321); + + /* Check that we got the right oneof according to command line */ + if (option == 1) + { + TEST(msg.which_values == AnonymousOneOfMessage_first_tag); + TEST(msg.first == 999); + } + else if (option == 2) + { + TEST(msg.which_values == AnonymousOneOfMessage_second_tag); + TEST(strcmp(msg.second, "abcd") == 0); + } + else if (option == 3) + { + TEST(msg.which_values == AnonymousOneOfMessage_third_tag); + TEST(msg.third.array[0] == 1); + TEST(msg.third.array[1] == 2); + TEST(msg.third.array[2] == 3); + TEST(msg.third.array[3] == 4); + TEST(msg.third.array[4] == 5); + } + + return status; +} + +int main(int argc, char **argv) +{ + uint8_t buffer[AnonymousOneOfMessage_size]; + size_t count; + int option; + + if (argc != 2) + { + fprintf(stderr, "Usage: decode_oneof [number]\n"); + return 1; + } + option = atoi(argv[1]); + + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + + if (!feof(stdin)) + { + printf("Message does not fit in buffer\n"); + return 1; + } + + { + int status = 0; + pb_istream_t stream; + + stream = pb_istream_from_buffer(buffer, count); + status = test_oneof_1(&stream, option); + + if (status != 0) + return status; + } + + return 0; +} diff --git a/libs/nanopb/tests/anonymous_oneof/oneof.proto b/libs/nanopb/tests/anonymous_oneof/oneof.proto new file mode 100644 index 00000000..d56285c0 --- /dev/null +++ b/libs/nanopb/tests/anonymous_oneof/oneof.proto @@ -0,0 +1,23 @@ +syntax = "proto2"; + +import 'nanopb.proto'; + +message SubMessage +{ + repeated int32 array = 1 [(nanopb).max_count = 8]; +} + +/* Oneof in a message with other fields */ +message AnonymousOneOfMessage +{ + option (nanopb_msgopt).anonymous_oneof = true; + required int32 prefix = 1; + oneof values + { + int32 first = 5; + string second = 6 [(nanopb).max_size = 8]; + SubMessage third = 7; + } + required int32 suffix = 99; +} + diff --git a/libs/nanopb/tests/backwards_compatibility/SConscript b/libs/nanopb/tests/backwards_compatibility/SConscript new file mode 100644 index 00000000..81b03182 --- /dev/null +++ b/libs/nanopb/tests/backwards_compatibility/SConscript @@ -0,0 +1,11 @@ +# Check that the old generated .pb.c/.pb.h files are still compatible with the +# current version of nanopb. + +Import("env") + +enc = env.Program(["encode_legacy.c", "alltypes_legacy.c", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) +dec = env.Program(["decode_legacy.c", "alltypes_legacy.c", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) + +env.RunTest(enc) +env.RunTest([dec, "encode_legacy.output"]) + diff --git a/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.c b/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.c new file mode 100644 index 00000000..7311fd45 --- /dev/null +++ b/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.c @@ -0,0 +1,153 @@ +/* Automatically generated nanopb constant definitions */ +/* Generated by nanopb-0.3.0-dev at Tue Aug 19 17:53:24 2014. */ + +#include "alltypes_legacy.h" + +#if PB_PROTO_HEADER_VERSION != 30 +#error Regenerate this file with the current version of nanopb generator. +#endif + +const char SubMessage_substuff1_default[16] = "1"; +const int32_t SubMessage_substuff2_default = 2; +const uint32_t SubMessage_substuff3_default = 3u; +const int32_t Limits_int32_min_default = 2147483647; +const int32_t Limits_int32_max_default = -2147483647; +const uint32_t Limits_uint32_min_default = 4294967295u; +const uint32_t Limits_uint32_max_default = 0u; +const int64_t Limits_int64_min_default = 9223372036854775807ll; +const int64_t Limits_int64_max_default = -9223372036854775807ll; +const uint64_t Limits_uint64_min_default = 18446744073709551615ull; +const uint64_t Limits_uint64_max_default = 0ull; +const HugeEnum Limits_enum_min_default = HugeEnum_Positive; +const HugeEnum Limits_enum_max_default = HugeEnum_Negative; +const int32_t AllTypes_opt_int32_default = 4041; +const int64_t AllTypes_opt_int64_default = 4042ll; +const uint32_t AllTypes_opt_uint32_default = 4043u; +const uint64_t AllTypes_opt_uint64_default = 4044ull; +const int32_t AllTypes_opt_sint32_default = 4045; +const int64_t AllTypes_opt_sint64_default = 4046; +const bool AllTypes_opt_bool_default = false; +const uint32_t AllTypes_opt_fixed32_default = 4048u; +const int32_t AllTypes_opt_sfixed32_default = 4049; +const float AllTypes_opt_float_default = 4050; +const uint64_t AllTypes_opt_fixed64_default = 4051ull; +const int64_t AllTypes_opt_sfixed64_default = 4052ll; +const double AllTypes_opt_double_default = 4053; +const char AllTypes_opt_string_default[16] = "4054"; +const AllTypes_opt_bytes_t AllTypes_opt_bytes_default = {4, {0x34,0x30,0x35,0x35}}; +const MyEnum AllTypes_opt_enum_default = MyEnum_Second; + + +const pb_field_t SubMessage_fields[4] = { + PB_FIELD( 1, STRING , REQUIRED, STATIC , FIRST, SubMessage, substuff1, substuff1, &SubMessage_substuff1_default), + PB_FIELD( 2, INT32 , REQUIRED, STATIC , OTHER, SubMessage, substuff2, substuff1, &SubMessage_substuff2_default), + PB_FIELD( 3, FIXED32 , OPTIONAL, STATIC , OTHER, SubMessage, substuff3, substuff2, &SubMessage_substuff3_default), + PB_LAST_FIELD +}; + +const pb_field_t EmptyMessage_fields[1] = { + PB_LAST_FIELD +}; + +const pb_field_t Limits_fields[11] = { + PB_FIELD( 1, INT32 , REQUIRED, STATIC , FIRST, Limits, int32_min, int32_min, &Limits_int32_min_default), + PB_FIELD( 2, INT32 , REQUIRED, STATIC , OTHER, Limits, int32_max, int32_min, &Limits_int32_max_default), + PB_FIELD( 3, UINT32 , REQUIRED, STATIC , OTHER, Limits, uint32_min, int32_max, &Limits_uint32_min_default), + PB_FIELD( 4, UINT32 , REQUIRED, STATIC , OTHER, Limits, uint32_max, uint32_min, &Limits_uint32_max_default), + PB_FIELD( 5, INT64 , REQUIRED, STATIC , OTHER, Limits, int64_min, uint32_max, &Limits_int64_min_default), + PB_FIELD( 6, INT64 , REQUIRED, STATIC , OTHER, Limits, int64_max, int64_min, &Limits_int64_max_default), + PB_FIELD( 7, UINT64 , REQUIRED, STATIC , OTHER, Limits, uint64_min, int64_max, &Limits_uint64_min_default), + PB_FIELD( 8, UINT64 , REQUIRED, STATIC , OTHER, Limits, uint64_max, uint64_min, &Limits_uint64_max_default), + PB_FIELD( 9, ENUM , REQUIRED, STATIC , OTHER, Limits, enum_min, uint64_max, &Limits_enum_min_default), + PB_FIELD( 10, ENUM , REQUIRED, STATIC , OTHER, Limits, enum_max, enum_min, &Limits_enum_max_default), + PB_LAST_FIELD +}; + +const pb_field_t AllTypes_fields[54] = { + PB_FIELD( 1, INT32 , REQUIRED, STATIC , FIRST, AllTypes, req_int32, req_int32, 0), + PB_FIELD( 2, INT64 , REQUIRED, STATIC , OTHER, AllTypes, req_int64, req_int32, 0), + PB_FIELD( 3, UINT32 , REQUIRED, STATIC , OTHER, AllTypes, req_uint32, req_int64, 0), + PB_FIELD( 4, UINT64 , REQUIRED, STATIC , OTHER, AllTypes, req_uint64, req_uint32, 0), + PB_FIELD( 5, SINT32 , REQUIRED, STATIC , OTHER, AllTypes, req_sint32, req_uint64, 0), + PB_FIELD( 6, SINT64 , REQUIRED, STATIC , OTHER, AllTypes, req_sint64, req_sint32, 0), + PB_FIELD( 7, BOOL , REQUIRED, STATIC , OTHER, AllTypes, req_bool, req_sint64, 0), + PB_FIELD( 8, FIXED32 , REQUIRED, STATIC , OTHER, AllTypes, req_fixed32, req_bool, 0), + PB_FIELD( 9, SFIXED32, REQUIRED, STATIC , OTHER, AllTypes, req_sfixed32, req_fixed32, 0), + PB_FIELD( 10, FLOAT , REQUIRED, STATIC , OTHER, AllTypes, req_float, req_sfixed32, 0), + PB_FIELD( 11, FIXED64 , REQUIRED, STATIC , OTHER, AllTypes, req_fixed64, req_float, 0), + PB_FIELD( 12, SFIXED64, REQUIRED, STATIC , OTHER, AllTypes, req_sfixed64, req_fixed64, 0), + PB_FIELD( 13, DOUBLE , REQUIRED, STATIC , OTHER, AllTypes, req_double, req_sfixed64, 0), + PB_FIELD( 14, STRING , REQUIRED, STATIC , OTHER, AllTypes, req_string, req_double, 0), + PB_FIELD( 15, BYTES , REQUIRED, STATIC , OTHER, AllTypes, req_bytes, req_string, 0), + PB_FIELD( 16, MESSAGE , REQUIRED, STATIC , OTHER, AllTypes, req_submsg, req_bytes, &SubMessage_fields), + PB_FIELD( 17, ENUM , REQUIRED, STATIC , OTHER, AllTypes, req_enum, req_submsg, 0), + PB_FIELD( 21, INT32 , REPEATED, STATIC , OTHER, AllTypes, rep_int32, req_enum, 0), + PB_FIELD( 22, INT64 , REPEATED, STATIC , OTHER, AllTypes, rep_int64, rep_int32, 0), + PB_FIELD( 23, UINT32 , REPEATED, STATIC , OTHER, AllTypes, rep_uint32, rep_int64, 0), + PB_FIELD( 24, UINT64 , REPEATED, STATIC , OTHER, AllTypes, rep_uint64, rep_uint32, 0), + PB_FIELD( 25, SINT32 , REPEATED, STATIC , OTHER, AllTypes, rep_sint32, rep_uint64, 0), + PB_FIELD( 26, SINT64 , REPEATED, STATIC , OTHER, AllTypes, rep_sint64, rep_sint32, 0), + PB_FIELD( 27, BOOL , REPEATED, STATIC , OTHER, AllTypes, rep_bool, rep_sint64, 0), + PB_FIELD( 28, FIXED32 , REPEATED, STATIC , OTHER, AllTypes, rep_fixed32, rep_bool, 0), + PB_FIELD( 29, SFIXED32, REPEATED, STATIC , OTHER, AllTypes, rep_sfixed32, rep_fixed32, 0), + PB_FIELD( 30, FLOAT , REPEATED, STATIC , OTHER, AllTypes, rep_float, rep_sfixed32, 0), + PB_FIELD( 31, FIXED64 , REPEATED, STATIC , OTHER, AllTypes, rep_fixed64, rep_float, 0), + PB_FIELD( 32, SFIXED64, REPEATED, STATIC , OTHER, AllTypes, rep_sfixed64, rep_fixed64, 0), + PB_FIELD( 33, DOUBLE , REPEATED, STATIC , OTHER, AllTypes, rep_double, rep_sfixed64, 0), + PB_FIELD( 34, STRING , REPEATED, STATIC , OTHER, AllTypes, rep_string, rep_double, 0), + PB_FIELD( 35, BYTES , REPEATED, STATIC , OTHER, AllTypes, rep_bytes, rep_string, 0), + PB_FIELD( 36, MESSAGE , REPEATED, STATIC , OTHER, AllTypes, rep_submsg, rep_bytes, &SubMessage_fields), + PB_FIELD( 37, ENUM , REPEATED, STATIC , OTHER, AllTypes, rep_enum, rep_submsg, 0), + PB_FIELD( 41, INT32 , OPTIONAL, STATIC , OTHER, AllTypes, opt_int32, rep_enum, &AllTypes_opt_int32_default), + PB_FIELD( 42, INT64 , OPTIONAL, STATIC , OTHER, AllTypes, opt_int64, opt_int32, &AllTypes_opt_int64_default), + PB_FIELD( 43, UINT32 , OPTIONAL, STATIC , OTHER, AllTypes, opt_uint32, opt_int64, &AllTypes_opt_uint32_default), + PB_FIELD( 44, UINT64 , OPTIONAL, STATIC , OTHER, AllTypes, opt_uint64, opt_uint32, &AllTypes_opt_uint64_default), + PB_FIELD( 45, SINT32 , OPTIONAL, STATIC , OTHER, AllTypes, opt_sint32, opt_uint64, &AllTypes_opt_sint32_default), + PB_FIELD( 46, SINT64 , OPTIONAL, STATIC , OTHER, AllTypes, opt_sint64, opt_sint32, &AllTypes_opt_sint64_default), + PB_FIELD( 47, BOOL , OPTIONAL, STATIC , OTHER, AllTypes, opt_bool, opt_sint64, &AllTypes_opt_bool_default), + PB_FIELD( 48, FIXED32 , OPTIONAL, STATIC , OTHER, AllTypes, opt_fixed32, opt_bool, &AllTypes_opt_fixed32_default), + PB_FIELD( 49, SFIXED32, OPTIONAL, STATIC , OTHER, AllTypes, opt_sfixed32, opt_fixed32, &AllTypes_opt_sfixed32_default), + PB_FIELD( 50, FLOAT , OPTIONAL, STATIC , OTHER, AllTypes, opt_float, opt_sfixed32, &AllTypes_opt_float_default), + PB_FIELD( 51, FIXED64 , OPTIONAL, STATIC , OTHER, AllTypes, opt_fixed64, opt_float, &AllTypes_opt_fixed64_default), + PB_FIELD( 52, SFIXED64, OPTIONAL, STATIC , OTHER, AllTypes, opt_sfixed64, opt_fixed64, &AllTypes_opt_sfixed64_default), + PB_FIELD( 53, DOUBLE , OPTIONAL, STATIC , OTHER, AllTypes, opt_double, opt_sfixed64, &AllTypes_opt_double_default), + PB_FIELD( 54, STRING , OPTIONAL, STATIC , OTHER, AllTypes, opt_string, opt_double, &AllTypes_opt_string_default), + PB_FIELD( 55, BYTES , OPTIONAL, STATIC , OTHER, AllTypes, opt_bytes, opt_string, &AllTypes_opt_bytes_default), + PB_FIELD( 56, MESSAGE , OPTIONAL, STATIC , OTHER, AllTypes, opt_submsg, opt_bytes, &SubMessage_fields), + PB_FIELD( 57, ENUM , OPTIONAL, STATIC , OTHER, AllTypes, opt_enum, opt_submsg, &AllTypes_opt_enum_default), + PB_FIELD( 99, INT32 , REQUIRED, STATIC , OTHER, AllTypes, end, opt_enum, 0), + PB_FIELD(200, EXTENSION, OPTIONAL, CALLBACK, OTHER, AllTypes, extensions, end, 0), + PB_LAST_FIELD +}; + + +/* Check that field information fits in pb_field_t */ +#if !defined(PB_FIELD_32BIT) +/* If you get an error here, it means that you need to define PB_FIELD_32BIT + * compile-time option. You can do that in pb.h or on compiler command line. + * + * The reason you need to do this is that some of your messages contain tag + * numbers or field sizes that are larger than what can fit in 8 or 16 bit + * field descriptors. + */ +PB_STATIC_ASSERT((pb_membersize(AllTypes, req_submsg) < 65536 && pb_membersize(AllTypes, rep_submsg[0]) < 65536 && pb_membersize(AllTypes, opt_submsg) < 65536), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_SubMessage_EmptyMessage_Limits_AllTypes) +#endif + +#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT) +/* If you get an error here, it means that you need to define PB_FIELD_16BIT + * compile-time option. You can do that in pb.h or on compiler command line. + * + * The reason you need to do this is that some of your messages contain tag + * numbers or field sizes that are larger than what can fit in the default + * 8 bit descriptors. + */ +PB_STATIC_ASSERT((pb_membersize(AllTypes, req_submsg) < 256 && pb_membersize(AllTypes, rep_submsg[0]) < 256 && pb_membersize(AllTypes, opt_submsg) < 256), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_SubMessage_EmptyMessage_Limits_AllTypes) +#endif + + +/* On some platforms (such as AVR), double is really float. + * These are not directly supported by nanopb, but see example_avr_double. + * To get rid of this error, remove any double fields from your .proto. + */ +PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES) + diff --git a/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.h b/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.h new file mode 100644 index 00000000..4e0a63be --- /dev/null +++ b/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.h @@ -0,0 +1,274 @@ +/* Automatically generated nanopb header */ +/* Generated by nanopb-0.3.0-dev at Tue Aug 19 17:53:24 2014. */ + +#ifndef PB_ALLTYPES_LEGACY_H_INCLUDED +#define PB_ALLTYPES_LEGACY_H_INCLUDED +#include + +#if PB_PROTO_HEADER_VERSION != 30 +#error Regenerate this file with the current version of nanopb generator. +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Enum definitions */ +typedef enum _HugeEnum { + HugeEnum_Negative = -2147483647, + HugeEnum_Positive = 2147483647 +} HugeEnum; + +typedef enum _MyEnum { + MyEnum_Zero = 0, + MyEnum_First = 1, + MyEnum_Second = 2, + MyEnum_Truth = 42 +} MyEnum; + +/* Struct definitions */ +typedef struct _EmptyMessage { + uint8_t dummy_field; +} EmptyMessage; + +typedef struct _Limits { + int32_t int32_min; + int32_t int32_max; + uint32_t uint32_min; + uint32_t uint32_max; + int64_t int64_min; + int64_t int64_max; + uint64_t uint64_min; + uint64_t uint64_max; + HugeEnum enum_min; + HugeEnum enum_max; +} Limits; + +typedef struct _SubMessage { + char substuff1[16]; + int32_t substuff2; + bool has_substuff3; + uint32_t substuff3; +} SubMessage; + +typedef PB_BYTES_ARRAY_T(16) AllTypes_req_bytes_t; + +typedef PB_BYTES_ARRAY_T(16) AllTypes_rep_bytes_t; + +typedef PB_BYTES_ARRAY_T(16) AllTypes_opt_bytes_t; + +typedef struct _AllTypes { + int32_t req_int32; + int64_t req_int64; + uint32_t req_uint32; + uint64_t req_uint64; + int32_t req_sint32; + int64_t req_sint64; + bool req_bool; + uint32_t req_fixed32; + int32_t req_sfixed32; + float req_float; + uint64_t req_fixed64; + int64_t req_sfixed64; + double req_double; + char req_string[16]; + AllTypes_req_bytes_t req_bytes; + SubMessage req_submsg; + MyEnum req_enum; + pb_size_t rep_int32_count; + int32_t rep_int32[5]; + pb_size_t rep_int64_count; + int64_t rep_int64[5]; + pb_size_t rep_uint32_count; + uint32_t rep_uint32[5]; + pb_size_t rep_uint64_count; + uint64_t rep_uint64[5]; + pb_size_t rep_sint32_count; + int32_t rep_sint32[5]; + pb_size_t rep_sint64_count; + int64_t rep_sint64[5]; + pb_size_t rep_bool_count; + bool rep_bool[5]; + pb_size_t rep_fixed32_count; + uint32_t rep_fixed32[5]; + pb_size_t rep_sfixed32_count; + int32_t rep_sfixed32[5]; + pb_size_t rep_float_count; + float rep_float[5]; + pb_size_t rep_fixed64_count; + uint64_t rep_fixed64[5]; + pb_size_t rep_sfixed64_count; + int64_t rep_sfixed64[5]; + pb_size_t rep_double_count; + double rep_double[5]; + pb_size_t rep_string_count; + char rep_string[5][16]; + pb_size_t rep_bytes_count; + AllTypes_rep_bytes_t rep_bytes[5]; + pb_size_t rep_submsg_count; + SubMessage rep_submsg[5]; + pb_size_t rep_enum_count; + MyEnum rep_enum[5]; + bool has_opt_int32; + int32_t opt_int32; + bool has_opt_int64; + int64_t opt_int64; + bool has_opt_uint32; + uint32_t opt_uint32; + bool has_opt_uint64; + uint64_t opt_uint64; + bool has_opt_sint32; + int32_t opt_sint32; + bool has_opt_sint64; + int64_t opt_sint64; + bool has_opt_bool; + bool opt_bool; + bool has_opt_fixed32; + uint32_t opt_fixed32; + bool has_opt_sfixed32; + int32_t opt_sfixed32; + bool has_opt_float; + float opt_float; + bool has_opt_fixed64; + uint64_t opt_fixed64; + bool has_opt_sfixed64; + int64_t opt_sfixed64; + bool has_opt_double; + double opt_double; + bool has_opt_string; + char opt_string[16]; + bool has_opt_bytes; + AllTypes_opt_bytes_t opt_bytes; + bool has_opt_submsg; + SubMessage opt_submsg; + bool has_opt_enum; + MyEnum opt_enum; + int32_t end; + pb_extension_t *extensions; +} AllTypes; + +/* Default values for struct fields */ +extern const char SubMessage_substuff1_default[16]; +extern const int32_t SubMessage_substuff2_default; +extern const uint32_t SubMessage_substuff3_default; +extern const int32_t Limits_int32_min_default; +extern const int32_t Limits_int32_max_default; +extern const uint32_t Limits_uint32_min_default; +extern const uint32_t Limits_uint32_max_default; +extern const int64_t Limits_int64_min_default; +extern const int64_t Limits_int64_max_default; +extern const uint64_t Limits_uint64_min_default; +extern const uint64_t Limits_uint64_max_default; +extern const HugeEnum Limits_enum_min_default; +extern const HugeEnum Limits_enum_max_default; +extern const int32_t AllTypes_opt_int32_default; +extern const int64_t AllTypes_opt_int64_default; +extern const uint32_t AllTypes_opt_uint32_default; +extern const uint64_t AllTypes_opt_uint64_default; +extern const int32_t AllTypes_opt_sint32_default; +extern const int64_t AllTypes_opt_sint64_default; +extern const bool AllTypes_opt_bool_default; +extern const uint32_t AllTypes_opt_fixed32_default; +extern const int32_t AllTypes_opt_sfixed32_default; +extern const float AllTypes_opt_float_default; +extern const uint64_t AllTypes_opt_fixed64_default; +extern const int64_t AllTypes_opt_sfixed64_default; +extern const double AllTypes_opt_double_default; +extern const char AllTypes_opt_string_default[16]; +extern const AllTypes_opt_bytes_t AllTypes_opt_bytes_default; +extern const MyEnum AllTypes_opt_enum_default; + +/* Initializer values for message structs */ +#define SubMessage_init_default {"1", 2, false, 3u} +#define EmptyMessage_init_default {0} +#define Limits_init_default {2147483647, -2147483647, 4294967295u, 0u, 9223372036854775807ll, -9223372036854775807ll, 18446744073709551615ull, 0ull, HugeEnum_Positive, HugeEnum_Negative} +#define AllTypes_init_default {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "", {0, {0}}, SubMessage_init_default, (MyEnum)0, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {"", "", "", "", ""}, 0, {{0, {0}}, {0, {0}}, {0, {0}}, {0, {0}}, {0, {0}}}, 0, {SubMessage_init_default, SubMessage_init_default, SubMessage_init_default, SubMessage_init_default, SubMessage_init_default}, 0, {(MyEnum)0, (MyEnum)0, (MyEnum)0, (MyEnum)0, (MyEnum)0}, false, 4041, false, 4042ll, false, 4043u, false, 4044ull, false, 4045, false, 4046, false, false, false, 4048u, false, 4049, false, 4050, false, 4051ull, false, 4052ll, false, 4053, false, "4054", false, {4, {0x34,0x30,0x35,0x35}}, false, SubMessage_init_default, false, MyEnum_Second, 0, NULL} +#define SubMessage_init_zero {"", 0, false, 0} +#define EmptyMessage_init_zero {0} +#define Limits_init_zero {0, 0, 0, 0, 0, 0, 0, 0, (HugeEnum)0, (HugeEnum)0} +#define AllTypes_init_zero {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "", {0, {0}}, SubMessage_init_zero, (MyEnum)0, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {0, 0, 0, 0, 0}, 0, {"", "", "", "", ""}, 0, {{0, {0}}, {0, {0}}, {0, {0}}, {0, {0}}, {0, {0}}}, 0, {SubMessage_init_zero, SubMessage_init_zero, SubMessage_init_zero, SubMessage_init_zero, SubMessage_init_zero}, 0, {(MyEnum)0, (MyEnum)0, (MyEnum)0, (MyEnum)0, (MyEnum)0}, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, "", false, {0, {0}}, false, SubMessage_init_zero, false, (MyEnum)0, 0, NULL} + +/* Field tags (for use in manual encoding/decoding) */ +#define Limits_int32_min_tag 1 +#define Limits_int32_max_tag 2 +#define Limits_uint32_min_tag 3 +#define Limits_uint32_max_tag 4 +#define Limits_int64_min_tag 5 +#define Limits_int64_max_tag 6 +#define Limits_uint64_min_tag 7 +#define Limits_uint64_max_tag 8 +#define Limits_enum_min_tag 9 +#define Limits_enum_max_tag 10 +#define SubMessage_substuff1_tag 1 +#define SubMessage_substuff2_tag 2 +#define SubMessage_substuff3_tag 3 +#define AllTypes_req_int32_tag 1 +#define AllTypes_req_int64_tag 2 +#define AllTypes_req_uint32_tag 3 +#define AllTypes_req_uint64_tag 4 +#define AllTypes_req_sint32_tag 5 +#define AllTypes_req_sint64_tag 6 +#define AllTypes_req_bool_tag 7 +#define AllTypes_req_fixed32_tag 8 +#define AllTypes_req_sfixed32_tag 9 +#define AllTypes_req_float_tag 10 +#define AllTypes_req_fixed64_tag 11 +#define AllTypes_req_sfixed64_tag 12 +#define AllTypes_req_double_tag 13 +#define AllTypes_req_string_tag 14 +#define AllTypes_req_bytes_tag 15 +#define AllTypes_req_submsg_tag 16 +#define AllTypes_req_enum_tag 17 +#define AllTypes_rep_int32_tag 21 +#define AllTypes_rep_int64_tag 22 +#define AllTypes_rep_uint32_tag 23 +#define AllTypes_rep_uint64_tag 24 +#define AllTypes_rep_sint32_tag 25 +#define AllTypes_rep_sint64_tag 26 +#define AllTypes_rep_bool_tag 27 +#define AllTypes_rep_fixed32_tag 28 +#define AllTypes_rep_sfixed32_tag 29 +#define AllTypes_rep_float_tag 30 +#define AllTypes_rep_fixed64_tag 31 +#define AllTypes_rep_sfixed64_tag 32 +#define AllTypes_rep_double_tag 33 +#define AllTypes_rep_string_tag 34 +#define AllTypes_rep_bytes_tag 35 +#define AllTypes_rep_submsg_tag 36 +#define AllTypes_rep_enum_tag 37 +#define AllTypes_opt_int32_tag 41 +#define AllTypes_opt_int64_tag 42 +#define AllTypes_opt_uint32_tag 43 +#define AllTypes_opt_uint64_tag 44 +#define AllTypes_opt_sint32_tag 45 +#define AllTypes_opt_sint64_tag 46 +#define AllTypes_opt_bool_tag 47 +#define AllTypes_opt_fixed32_tag 48 +#define AllTypes_opt_sfixed32_tag 49 +#define AllTypes_opt_float_tag 50 +#define AllTypes_opt_fixed64_tag 51 +#define AllTypes_opt_sfixed64_tag 52 +#define AllTypes_opt_double_tag 53 +#define AllTypes_opt_string_tag 54 +#define AllTypes_opt_bytes_tag 55 +#define AllTypes_opt_submsg_tag 56 +#define AllTypes_opt_enum_tag 57 +#define AllTypes_end_tag 99 + +/* Struct field encoding specification for nanopb */ +extern const pb_field_t SubMessage_fields[4]; +extern const pb_field_t EmptyMessage_fields[1]; +extern const pb_field_t Limits_fields[11]; +extern const pb_field_t AllTypes_fields[54]; + +/* Maximum encoded size of messages (where known) */ +#define SubMessage_size 34 +#define EmptyMessage_size 0 +#define Limits_size 90 +#define AllTypes_size 1362 + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.options b/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.options new file mode 100644 index 00000000..b31e3cf0 --- /dev/null +++ b/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.options @@ -0,0 +1,3 @@ +* max_size:16 +* max_count:5 + diff --git a/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.proto b/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.proto new file mode 100644 index 00000000..f5bc35ce --- /dev/null +++ b/libs/nanopb/tests/backwards_compatibility/alltypes_legacy.proto @@ -0,0 +1,110 @@ +syntax = "proto2"; + +message SubMessage { + required string substuff1 = 1 [default = "1"]; + required int32 substuff2 = 2 [default = 2]; + optional fixed32 substuff3 = 3 [default = 3]; +} + +message EmptyMessage { + +} + +enum HugeEnum { + Negative = -2147483647; /* protoc doesn't accept -2147483648 here */ + Positive = 2147483647; +} + +message Limits { + required int32 int32_min = 1 [default = 2147483647]; + required int32 int32_max = 2 [default = -2147483647]; + required uint32 uint32_min = 3 [default = 4294967295]; + required uint32 uint32_max = 4 [default = 0]; + required int64 int64_min = 5 [default = 9223372036854775807]; + required int64 int64_max = 6 [default = -9223372036854775807]; + required uint64 uint64_min = 7 [default = 18446744073709551615]; + required uint64 uint64_max = 8 [default = 0]; + required HugeEnum enum_min = 9 [default = Positive]; + required HugeEnum enum_max = 10 [default = Negative]; +} + +enum MyEnum { + Zero = 0; + First = 1; + Second = 2; + Truth = 42; +} + +message AllTypes { + required int32 req_int32 = 1; + required int64 req_int64 = 2; + required uint32 req_uint32 = 3; + required uint64 req_uint64 = 4; + required sint32 req_sint32 = 5; + required sint64 req_sint64 = 6; + required bool req_bool = 7; + + required fixed32 req_fixed32 = 8; + required sfixed32 req_sfixed32= 9; + required float req_float = 10; + + required fixed64 req_fixed64 = 11; + required sfixed64 req_sfixed64= 12; + required double req_double = 13; + + required string req_string = 14; + required bytes req_bytes = 15; + required SubMessage req_submsg = 16; + required MyEnum req_enum = 17; + + + repeated int32 rep_int32 = 21 [packed = true]; + repeated int64 rep_int64 = 22 [packed = true]; + repeated uint32 rep_uint32 = 23 [packed = true]; + repeated uint64 rep_uint64 = 24 [packed = true]; + repeated sint32 rep_sint32 = 25 [packed = true]; + repeated sint64 rep_sint64 = 26 [packed = true]; + repeated bool rep_bool = 27 [packed = true]; + + repeated fixed32 rep_fixed32 = 28 [packed = true]; + repeated sfixed32 rep_sfixed32= 29 [packed = true]; + repeated float rep_float = 30 [packed = true]; + + repeated fixed64 rep_fixed64 = 31 [packed = true]; + repeated sfixed64 rep_sfixed64= 32 [packed = true]; + repeated double rep_double = 33 [packed = true]; + + repeated string rep_string = 34; + repeated bytes rep_bytes = 35; + repeated SubMessage rep_submsg = 36; + repeated MyEnum rep_enum = 37 [packed = true]; + + optional int32 opt_int32 = 41 [default = 4041]; + optional int64 opt_int64 = 42 [default = 4042]; + optional uint32 opt_uint32 = 43 [default = 4043]; + optional uint64 opt_uint64 = 44 [default = 4044]; + optional sint32 opt_sint32 = 45 [default = 4045]; + optional sint64 opt_sint64 = 46 [default = 4046]; + optional bool opt_bool = 47 [default = false]; + + optional fixed32 opt_fixed32 = 48 [default = 4048]; + optional sfixed32 opt_sfixed32= 49 [default = 4049]; + optional float opt_float = 50 [default = 4050]; + + optional fixed64 opt_fixed64 = 51 [default = 4051]; + optional sfixed64 opt_sfixed64= 52 [default = 4052]; + optional double opt_double = 53 [default = 4053]; + + optional string opt_string = 54 [default = "4054"]; + optional bytes opt_bytes = 55 [default = "4055"]; + optional SubMessage opt_submsg = 56; + optional MyEnum opt_enum = 57 [default = Second]; + + // Just to make sure that the size of the fields has been calculated + // properly, i.e. otherwise a bug in last field might not be detected. + required int32 end = 99; + + + extensions 200 to 255; +} + diff --git a/libs/nanopb/tests/backwards_compatibility/decode_legacy.c b/libs/nanopb/tests/backwards_compatibility/decode_legacy.c new file mode 100644 index 00000000..5f5b6bbe --- /dev/null +++ b/libs/nanopb/tests/backwards_compatibility/decode_legacy.c @@ -0,0 +1,199 @@ +/* Tests the decoding of all types. + * This is a backwards-compatibility test, using alltypes_legacy.h. + * It is similar to decode_alltypes, but duplicated in order to allow + * decode_alltypes to test any new features introduced later. + * + * Run e.g. ./encode_legacy | ./decode_legacy + */ + +#include +#include +#include +#include +#include "alltypes_legacy.h" +#include "test_helpers.h" + +#define TEST(x) if (!(x)) { \ + printf("Test " #x " failed.\n"); \ + return false; \ + } + +/* This function is called once from main(), it handles + the decoding and checks the fields. */ +bool check_alltypes(pb_istream_t *stream, int mode) +{ + AllTypes alltypes = {0}; + + if (!pb_decode(stream, AllTypes_fields, &alltypes)) + return false; + + TEST(alltypes.req_int32 == -1001); + TEST(alltypes.req_int64 == -1002); + TEST(alltypes.req_uint32 == 1003); + TEST(alltypes.req_uint64 == 1004); + TEST(alltypes.req_sint32 == -1005); + TEST(alltypes.req_sint64 == -1006); + TEST(alltypes.req_bool == true); + + TEST(alltypes.req_fixed32 == 1008); + TEST(alltypes.req_sfixed32 == -1009); + TEST(alltypes.req_float == 1010.0f); + + TEST(alltypes.req_fixed64 == 1011); + TEST(alltypes.req_sfixed64 == -1012); + TEST(alltypes.req_double == 1013.0f); + + TEST(strcmp(alltypes.req_string, "1014") == 0); + TEST(alltypes.req_bytes.size == 4); + TEST(memcmp(alltypes.req_bytes.bytes, "1015", 4) == 0); + TEST(strcmp(alltypes.req_submsg.substuff1, "1016") == 0); + TEST(alltypes.req_submsg.substuff2 == 1016); + TEST(alltypes.req_submsg.substuff3 == 3); + TEST(alltypes.req_enum == MyEnum_Truth); + + TEST(alltypes.rep_int32_count == 5 && alltypes.rep_int32[4] == -2001 && alltypes.rep_int32[0] == 0); + TEST(alltypes.rep_int64_count == 5 && alltypes.rep_int64[4] == -2002 && alltypes.rep_int64[0] == 0); + TEST(alltypes.rep_uint32_count == 5 && alltypes.rep_uint32[4] == 2003 && alltypes.rep_uint32[0] == 0); + TEST(alltypes.rep_uint64_count == 5 && alltypes.rep_uint64[4] == 2004 && alltypes.rep_uint64[0] == 0); + TEST(alltypes.rep_sint32_count == 5 && alltypes.rep_sint32[4] == -2005 && alltypes.rep_sint32[0] == 0); + TEST(alltypes.rep_sint64_count == 5 && alltypes.rep_sint64[4] == -2006 && alltypes.rep_sint64[0] == 0); + TEST(alltypes.rep_bool_count == 5 && alltypes.rep_bool[4] == true && alltypes.rep_bool[0] == false); + + TEST(alltypes.rep_fixed32_count == 5 && alltypes.rep_fixed32[4] == 2008 && alltypes.rep_fixed32[0] == 0); + TEST(alltypes.rep_sfixed32_count == 5 && alltypes.rep_sfixed32[4] == -2009 && alltypes.rep_sfixed32[0] == 0); + TEST(alltypes.rep_float_count == 5 && alltypes.rep_float[4] == 2010.0f && alltypes.rep_float[0] == 0.0f); + + TEST(alltypes.rep_fixed64_count == 5 && alltypes.rep_fixed64[4] == 2011 && alltypes.rep_fixed64[0] == 0); + TEST(alltypes.rep_sfixed64_count == 5 && alltypes.rep_sfixed64[4] == -2012 && alltypes.rep_sfixed64[0] == 0); + TEST(alltypes.rep_double_count == 5 && alltypes.rep_double[4] == 2013.0 && alltypes.rep_double[0] == 0.0); + + TEST(alltypes.rep_string_count == 5 && strcmp(alltypes.rep_string[4], "2014") == 0 && alltypes.rep_string[0][0] == '\0'); + TEST(alltypes.rep_bytes_count == 5 && alltypes.rep_bytes[4].size == 4 && alltypes.rep_bytes[0].size == 0); + TEST(memcmp(alltypes.rep_bytes[4].bytes, "2015", 4) == 0); + + TEST(alltypes.rep_submsg_count == 5); + TEST(strcmp(alltypes.rep_submsg[4].substuff1, "2016") == 0 && alltypes.rep_submsg[0].substuff1[0] == '\0'); + TEST(alltypes.rep_submsg[4].substuff2 == 2016 && alltypes.rep_submsg[0].substuff2 == 0); + TEST(alltypes.rep_submsg[4].substuff3 == 2016 && alltypes.rep_submsg[0].substuff3 == 3); + + TEST(alltypes.rep_enum_count == 5 && alltypes.rep_enum[4] == MyEnum_Truth && alltypes.rep_enum[0] == MyEnum_Zero); + + if (mode == 0) + { + /* Expect default values */ + TEST(alltypes.has_opt_int32 == false); + TEST(alltypes.opt_int32 == 4041); + TEST(alltypes.has_opt_int64 == false); + TEST(alltypes.opt_int64 == 4042); + TEST(alltypes.has_opt_uint32 == false); + TEST(alltypes.opt_uint32 == 4043); + TEST(alltypes.has_opt_uint64 == false); + TEST(alltypes.opt_uint64 == 4044); + TEST(alltypes.has_opt_sint32 == false); + TEST(alltypes.opt_sint32 == 4045); + TEST(alltypes.has_opt_sint64 == false); + TEST(alltypes.opt_sint64 == 4046); + TEST(alltypes.has_opt_bool == false); + TEST(alltypes.opt_bool == false); + + TEST(alltypes.has_opt_fixed32 == false); + TEST(alltypes.opt_fixed32 == 4048); + TEST(alltypes.has_opt_sfixed32 == false); + TEST(alltypes.opt_sfixed32 == 4049); + TEST(alltypes.has_opt_float == false); + TEST(alltypes.opt_float == 4050.0f); + + TEST(alltypes.has_opt_fixed64 == false); + TEST(alltypes.opt_fixed64 == 4051); + TEST(alltypes.has_opt_sfixed64 == false); + TEST(alltypes.opt_sfixed64 == 4052); + TEST(alltypes.has_opt_double == false); + TEST(alltypes.opt_double == 4053.0); + + TEST(alltypes.has_opt_string == false); + TEST(strcmp(alltypes.opt_string, "4054") == 0); + TEST(alltypes.has_opt_bytes == false); + TEST(alltypes.opt_bytes.size == 4); + TEST(memcmp(alltypes.opt_bytes.bytes, "4055", 4) == 0); + TEST(alltypes.has_opt_submsg == false); + TEST(strcmp(alltypes.opt_submsg.substuff1, "1") == 0); + TEST(alltypes.opt_submsg.substuff2 == 2); + TEST(alltypes.opt_submsg.substuff3 == 3); + TEST(alltypes.has_opt_enum == false); + TEST(alltypes.opt_enum == MyEnum_Second); + } + else + { + /* Expect filled-in values */ + TEST(alltypes.has_opt_int32 == true); + TEST(alltypes.opt_int32 == 3041); + TEST(alltypes.has_opt_int64 == true); + TEST(alltypes.opt_int64 == 3042); + TEST(alltypes.has_opt_uint32 == true); + TEST(alltypes.opt_uint32 == 3043); + TEST(alltypes.has_opt_uint64 == true); + TEST(alltypes.opt_uint64 == 3044); + TEST(alltypes.has_opt_sint32 == true); + TEST(alltypes.opt_sint32 == 3045); + TEST(alltypes.has_opt_sint64 == true); + TEST(alltypes.opt_sint64 == 3046); + TEST(alltypes.has_opt_bool == true); + TEST(alltypes.opt_bool == true); + + TEST(alltypes.has_opt_fixed32 == true); + TEST(alltypes.opt_fixed32 == 3048); + TEST(alltypes.has_opt_sfixed32 == true); + TEST(alltypes.opt_sfixed32 == 3049); + TEST(alltypes.has_opt_float == true); + TEST(alltypes.opt_float == 3050.0f); + + TEST(alltypes.has_opt_fixed64 == true); + TEST(alltypes.opt_fixed64 == 3051); + TEST(alltypes.has_opt_sfixed64 == true); + TEST(alltypes.opt_sfixed64 == 3052); + TEST(alltypes.has_opt_double == true); + TEST(alltypes.opt_double == 3053.0); + + TEST(alltypes.has_opt_string == true); + TEST(strcmp(alltypes.opt_string, "3054") == 0); + TEST(alltypes.has_opt_bytes == true); + TEST(alltypes.opt_bytes.size == 4); + TEST(memcmp(alltypes.opt_bytes.bytes, "3055", 4) == 0); + TEST(alltypes.has_opt_submsg == true); + TEST(strcmp(alltypes.opt_submsg.substuff1, "3056") == 0); + TEST(alltypes.opt_submsg.substuff2 == 3056); + TEST(alltypes.opt_submsg.substuff3 == 3); + TEST(alltypes.has_opt_enum == true); + TEST(alltypes.opt_enum == MyEnum_Truth); + } + + TEST(alltypes.end == 1099); + + return true; +} + +int main(int argc, char **argv) +{ + uint8_t buffer[1024]; + size_t count; + pb_istream_t stream; + + /* Whether to expect the optional values or the default values. */ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Read the data into buffer */ + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + + /* Construct a pb_istream_t for reading from the buffer */ + stream = pb_istream_from_buffer(buffer, count); + + /* Decode and print out the stuff */ + if (!check_alltypes(&stream, mode)) + { + printf("Parsing failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } else { + return 0; + } +} diff --git a/libs/nanopb/tests/backwards_compatibility/encode_legacy.c b/libs/nanopb/tests/backwards_compatibility/encode_legacy.c new file mode 100644 index 00000000..5c9d41b3 --- /dev/null +++ b/libs/nanopb/tests/backwards_compatibility/encode_legacy.c @@ -0,0 +1,135 @@ +/* Attempts to test all the datatypes supported by ProtoBuf. + * This is a backwards-compatibility test, using alltypes_legacy.h. + * It is similar to encode_alltypes, but duplicated in order to allow + * encode_alltypes to test any new features introduced later. + */ + +#include +#include +#include +#include +#include "alltypes_legacy.h" +#include "test_helpers.h" + +int main(int argc, char **argv) +{ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Initialize the structure with constants */ + AllTypes alltypes = {0}; + + alltypes.req_int32 = -1001; + alltypes.req_int64 = -1002; + alltypes.req_uint32 = 1003; + alltypes.req_uint64 = 1004; + alltypes.req_sint32 = -1005; + alltypes.req_sint64 = -1006; + alltypes.req_bool = true; + + alltypes.req_fixed32 = 1008; + alltypes.req_sfixed32 = -1009; + alltypes.req_float = 1010.0f; + + alltypes.req_fixed64 = 1011; + alltypes.req_sfixed64 = -1012; + alltypes.req_double = 1013.0; + + strcpy(alltypes.req_string, "1014"); + alltypes.req_bytes.size = 4; + memcpy(alltypes.req_bytes.bytes, "1015", 4); + strcpy(alltypes.req_submsg.substuff1, "1016"); + alltypes.req_submsg.substuff2 = 1016; + alltypes.req_enum = MyEnum_Truth; + + alltypes.rep_int32_count = 5; alltypes.rep_int32[4] = -2001; + alltypes.rep_int64_count = 5; alltypes.rep_int64[4] = -2002; + alltypes.rep_uint32_count = 5; alltypes.rep_uint32[4] = 2003; + alltypes.rep_uint64_count = 5; alltypes.rep_uint64[4] = 2004; + alltypes.rep_sint32_count = 5; alltypes.rep_sint32[4] = -2005; + alltypes.rep_sint64_count = 5; alltypes.rep_sint64[4] = -2006; + alltypes.rep_bool_count = 5; alltypes.rep_bool[4] = true; + + alltypes.rep_fixed32_count = 5; alltypes.rep_fixed32[4] = 2008; + alltypes.rep_sfixed32_count = 5; alltypes.rep_sfixed32[4] = -2009; + alltypes.rep_float_count = 5; alltypes.rep_float[4] = 2010.0f; + + alltypes.rep_fixed64_count = 5; alltypes.rep_fixed64[4] = 2011; + alltypes.rep_sfixed64_count = 5; alltypes.rep_sfixed64[4] = -2012; + alltypes.rep_double_count = 5; alltypes.rep_double[4] = 2013.0; + + alltypes.rep_string_count = 5; strcpy(alltypes.rep_string[4], "2014"); + alltypes.rep_bytes_count = 5; alltypes.rep_bytes[4].size = 4; + memcpy(alltypes.rep_bytes[4].bytes, "2015", 4); + + alltypes.rep_submsg_count = 5; + strcpy(alltypes.rep_submsg[4].substuff1, "2016"); + alltypes.rep_submsg[4].substuff2 = 2016; + alltypes.rep_submsg[4].has_substuff3 = true; + alltypes.rep_submsg[4].substuff3 = 2016; + + alltypes.rep_enum_count = 5; alltypes.rep_enum[4] = MyEnum_Truth; + + if (mode != 0) + { + /* Fill in values for optional fields */ + alltypes.has_opt_int32 = true; + alltypes.opt_int32 = 3041; + alltypes.has_opt_int64 = true; + alltypes.opt_int64 = 3042; + alltypes.has_opt_uint32 = true; + alltypes.opt_uint32 = 3043; + alltypes.has_opt_uint64 = true; + alltypes.opt_uint64 = 3044; + alltypes.has_opt_sint32 = true; + alltypes.opt_sint32 = 3045; + alltypes.has_opt_sint64 = true; + alltypes.opt_sint64 = 3046; + alltypes.has_opt_bool = true; + alltypes.opt_bool = true; + + alltypes.has_opt_fixed32 = true; + alltypes.opt_fixed32 = 3048; + alltypes.has_opt_sfixed32 = true; + alltypes.opt_sfixed32 = 3049; + alltypes.has_opt_float = true; + alltypes.opt_float = 3050.0f; + + alltypes.has_opt_fixed64 = true; + alltypes.opt_fixed64 = 3051; + alltypes.has_opt_sfixed64 = true; + alltypes.opt_sfixed64 = 3052; + alltypes.has_opt_double = true; + alltypes.opt_double = 3053.0; + + alltypes.has_opt_string = true; + strcpy(alltypes.opt_string, "3054"); + alltypes.has_opt_bytes = true; + alltypes.opt_bytes.size = 4; + memcpy(alltypes.opt_bytes.bytes, "3055", 4); + alltypes.has_opt_submsg = true; + strcpy(alltypes.opt_submsg.substuff1, "3056"); + alltypes.opt_submsg.substuff2 = 3056; + alltypes.has_opt_enum = true; + alltypes.opt_enum = MyEnum_Truth; + } + + alltypes.end = 1099; + + { + uint8_t buffer[1024]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Now encode it and check if we succeeded. */ + if (pb_encode(&stream, AllTypes_fields, &alltypes)) + { + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; /* Success */ + } + else + { + fprintf(stderr, "Encoding failed!\n"); + return 1; /* Failure */ + } + } +} diff --git a/libs/nanopb/tests/basic_buffer/SConscript b/libs/nanopb/tests/basic_buffer/SConscript new file mode 100644 index 00000000..acaf5ffa --- /dev/null +++ b/libs/nanopb/tests/basic_buffer/SConscript @@ -0,0 +1,12 @@ +# Build and run a basic round-trip test using memory buffer encoding. + +Import("env") + +enc = env.Program(["encode_buffer.c", "$COMMON/person.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) +dec = env.Program(["decode_buffer.c", "$COMMON/person.pb.c", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) + +env.RunTest(enc) +env.RunTest([dec, "encode_buffer.output"]) +env.Decode(["encode_buffer.output", "$COMMON/person.proto"], MESSAGE = "Person") +env.Compare(["decode_buffer.output", "encode_buffer.decoded"]) + diff --git a/libs/nanopb/tests/basic_buffer/decode_buffer.c b/libs/nanopb/tests/basic_buffer/decode_buffer.c new file mode 100644 index 00000000..291d164c --- /dev/null +++ b/libs/nanopb/tests/basic_buffer/decode_buffer.c @@ -0,0 +1,88 @@ +/* A very simple decoding test case, using person.proto. + * Produces output compatible with protoc --decode. + * Reads the encoded data from stdin and prints the values + * to stdout as text. + * + * Run e.g. ./test_encode1 | ./test_decode1 + */ + +#include +#include +#include "person.pb.h" +#include "test_helpers.h" + +/* This function is called once from main(), it handles + the decoding and printing. */ +bool print_person(pb_istream_t *stream) +{ + int i; + Person person = Person_init_zero; + + if (!pb_decode(stream, Person_fields, &person)) + return false; + + /* Now the decoding is done, rest is just to print stuff out. */ + + printf("name: \"%s\"\n", person.name); + printf("id: %ld\n", (long)person.id); + + if (person.has_email) + printf("email: \"%s\"\n", person.email); + + for (i = 0; i < person.phone_count; i++) + { + Person_PhoneNumber *phone = &person.phone[i]; + printf("phone {\n"); + printf(" number: \"%s\"\n", phone->number); + + if (phone->has_type) + { + switch (phone->type) + { + case Person_PhoneType_WORK: + printf(" type: WORK\n"); + break; + + case Person_PhoneType_HOME: + printf(" type: HOME\n"); + break; + + case Person_PhoneType_MOBILE: + printf(" type: MOBILE\n"); + break; + } + } + printf("}\n"); + } + + return true; +} + +int main() +{ + uint8_t buffer[Person_size]; + pb_istream_t stream; + size_t count; + + /* Read the data into buffer */ + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + + if (!feof(stdin)) + { + printf("Message does not fit in buffer\n"); + return 1; + } + + /* Construct a pb_istream_t for reading from the buffer */ + stream = pb_istream_from_buffer(buffer, count); + + /* Decode and print out the stuff */ + if (!print_person(&stream)) + { + printf("Parsing failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } else { + return 0; + } +} diff --git a/libs/nanopb/tests/basic_buffer/encode_buffer.c b/libs/nanopb/tests/basic_buffer/encode_buffer.c new file mode 100644 index 00000000..c412c14e --- /dev/null +++ b/libs/nanopb/tests/basic_buffer/encode_buffer.c @@ -0,0 +1,38 @@ +/* A very simple encoding test case using person.proto. + * Just puts constant data in the fields and encodes into + * buffer, which is then written to stdout. + */ + +#include +#include +#include "person.pb.h" +#include "test_helpers.h" + +int main() +{ + uint8_t buffer[Person_size]; + pb_ostream_t stream; + + /* Initialize the structure with constants */ + Person person = {"Test Person 99", 99, true, "test@person.com", + 3, {{"555-12345678", true, Person_PhoneType_MOBILE}, + {"99-2342", false, 0}, + {"1234-5678", true, Person_PhoneType_WORK}, + }}; + + stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Now encode it and check if we succeeded. */ + if (pb_encode(&stream, Person_fields, &person)) + { + /* Write the result data to stdout */ + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; /* Success */ + } + else + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; /* Failure */ + } +} diff --git a/libs/nanopb/tests/basic_stream/SConscript b/libs/nanopb/tests/basic_stream/SConscript new file mode 100644 index 00000000..7d668562 --- /dev/null +++ b/libs/nanopb/tests/basic_stream/SConscript @@ -0,0 +1,12 @@ +# Build and run a basic round-trip test using direct stream encoding. + +Import("env") + +enc = env.Program(["encode_stream.c", "$COMMON/person.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) +dec = env.Program(["decode_stream.c", "$COMMON/person.pb.c", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) + +env.RunTest(enc) +env.RunTest([dec, "encode_stream.output"]) +env.Decode(["encode_stream.output", "$COMMON/person.proto"], MESSAGE = "Person") +env.Compare(["decode_stream.output", "encode_stream.decoded"]) + diff --git a/libs/nanopb/tests/basic_stream/decode_stream.c b/libs/nanopb/tests/basic_stream/decode_stream.c new file mode 100644 index 00000000..798dcc50 --- /dev/null +++ b/libs/nanopb/tests/basic_stream/decode_stream.c @@ -0,0 +1,84 @@ +/* Same as test_decode1 but reads from stdin directly. + */ + +#include +#include +#include "person.pb.h" +#include "test_helpers.h" + +/* This function is called once from main(), it handles + the decoding and printing. + Ugly copy-paste from test_decode1.c. */ +bool print_person(pb_istream_t *stream) +{ + int i; + Person person = Person_init_zero; + + if (!pb_decode(stream, Person_fields, &person)) + return false; + + /* Now the decoding is done, rest is just to print stuff out. */ + + printf("name: \"%s\"\n", person.name); + printf("id: %ld\n", (long)person.id); + + if (person.has_email) + printf("email: \"%s\"\n", person.email); + + for (i = 0; i < person.phone_count; i++) + { + Person_PhoneNumber *phone = &person.phone[i]; + printf("phone {\n"); + printf(" number: \"%s\"\n", phone->number); + + if (phone->has_type) + { + switch (phone->type) + { + case Person_PhoneType_WORK: + printf(" type: WORK\n"); + break; + + case Person_PhoneType_HOME: + printf(" type: HOME\n"); + break; + + case Person_PhoneType_MOBILE: + printf(" type: MOBILE\n"); + break; + } + } + printf("}\n"); + } + + return true; +} + +/* This binds the pb_istream_t to stdin */ +bool callback(pb_istream_t *stream, uint8_t *buf, size_t count) +{ + FILE *file = (FILE*)stream->state; + bool status; + + status = (fread(buf, 1, count, file) == count); + + if (feof(file)) + stream->bytes_left = 0; + + return status; +} + +int main() +{ + pb_istream_t stream = {&callback, NULL, SIZE_MAX}; + stream.state = stdin; + SET_BINARY_MODE(stdin); + + if (!print_person(&stream)) + { + printf("Parsing failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } else { + return 0; + } +} diff --git a/libs/nanopb/tests/basic_stream/encode_stream.c b/libs/nanopb/tests/basic_stream/encode_stream.c new file mode 100644 index 00000000..7f571c41 --- /dev/null +++ b/libs/nanopb/tests/basic_stream/encode_stream.c @@ -0,0 +1,40 @@ +/* Same as test_encode1.c, except writes directly to stdout. + */ + +#include +#include +#include "person.pb.h" +#include "test_helpers.h" + +/* This binds the pb_ostream_t into the stdout stream */ +bool streamcallback(pb_ostream_t *stream, const uint8_t *buf, size_t count) +{ + FILE *file = (FILE*) stream->state; + return fwrite(buf, 1, count, file) == count; +} + +int main() +{ + /* Initialize the structure with constants */ + Person person = {"Test Person 99", 99, true, "test@person.com", + 3, {{"555-12345678", true, Person_PhoneType_MOBILE}, + {"99-2342", false, 0}, + {"1234-5678", true, Person_PhoneType_WORK}, + }}; + + /* Prepare the stream, output goes directly to stdout */ + pb_ostream_t stream = {&streamcallback, NULL, SIZE_MAX, 0}; + stream.state = stdout; + SET_BINARY_MODE(stdout); + + /* Now encode it and check if we succeeded. */ + if (pb_encode(&stream, Person_fields, &person)) + { + return 0; /* Success */ + } + else + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; /* Failure */ + } +} diff --git a/libs/nanopb/tests/buffer_only/SConscript b/libs/nanopb/tests/buffer_only/SConscript new file mode 100644 index 00000000..55b747b0 --- /dev/null +++ b/libs/nanopb/tests/buffer_only/SConscript @@ -0,0 +1,28 @@ +# Run the alltypes test case, but compile with PB_BUFFER_ONLY=1 + +Import("env") + +# Take copy of the files for custom build. +c = Copy("$TARGET", "$SOURCE") +env.Command("alltypes.pb.h", "$BUILD/alltypes/alltypes.pb.h", c) +env.Command("alltypes.pb.c", "$BUILD/alltypes/alltypes.pb.c", c) +env.Command("encode_alltypes.c", "$BUILD/alltypes/encode_alltypes.c", c) +env.Command("decode_alltypes.c", "$BUILD/alltypes/decode_alltypes.c", c) + +# Define the compilation options +opts = env.Clone() +opts.Append(CPPDEFINES = {'PB_BUFFER_ONLY': 1}) + +# Build new version of core +strict = opts.Clone() +strict.Append(CFLAGS = strict['CORECFLAGS']) +strict.Object("pb_decode_bufonly.o", "$NANOPB/pb_decode.c") +strict.Object("pb_encode_bufonly.o", "$NANOPB/pb_encode.c") +strict.Object("pb_common_bufonly.o", "$NANOPB/pb_common.c") + +# Now build and run the test normally. +enc = opts.Program(["encode_alltypes.c", "alltypes.pb.c", "pb_encode_bufonly.o", "pb_common_bufonly.o"]) +dec = opts.Program(["decode_alltypes.c", "alltypes.pb.c", "pb_decode_bufonly.o", "pb_common_bufonly.o"]) + +env.RunTest(enc) +env.RunTest([dec, "encode_alltypes.output"]) diff --git a/libs/nanopb/tests/callbacks/SConscript b/libs/nanopb/tests/callbacks/SConscript new file mode 100644 index 00000000..44521439 --- /dev/null +++ b/libs/nanopb/tests/callbacks/SConscript @@ -0,0 +1,14 @@ +# Test the functionality of the callback fields. + +Import("env") + +env.NanopbProto("callbacks") +enc = env.Program(["encode_callbacks.c", "callbacks.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) +dec = env.Program(["decode_callbacks.c", "callbacks.pb.c", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) + +env.RunTest(enc) +env.RunTest([dec, "encode_callbacks.output"]) + +env.Decode(["encode_callbacks.output", "callbacks.proto"], MESSAGE = "TestMessage") +env.Compare(["decode_callbacks.output", "encode_callbacks.decoded"]) + diff --git a/libs/nanopb/tests/callbacks/callbacks.proto b/libs/nanopb/tests/callbacks/callbacks.proto new file mode 100644 index 00000000..96ac744d --- /dev/null +++ b/libs/nanopb/tests/callbacks/callbacks.proto @@ -0,0 +1,18 @@ +syntax = "proto2"; + +message SubMessage { + optional string stringvalue = 1; + repeated int32 int32value = 2; + repeated fixed32 fixed32value = 3; + repeated fixed64 fixed64value = 4; +} + +message TestMessage { + optional string stringvalue = 1; + repeated int32 int32value = 2; + repeated fixed32 fixed32value = 3; + repeated fixed64 fixed64value = 4; + optional SubMessage submsg = 5; + repeated string repeatedstring = 6; +} + diff --git a/libs/nanopb/tests/callbacks/decode_callbacks.c b/libs/nanopb/tests/callbacks/decode_callbacks.c new file mode 100644 index 00000000..45724d0b --- /dev/null +++ b/libs/nanopb/tests/callbacks/decode_callbacks.c @@ -0,0 +1,97 @@ +/* Decoding testcase for callback fields. + * Run e.g. ./test_encode_callbacks | ./test_decode_callbacks + */ + +#include +#include +#include "callbacks.pb.h" +#include "test_helpers.h" + +bool print_string(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint8_t buffer[1024] = {0}; + + /* We could read block-by-block to avoid the large buffer... */ + if (stream->bytes_left > sizeof(buffer) - 1) + return false; + + if (!pb_read(stream, buffer, stream->bytes_left)) + return false; + + /* Print the string, in format comparable with protoc --decode. + * Format comes from the arg defined in main(). + */ + printf((char*)*arg, buffer); + return true; +} + +bool print_int32(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint64_t value; + if (!pb_decode_varint(stream, &value)) + return false; + + printf((char*)*arg, (long)value); + return true; +} + +bool print_fixed32(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint32_t value; + if (!pb_decode_fixed32(stream, &value)) + return false; + + printf((char*)*arg, (long)value); + return true; +} + +bool print_fixed64(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint64_t value; + if (!pb_decode_fixed64(stream, &value)) + return false; + + printf((char*)*arg, (long)value); + return true; +} + +int main() +{ + uint8_t buffer[1024]; + size_t length; + pb_istream_t stream; + /* Note: empty initializer list initializes the struct with all-0. + * This is recommended so that unused callbacks are set to NULL instead + * of crashing at runtime. + */ + TestMessage testmessage = {{{NULL}}}; + + SET_BINARY_MODE(stdin); + length = fread(buffer, 1, 1024, stdin); + stream = pb_istream_from_buffer(buffer, length); + + testmessage.submsg.stringvalue.funcs.decode = &print_string; + testmessage.submsg.stringvalue.arg = "submsg {\n stringvalue: \"%s\"\n"; + testmessage.submsg.int32value.funcs.decode = &print_int32; + testmessage.submsg.int32value.arg = " int32value: %ld\n"; + testmessage.submsg.fixed32value.funcs.decode = &print_fixed32; + testmessage.submsg.fixed32value.arg = " fixed32value: %ld\n"; + testmessage.submsg.fixed64value.funcs.decode = &print_fixed64; + testmessage.submsg.fixed64value.arg = " fixed64value: %ld\n}\n"; + + testmessage.stringvalue.funcs.decode = &print_string; + testmessage.stringvalue.arg = "stringvalue: \"%s\"\n"; + testmessage.int32value.funcs.decode = &print_int32; + testmessage.int32value.arg = "int32value: %ld\n"; + testmessage.fixed32value.funcs.decode = &print_fixed32; + testmessage.fixed32value.arg = "fixed32value: %ld\n"; + testmessage.fixed64value.funcs.decode = &print_fixed64; + testmessage.fixed64value.arg = "fixed64value: %ld\n"; + testmessage.repeatedstring.funcs.decode = &print_string; + testmessage.repeatedstring.arg = "repeatedstring: \"%s\"\n"; + + if (!pb_decode(&stream, TestMessage_fields, &testmessage)) + return 1; + + return 0; +} diff --git a/libs/nanopb/tests/callbacks/encode_callbacks.c b/libs/nanopb/tests/callbacks/encode_callbacks.c new file mode 100644 index 00000000..6cb67b1e --- /dev/null +++ b/libs/nanopb/tests/callbacks/encode_callbacks.c @@ -0,0 +1,92 @@ +/* Encoding testcase for callback fields */ + +#include +#include +#include +#include "callbacks.pb.h" +#include "test_helpers.h" + +bool encode_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + char *str = "Hello world!"; + + if (!pb_encode_tag_for_field(stream, field)) + return false; + + return pb_encode_string(stream, (uint8_t*)str, strlen(str)); +} + +bool encode_int32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + if (!pb_encode_tag_for_field(stream, field)) + return false; + + return pb_encode_varint(stream, 42); +} + +bool encode_fixed32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + uint32_t value = 42; + + if (!pb_encode_tag_for_field(stream, field)) + return false; + + return pb_encode_fixed32(stream, &value); +} + +bool encode_fixed64(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + uint64_t value = 42; + + if (!pb_encode_tag_for_field(stream, field)) + return false; + + return pb_encode_fixed64(stream, &value); +} + +bool encode_repeatedstring(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + char *str[4] = {"Hello world!", "", "Test", "Test2"}; + int i; + + for (i = 0; i < 4; i++) + { + if (!pb_encode_tag_for_field(stream, field)) + return false; + + if (!pb_encode_string(stream, (uint8_t*)str[i], strlen(str[i]))) + return false; + } + return true; +} + +int main() +{ + uint8_t buffer[1024]; + pb_ostream_t stream; + TestMessage testmessage = {{{NULL}}}; + + stream = pb_ostream_from_buffer(buffer, 1024); + + testmessage.stringvalue.funcs.encode = &encode_string; + testmessage.int32value.funcs.encode = &encode_int32; + testmessage.fixed32value.funcs.encode = &encode_fixed32; + testmessage.fixed64value.funcs.encode = &encode_fixed64; + + testmessage.has_submsg = true; + testmessage.submsg.stringvalue.funcs.encode = &encode_string; + testmessage.submsg.int32value.funcs.encode = &encode_int32; + testmessage.submsg.fixed32value.funcs.encode = &encode_fixed32; + testmessage.submsg.fixed64value.funcs.encode = &encode_fixed64; + + testmessage.repeatedstring.funcs.encode = &encode_repeatedstring; + + if (!pb_encode(&stream, TestMessage_fields, &testmessage)) + return 1; + + SET_BINARY_MODE(stdout); + if (fwrite(buffer, stream.bytes_written, 1, stdout) != 1) + return 2; + + return 0; +} diff --git a/libs/nanopb/tests/common/SConscript b/libs/nanopb/tests/common/SConscript new file mode 100644 index 00000000..05e2f852 --- /dev/null +++ b/libs/nanopb/tests/common/SConscript @@ -0,0 +1,48 @@ +# Build the common files needed by multiple test cases + +Import('env') + +# Protocol definitions for the encode/decode_unittests +env.NanopbProto("unittestproto") + +# Protocol definitions for basic_buffer/stream tests +env.NanopbProto("person") + +#-------------------------------------------- +# Binaries of the pb_decode.c and pb_encode.c +# These are built using more strict warning flags. +strict = env.Clone() +strict.Append(CFLAGS = strict['CORECFLAGS']) +strict.Object("pb_decode.o", "$NANOPB/pb_decode.c") +strict.Object("pb_encode.o", "$NANOPB/pb_encode.c") +strict.Object("pb_common.o", "$NANOPB/pb_common.c") + +#----------------------------------------------- +# Binaries of pb_decode etc. with malloc support +# Uses malloc_wrappers.c to count allocations. +malloc_env = env.Clone() +malloc_env.Append(CPPDEFINES = {'PB_ENABLE_MALLOC': 1, + 'PB_SYSTEM_HEADER': '\\"malloc_wrappers_syshdr.h\\"'}) +malloc_env.Append(CPPPATH = ["$COMMON"]) + +if 'SYSHDR' in malloc_env: + malloc_env.Append(CPPDEFINES = {'PB_OLD_SYSHDR': malloc_env['SYSHDR']}) + +# Disable libmudflap, because it will confuse valgrind +# and other memory leak detection tools. +if '-fmudflap' in env["CCFLAGS"]: + malloc_env["CCFLAGS"].remove("-fmudflap") + malloc_env["LINKFLAGS"].remove("-fmudflap") + malloc_env["LIBS"].remove("mudflap") + +malloc_strict = malloc_env.Clone() +malloc_strict.Append(CFLAGS = malloc_strict['CORECFLAGS']) +malloc_strict.Object("pb_decode_with_malloc.o", "$NANOPB/pb_decode.c") +malloc_strict.Object("pb_encode_with_malloc.o", "$NANOPB/pb_encode.c") +malloc_strict.Object("pb_common_with_malloc.o", "$NANOPB/pb_common.c") + +malloc_env.Object("malloc_wrappers.o", "malloc_wrappers.c") +malloc_env.Depends("$NANOPB/pb.h", ["malloc_wrappers_syshdr.h", "malloc_wrappers.h"]) + +Export("malloc_env") + diff --git a/libs/nanopb/tests/common/malloc_wrappers.c b/libs/nanopb/tests/common/malloc_wrappers.c new file mode 100644 index 00000000..ad69f1ce --- /dev/null +++ b/libs/nanopb/tests/common/malloc_wrappers.c @@ -0,0 +1,54 @@ +#include "malloc_wrappers.h" +#include +#include +#include + +static size_t alloc_count = 0; + +/* Allocate memory and place check values before and after. */ +void* malloc_with_check(size_t size) +{ + size_t size32 = (size + 3) / 4 + 3; + uint32_t *buf = malloc(size32 * sizeof(uint32_t)); + buf[0] = size32; + buf[1] = 0xDEADBEEF; + buf[size32 - 1] = 0xBADBAD; + return buf + 2; +} + +/* Free memory allocated with malloc_with_check() and do the checks. */ +void free_with_check(void *mem) +{ + uint32_t *buf = (uint32_t*)mem - 2; + assert(buf[1] == 0xDEADBEEF); + assert(buf[buf[0] - 1] == 0xBADBAD); + free(buf); +} + +/* Track memory usage */ +void* counting_realloc(void *ptr, size_t size) +{ + /* Don't allocate crazy amounts of RAM when fuzzing */ + if (size > 1000000) + return NULL; + + if (!ptr && size) + alloc_count++; + + return realloc(ptr, size); +} + +void counting_free(void *ptr) +{ + if (ptr) + { + assert(alloc_count > 0); + alloc_count--; + free(ptr); + } +} + +size_t get_alloc_count() +{ + return alloc_count; +} diff --git a/libs/nanopb/tests/common/malloc_wrappers.h b/libs/nanopb/tests/common/malloc_wrappers.h new file mode 100644 index 00000000..7eec7952 --- /dev/null +++ b/libs/nanopb/tests/common/malloc_wrappers.h @@ -0,0 +1,7 @@ +#include + +void* malloc_with_check(size_t size); +void free_with_check(void *mem); +void* counting_realloc(void *ptr, size_t size); +void counting_free(void *ptr); +size_t get_alloc_count(); diff --git a/libs/nanopb/tests/common/malloc_wrappers_syshdr.h b/libs/nanopb/tests/common/malloc_wrappers_syshdr.h new file mode 100644 index 00000000..d295d9ed --- /dev/null +++ b/libs/nanopb/tests/common/malloc_wrappers_syshdr.h @@ -0,0 +1,15 @@ +/* This is just a wrapper in order to get our own malloc wrappers into nanopb core. */ + +#define pb_realloc(ptr,size) counting_realloc(ptr,size) +#define pb_free(ptr) counting_free(ptr) + +#ifdef PB_OLD_SYSHDR +#include PB_OLD_SYSHDR +#else +#include +#include +#include +#include +#endif + +#include diff --git a/libs/nanopb/tests/common/person.proto b/libs/nanopb/tests/common/person.proto new file mode 100644 index 00000000..becefdf3 --- /dev/null +++ b/libs/nanopb/tests/common/person.proto @@ -0,0 +1,22 @@ +syntax = "proto2"; + +import "nanopb.proto"; + +message Person { + required string name = 1 [(nanopb).max_size = 40]; + required int32 id = 2; + optional string email = 3 [(nanopb).max_size = 40]; + + enum PhoneType { + MOBILE = 0; + HOME = 1; + WORK = 2; + } + + message PhoneNumber { + required string number = 1 [(nanopb).max_size = 40]; + optional PhoneType type = 2 [default = HOME]; + } + + repeated PhoneNumber phone = 4 [(nanopb).max_count = 5]; +} diff --git a/libs/nanopb/tests/common/test_helpers.h b/libs/nanopb/tests/common/test_helpers.h new file mode 100644 index 00000000..f77760a5 --- /dev/null +++ b/libs/nanopb/tests/common/test_helpers.h @@ -0,0 +1,17 @@ +/* Compatibility helpers for the test programs. */ + +#ifndef _TEST_HELPERS_H_ +#define _TEST_HELPERS_H_ + +#ifdef _WIN32 +#include +#include +#define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) + +#else +#define SET_BINARY_MODE(file) + +#endif + + +#endif diff --git a/libs/nanopb/tests/common/unittestproto.proto b/libs/nanopb/tests/common/unittestproto.proto new file mode 100644 index 00000000..23b5b97f --- /dev/null +++ b/libs/nanopb/tests/common/unittestproto.proto @@ -0,0 +1,43 @@ +syntax = "proto2"; + +import 'nanopb.proto'; + +message IntegerArray { + repeated int32 data = 1 [(nanopb).max_count = 10]; +} + +message FloatArray { + repeated float data = 1 [(nanopb).max_count = 10]; +} + +message StringMessage { + required string data = 1 [(nanopb).max_size = 10]; +} + +message BytesMessage { + required bytes data = 1 [(nanopb).max_size = 16]; +} + +message CallbackArray { + // We cheat a bit and use this message for testing other types, too. + // Nanopb does not care about the actual defined data type for callback + // fields. + repeated int32 data = 1; +} + +message IntegerContainer { + required IntegerArray submsg = 1; +} + +message CallbackContainer { + required CallbackArray submsg = 1; +} + +message CallbackContainerContainer { + required CallbackContainer submsg = 1; +} + +message StringPointerContainer { + repeated string rep_str = 1 [(nanopb).type = FT_POINTER]; +} + diff --git a/libs/nanopb/tests/common/unittests.h b/libs/nanopb/tests/common/unittests.h new file mode 100644 index 00000000..c2b470ad --- /dev/null +++ b/libs/nanopb/tests/common/unittests.h @@ -0,0 +1,14 @@ +#include + +#define COMMENT(x) printf("\n----" x "----\n"); +#define STR(x) #x +#define STR2(x) STR(x) +#define TEST(x) \ + if (!(x)) { \ + fprintf(stderr, "\033[31;1mFAILED:\033[22;39m " __FILE__ ":" STR2(__LINE__) " " #x "\n"); \ + status = 1; \ + } else { \ + printf("\033[32;1mOK:\033[22;39m " #x "\n"); \ + } + + diff --git a/libs/nanopb/tests/cxx_main_program/SConscript b/libs/nanopb/tests/cxx_main_program/SConscript new file mode 100644 index 00000000..edb88127 --- /dev/null +++ b/libs/nanopb/tests/cxx_main_program/SConscript @@ -0,0 +1,25 @@ +# Run the alltypes test case, but compile it as C++ instead. +# In fact, compile the entire nanopb using C++ compiler. + +Import("env") + +# This is needed to get INT32_MIN etc. macros defined +env = env.Clone() +env.Append(CPPDEFINES = ['__STDC_LIMIT_MACROS']) + +# Copy the files to .cxx extension in order to force C++ build. +c = Copy("$TARGET", "$SOURCE") +env.Command("pb_encode.cxx", "#../pb_encode.c", c) +env.Command("pb_decode.cxx", "#../pb_decode.c", c) +env.Command("pb_common.cxx", "#../pb_common.c", c) +env.Command("alltypes.pb.h", "$BUILD/alltypes/alltypes.pb.h", c) +env.Command("alltypes.pb.cxx", "$BUILD/alltypes/alltypes.pb.c", c) +env.Command("encode_alltypes.cxx", "$BUILD/alltypes/encode_alltypes.c", c) +env.Command("decode_alltypes.cxx", "$BUILD/alltypes/decode_alltypes.c", c) + +# Now build and run the test normally. +enc = env.Program(["encode_alltypes.cxx", "alltypes.pb.cxx", "pb_encode.cxx", "pb_common.cxx"]) +dec = env.Program(["decode_alltypes.cxx", "alltypes.pb.cxx", "pb_decode.cxx", "pb_common.cxx"]) + +env.RunTest(enc) +env.RunTest([dec, "encode_alltypes.output"]) diff --git a/libs/nanopb/tests/cyclic_messages/SConscript b/libs/nanopb/tests/cyclic_messages/SConscript new file mode 100644 index 00000000..c782001c --- /dev/null +++ b/libs/nanopb/tests/cyclic_messages/SConscript @@ -0,0 +1,11 @@ +Import("env") + +# Encode cyclic messages with callback fields + +c = Copy("$TARGET", "$SOURCE") +env.Command("cyclic_callback.proto", "cyclic.proto", c) +env.NanopbProto(["cyclic_callback", "cyclic_callback.options"]) + +enc_callback = env.Program(["encode_cyclic_callback.c", "cyclic_callback.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) + + diff --git a/libs/nanopb/tests/cyclic_messages/cyclic.proto b/libs/nanopb/tests/cyclic_messages/cyclic.proto new file mode 100644 index 00000000..8cab0b14 --- /dev/null +++ b/libs/nanopb/tests/cyclic_messages/cyclic.proto @@ -0,0 +1,27 @@ +// Test structures with cyclic references. +// These can only be handled in pointer/callback mode, +// see associated .options files. + +syntax = "proto2"; + +message TreeNode +{ + optional int32 leaf = 1; + optional TreeNode left = 2; + optional TreeNode right = 3; +} + +message Dictionary +{ + repeated KeyValuePair dictItem = 1; +} + +message KeyValuePair +{ + required string key = 1; + optional string stringValue = 2; + optional int32 intValue = 3; + optional Dictionary dictValue = 4; + optional TreeNode treeValue = 5; +} + diff --git a/libs/nanopb/tests/cyclic_messages/cyclic_callback.options b/libs/nanopb/tests/cyclic_messages/cyclic_callback.options new file mode 100644 index 00000000..fd4e1e1c --- /dev/null +++ b/libs/nanopb/tests/cyclic_messages/cyclic_callback.options @@ -0,0 +1,7 @@ +TreeNode.left type:FT_CALLBACK +TreeNode.right type:FT_CALLBACK + +Dictionary.data type:FT_CALLBACK +KeyValuePair.key max_size:8 +KeyValuePair.stringValue max_size:8 +KeyValuePair.treeValue type:FT_CALLBACK diff --git a/libs/nanopb/tests/cyclic_messages/encode_cyclic_callback.c b/libs/nanopb/tests/cyclic_messages/encode_cyclic_callback.c new file mode 100644 index 00000000..7f67e70c --- /dev/null +++ b/libs/nanopb/tests/cyclic_messages/encode_cyclic_callback.c @@ -0,0 +1,148 @@ +/* This program parses an input string in a format a bit like JSON: + * {'foobar': 1234, 'xyz': 'abc', 'tree': [[[1, 2], 3], [4, 5]]} + * and encodes it as protobuf + * + * Note: The string parsing here is not in any way intended to be robust + * nor safe against buffer overflows. It is just for this test. + */ + +#include +#include +#include +#include +#include "cyclic_callback.pb.h" + +static char *find_end_of_item(char *p) +{ + int depth = 0; + do { + if (*p == '[' || *p == '{') depth++; + if (*p == ']' || *p == '}') depth--; + p++; + } while (depth > 0 || (*p != ',' && *p != '}')); + + if (*p == '}') + return p; /* End of parent dict */ + + p++; + while (*p == ' ') p++; + return p; +} + +/* Parse a tree in format [[1 2] 3] and encode it directly to protobuf */ +static bool encode_tree(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + TreeNode tree = TreeNode_init_zero; + char *p = (char*)*arg; + + if (*p == '[') + { + /* This is a tree branch */ + p++; + tree.left.funcs.encode = encode_tree; + tree.left.arg = p; + + p = find_end_of_item(p); + tree.right.funcs.encode = encode_tree; + tree.right.arg = p; + } + else + { + /* This is a leaf node */ + tree.has_leaf = true; + tree.leaf = atoi(p); + } + + return pb_encode_tag_for_field(stream, field) && + pb_encode_submessage(stream, TreeNode_fields, &tree); +} + +/* Parse a dictionary in format {'name': value} and encode it directly to protobuf */ +static bool encode_dictionary(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + int textlen; + char *p = (char*)*arg; + if (*p == '{') p++; + while (*p != '}') + { + KeyValuePair pair = KeyValuePair_init_zero; + + if (*p != '\'') + PB_RETURN_ERROR(stream, "invalid key, missing quote"); + + p++; /* Starting quote of key */ + textlen = strchr(p, '\'') - p; + strncpy(pair.key, p, textlen); + pair.key[textlen] = 0; + p += textlen + 2; + + while (*p == ' ') p++; + + if (*p == '[') + { + /* Value is a tree */ + pair.treeValue.funcs.encode = encode_tree; + pair.treeValue.arg = p; + } + else if (*p == '\'') + { + /* Value is a string */ + pair.has_stringValue = true; + p++; + textlen = strchr(p, '\'') - p; + strncpy(pair.stringValue, p, textlen); + pair.stringValue[textlen] = 0; + } + else if (*p == '{') + { + /* Value is a dictionary */ + pair.has_dictValue = true; + pair.dictValue.dictItem.funcs.encode = encode_dictionary; + pair.dictValue.dictItem.arg = p; + } + else + { + /* Value is integer */ + pair.has_intValue = true; + pair.intValue = atoi(p); + } + + p = find_end_of_item(p); + + if (!pb_encode_tag_for_field(stream, field)) + return false; + + if (!pb_encode_submessage(stream, KeyValuePair_fields, &pair)) + return false; + } + + return true; +} + + +int main(int argc, char *argv[]) +{ + uint8_t buffer[256]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + Dictionary dict = Dictionary_init_zero; + + if (argc <= 1) + { + fprintf(stderr, "Usage: %s \"{'foobar': 1234, ...}\"\n", argv[0]); + return 1; + } + + dict.dictItem.funcs.encode = encode_dictionary; + dict.dictItem.arg = argv[1]; + + if (!pb_encode(&stream, Dictionary_fields, &dict)) + { + fprintf(stderr, "Encoding error: %s\n", PB_GET_ERROR(&stream)); + return 1; + } + + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; +} + + diff --git a/libs/nanopb/tests/decode_unittests/SConscript b/libs/nanopb/tests/decode_unittests/SConscript new file mode 100644 index 00000000..369b9dc7 --- /dev/null +++ b/libs/nanopb/tests/decode_unittests/SConscript @@ -0,0 +1,4 @@ +Import('env') +p = env.Program(["decode_unittests.c", "$COMMON/unittestproto.pb.c"]) +env.RunTest(p) + diff --git a/libs/nanopb/tests/decode_unittests/decode_unittests.c b/libs/nanopb/tests/decode_unittests/decode_unittests.c new file mode 100644 index 00000000..a6f5c17e --- /dev/null +++ b/libs/nanopb/tests/decode_unittests/decode_unittests.c @@ -0,0 +1,388 @@ +/* This includes the whole .c file to get access to static functions. */ +#define PB_ENABLE_MALLOC +#include "pb_common.c" +#include "pb_decode.c" + +#include +#include +#include "unittests.h" +#include "unittestproto.pb.h" + +#define S(x) pb_istream_from_buffer((uint8_t*)x, sizeof(x) - 1) + +bool stream_callback(pb_istream_t *stream, uint8_t *buf, size_t count) +{ + if (stream->state != NULL) + return false; /* Simulate error */ + + if (buf != NULL) + memset(buf, 'x', count); + return true; +} + +/* Verifies that the stream passed to callback matches the byte array pointed to by arg. */ +bool callback_check(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + int i; + uint8_t byte; + pb_bytes_array_t *ref = (pb_bytes_array_t*) *arg; + + for (i = 0; i < ref->size; i++) + { + if (!pb_read(stream, &byte, 1)) + return false; + + if (byte != ref->bytes[i]) + return false; + } + + return true; +} + +int main() +{ + int status = 0; + + { + uint8_t buffer1[] = "foobartest1234"; + uint8_t buffer2[sizeof(buffer1)]; + pb_istream_t stream = pb_istream_from_buffer(buffer1, sizeof(buffer1)); + + COMMENT("Test pb_read and pb_istream_t"); + TEST(pb_read(&stream, buffer2, 6)) + TEST(memcmp(buffer2, "foobar", 6) == 0) + TEST(stream.bytes_left == sizeof(buffer1) - 6) + TEST(pb_read(&stream, buffer2 + 6, stream.bytes_left)) + TEST(memcmp(buffer1, buffer2, sizeof(buffer1)) == 0) + TEST(stream.bytes_left == 0) + TEST(!pb_read(&stream, buffer2, 1)) + } + + { + uint8_t buffer[20]; + pb_istream_t stream = {&stream_callback, NULL, 20}; + + COMMENT("Test pb_read with custom callback"); + TEST(pb_read(&stream, buffer, 5)) + TEST(memcmp(buffer, "xxxxx", 5) == 0) + TEST(!pb_read(&stream, buffer, 50)) + stream.state = (void*)1; /* Simulated error return from callback */ + TEST(!pb_read(&stream, buffer, 5)) + stream.state = NULL; + TEST(pb_read(&stream, buffer, 15)) + } + + { + pb_istream_t s; + uint64_t u; + int64_t i; + + COMMENT("Test pb_decode_varint"); + TEST((s = S("\x00"), pb_decode_varint(&s, &u) && u == 0)); + TEST((s = S("\x01"), pb_decode_varint(&s, &u) && u == 1)); + TEST((s = S("\xAC\x02"), pb_decode_varint(&s, &u) && u == 300)); + TEST((s = S("\xFF\xFF\xFF\xFF\x0F"), pb_decode_varint(&s, &u) && u == UINT32_MAX)); + TEST((s = S("\xFF\xFF\xFF\xFF\x0F"), pb_decode_varint(&s, (uint64_t*)&i) && i == UINT32_MAX)); + TEST((s = S("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"), + pb_decode_varint(&s, (uint64_t*)&i) && i == -1)); + TEST((s = S("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"), + pb_decode_varint(&s, &u) && u == UINT64_MAX)); + TEST((s = S("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"), + !pb_decode_varint(&s, &u))); + } + + { + pb_istream_t s; + uint32_t u; + + COMMENT("Test pb_decode_varint32"); + TEST((s = S("\x00"), pb_decode_varint32(&s, &u) && u == 0)); + TEST((s = S("\x01"), pb_decode_varint32(&s, &u) && u == 1)); + TEST((s = S("\xAC\x02"), pb_decode_varint32(&s, &u) && u == 300)); + TEST((s = S("\xFF\xFF\xFF\xFF\x0F"), pb_decode_varint32(&s, &u) && u == UINT32_MAX)); + TEST((s = S("\xFF\xFF\xFF\xFF\xFF\x01"), !pb_decode_varint32(&s, &u))); + } + + { + pb_istream_t s; + COMMENT("Test pb_skip_varint"); + TEST((s = S("\x00""foobar"), pb_skip_varint(&s) && s.bytes_left == 6)) + TEST((s = S("\xAC\x02""foobar"), pb_skip_varint(&s) && s.bytes_left == 6)) + TEST((s = S("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01""foobar"), + pb_skip_varint(&s) && s.bytes_left == 6)) + TEST((s = S("\xFF"), !pb_skip_varint(&s))) + } + + { + pb_istream_t s; + COMMENT("Test pb_skip_string") + TEST((s = S("\x00""foobar"), pb_skip_string(&s) && s.bytes_left == 6)) + TEST((s = S("\x04""testfoobar"), pb_skip_string(&s) && s.bytes_left == 6)) + TEST((s = S("\x04"), !pb_skip_string(&s))) + TEST((s = S("\xFF"), !pb_skip_string(&s))) + } + + { + pb_istream_t s = S("\x01\x00"); + pb_field_t f = {1, PB_LTYPE_VARINT, 0, 0, 4, 0, 0}; + uint32_t d; + COMMENT("Test pb_dec_varint using uint32_t") + TEST(pb_dec_varint(&s, &f, &d) && d == 1) + + /* Verify that no more than data_size is written. */ + d = 0xFFFFFFFF; + f.data_size = 1; + TEST(pb_dec_varint(&s, &f, &d) && (d == 0xFFFFFF00 || d == 0x00FFFFFF)) + } + + { + pb_istream_t s; + pb_field_t f = {1, PB_LTYPE_SVARINT, 0, 0, 4, 0, 0}; + int32_t d; + + COMMENT("Test pb_dec_svarint using int32_t") + TEST((s = S("\x01"), pb_dec_svarint(&s, &f, &d) && d == -1)) + TEST((s = S("\x02"), pb_dec_svarint(&s, &f, &d) && d == 1)) + TEST((s = S("\xfe\xff\xff\xff\x0f"), pb_dec_svarint(&s, &f, &d) && d == INT32_MAX)) + TEST((s = S("\xff\xff\xff\xff\x0f"), pb_dec_svarint(&s, &f, &d) && d == INT32_MIN)) + } + + { + pb_istream_t s; + pb_field_t f = {1, PB_LTYPE_SVARINT, 0, 0, 8, 0, 0}; + int64_t d; + + COMMENT("Test pb_dec_svarint using int64_t") + TEST((s = S("\x01"), pb_dec_svarint(&s, &f, &d) && d == -1)) + TEST((s = S("\x02"), pb_dec_svarint(&s, &f, &d) && d == 1)) + TEST((s = S("\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"), pb_dec_svarint(&s, &f, &d) && d == INT64_MAX)) + TEST((s = S("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"), pb_dec_svarint(&s, &f, &d) && d == INT64_MIN)) + } + + { + pb_istream_t s; + pb_field_t f = {1, PB_LTYPE_SVARINT, 0, 0, 4, 0, 0}; + int32_t d; + + COMMENT("Test pb_dec_svarint overflow detection using int32_t"); + TEST((s = S("\xfe\xff\xff\xff\x0f"), pb_dec_svarint(&s, &f, &d))); + TEST((s = S("\xfe\xff\xff\xff\x10"), !pb_dec_svarint(&s, &f, &d))); + TEST((s = S("\xff\xff\xff\xff\x0f"), pb_dec_svarint(&s, &f, &d))); + TEST((s = S("\xff\xff\xff\xff\x10"), !pb_dec_svarint(&s, &f, &d))); + } + + { + pb_istream_t s; + pb_field_t f = {1, PB_LTYPE_SVARINT, 0, 0, 4, 0, 0}; + uint32_t d; + + COMMENT("Test pb_dec_uvarint using uint32_t") + TEST((s = S("\x01"), pb_dec_uvarint(&s, &f, &d) && d == 1)) + TEST((s = S("\x02"), pb_dec_uvarint(&s, &f, &d) && d == 2)) + TEST((s = S("\xff\xff\xff\xff\x0f"), pb_dec_uvarint(&s, &f, &d) && d == UINT32_MAX)) + } + + { + pb_istream_t s; + pb_field_t f = {1, PB_LTYPE_SVARINT, 0, 0, 8, 0, 0}; + uint64_t d; + + COMMENT("Test pb_dec_uvarint using uint64_t") + TEST((s = S("\x01"), pb_dec_uvarint(&s, &f, &d) && d == 1)) + TEST((s = S("\x02"), pb_dec_uvarint(&s, &f, &d) && d == 2)) + TEST((s = S("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"), pb_dec_uvarint(&s, &f, &d) && d == UINT64_MAX)) + } + + { + pb_istream_t s; + pb_field_t f = {1, PB_LTYPE_SVARINT, 0, 0, 4, 0, 0}; + uint32_t d; + + COMMENT("Test pb_dec_uvarint overflow detection using int32_t"); + TEST((s = S("\xff\xff\xff\xff\x0f"), pb_dec_uvarint(&s, &f, &d))); + TEST((s = S("\xff\xff\xff\xff\x10"), !pb_dec_uvarint(&s, &f, &d))); + } + + { + pb_istream_t s; + pb_field_t f = {1, PB_LTYPE_FIXED32, 0, 0, 4, 0, 0}; + float d; + + COMMENT("Test pb_dec_fixed32 using float (failures here may be caused by imperfect rounding)") + TEST((s = S("\x00\x00\x00\x00"), pb_dec_fixed32(&s, &f, &d) && d == 0.0f)) + TEST((s = S("\x00\x00\xc6\x42"), pb_dec_fixed32(&s, &f, &d) && d == 99.0f)) + TEST((s = S("\x4e\x61\x3c\xcb"), pb_dec_fixed32(&s, &f, &d) && d == -12345678.0f)) + TEST((s = S("\x00"), !pb_dec_fixed32(&s, &f, &d) && d == -12345678.0f)) + } + + { + pb_istream_t s; + pb_field_t f = {1, PB_LTYPE_FIXED64, 0, 0, 8, 0, 0}; + double d; + + COMMENT("Test pb_dec_fixed64 using double (failures here may be caused by imperfect rounding)") + TEST((s = S("\x00\x00\x00\x00\x00\x00\x00\x00"), pb_dec_fixed64(&s, &f, &d) && d == 0.0)) + TEST((s = S("\x00\x00\x00\x00\x00\xc0\x58\x40"), pb_dec_fixed64(&s, &f, &d) && d == 99.0)) + TEST((s = S("\x00\x00\x00\xc0\x29\x8c\x67\xc1"), pb_dec_fixed64(&s, &f, &d) && d == -12345678.0f)) + } + + { + pb_istream_t s; + struct { pb_size_t size; uint8_t bytes[5]; } d; + pb_field_t f = {1, PB_LTYPE_BYTES, 0, 0, sizeof(d), 0, 0}; + + COMMENT("Test pb_dec_bytes") + TEST((s = S("\x00"), pb_dec_bytes(&s, &f, &d) && d.size == 0)) + TEST((s = S("\x01\xFF"), pb_dec_bytes(&s, &f, &d) && d.size == 1 && d.bytes[0] == 0xFF)) + TEST((s = S("\x05xxxxx"), pb_dec_bytes(&s, &f, &d) && d.size == 5)) + TEST((s = S("\x05xxxx"), !pb_dec_bytes(&s, &f, &d))) + + /* Note: the size limit on bytes-fields is not strictly obeyed, as + * the compiler may add some padding to the struct. Using this padding + * is not a very good thing to do, but it is difficult to avoid when + * we use only a single uint8_t to store the size of the field. + * Therefore this tests against a 10-byte string, while otherwise even + * 6 bytes should error out. + */ + TEST((s = S("\x10xxxxxxxxxx"), !pb_dec_bytes(&s, &f, &d))) + } + + { + pb_istream_t s; + pb_field_t f = {1, PB_LTYPE_STRING, 0, 0, 5, 0, 0}; + char d[5]; + + COMMENT("Test pb_dec_string") + TEST((s = S("\x00"), pb_dec_string(&s, &f, &d) && d[0] == '\0')) + TEST((s = S("\x04xyzz"), pb_dec_string(&s, &f, &d) && strcmp(d, "xyzz") == 0)) + TEST((s = S("\x05xyzzy"), !pb_dec_string(&s, &f, &d))) + } + + { + pb_istream_t s; + IntegerArray dest; + + COMMENT("Testing pb_decode with repeated int32 field") + TEST((s = S(""), pb_decode(&s, IntegerArray_fields, &dest) && dest.data_count == 0)) + TEST((s = S("\x08\x01\x08\x02"), pb_decode(&s, IntegerArray_fields, &dest) + && dest.data_count == 2 && dest.data[0] == 1 && dest.data[1] == 2)) + s = S("\x08\x01\x08\x02\x08\x03\x08\x04\x08\x05\x08\x06\x08\x07\x08\x08\x08\x09\x08\x0A"); + TEST(pb_decode(&s, IntegerArray_fields, &dest) && dest.data_count == 10 && dest.data[9] == 10) + s = S("\x08\x01\x08\x02\x08\x03\x08\x04\x08\x05\x08\x06\x08\x07\x08\x08\x08\x09\x08\x0A\x08\x0B"); + TEST(!pb_decode(&s, IntegerArray_fields, &dest)) + } + + { + pb_istream_t s; + IntegerArray dest; + + COMMENT("Testing pb_decode with packed int32 field") + TEST((s = S("\x0A\x00"), pb_decode(&s, IntegerArray_fields, &dest) + && dest.data_count == 0)) + TEST((s = S("\x0A\x01\x01"), pb_decode(&s, IntegerArray_fields, &dest) + && dest.data_count == 1 && dest.data[0] == 1)) + TEST((s = S("\x0A\x0A\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A"), pb_decode(&s, IntegerArray_fields, &dest) + && dest.data_count == 10 && dest.data[0] == 1 && dest.data[9] == 10)) + TEST((s = S("\x0A\x0B\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B"), !pb_decode(&s, IntegerArray_fields, &dest))) + + /* Test invalid wire data */ + TEST((s = S("\x0A\xFF"), !pb_decode(&s, IntegerArray_fields, &dest))) + TEST((s = S("\x0A\x01"), !pb_decode(&s, IntegerArray_fields, &dest))) + } + + { + pb_istream_t s; + IntegerArray dest; + + COMMENT("Testing pb_decode with unknown fields") + TEST((s = S("\x18\x0F\x08\x01"), pb_decode(&s, IntegerArray_fields, &dest) + && dest.data_count == 1 && dest.data[0] == 1)) + TEST((s = S("\x19\x00\x00\x00\x00\x00\x00\x00\x00\x08\x01"), pb_decode(&s, IntegerArray_fields, &dest) + && dest.data_count == 1 && dest.data[0] == 1)) + TEST((s = S("\x1A\x00\x08\x01"), pb_decode(&s, IntegerArray_fields, &dest) + && dest.data_count == 1 && dest.data[0] == 1)) + TEST((s = S("\x1B\x08\x01"), !pb_decode(&s, IntegerArray_fields, &dest))) + TEST((s = S("\x1D\x00\x00\x00\x00\x08\x01"), pb_decode(&s, IntegerArray_fields, &dest) + && dest.data_count == 1 && dest.data[0] == 1)) + } + + { + pb_istream_t s; + CallbackArray dest; + struct { pb_size_t size; uint8_t bytes[10]; } ref; + dest.data.funcs.decode = &callback_check; + dest.data.arg = &ref; + + COMMENT("Testing pb_decode with callbacks") + /* Single varint */ + ref.size = 1; ref.bytes[0] = 0x55; + TEST((s = S("\x08\x55"), pb_decode(&s, CallbackArray_fields, &dest))) + /* Packed varint */ + ref.size = 3; ref.bytes[0] = ref.bytes[1] = ref.bytes[2] = 0x55; + TEST((s = S("\x0A\x03\x55\x55\x55"), pb_decode(&s, CallbackArray_fields, &dest))) + /* Packed varint with loop */ + ref.size = 1; ref.bytes[0] = 0x55; + TEST((s = S("\x0A\x03\x55\x55\x55"), pb_decode(&s, CallbackArray_fields, &dest))) + /* Single fixed32 */ + ref.size = 4; ref.bytes[0] = ref.bytes[1] = ref.bytes[2] = ref.bytes[3] = 0xAA; + TEST((s = S("\x0D\xAA\xAA\xAA\xAA"), pb_decode(&s, CallbackArray_fields, &dest))) + /* Single fixed64 */ + ref.size = 8; memset(ref.bytes, 0xAA, 8); + TEST((s = S("\x09\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA"), pb_decode(&s, CallbackArray_fields, &dest))) + /* Unsupported field type */ + TEST((s = S("\x0B\x00"), !pb_decode(&s, CallbackArray_fields, &dest))) + + /* Just make sure that our test function works */ + ref.size = 1; ref.bytes[0] = 0x56; + TEST((s = S("\x08\x55"), !pb_decode(&s, CallbackArray_fields, &dest))) + } + + { + pb_istream_t s; + IntegerArray dest; + + COMMENT("Testing pb_decode message termination") + TEST((s = S(""), pb_decode(&s, IntegerArray_fields, &dest))) + TEST((s = S("\x00"), pb_decode(&s, IntegerArray_fields, &dest))) + TEST((s = S("\x08\x01"), pb_decode(&s, IntegerArray_fields, &dest))) + TEST((s = S("\x08\x01\x00"), pb_decode(&s, IntegerArray_fields, &dest))) + TEST((s = S("\x08"), !pb_decode(&s, IntegerArray_fields, &dest))) + } + + { + pb_istream_t s; + IntegerContainer dest = {{0}}; + + COMMENT("Testing pb_decode_delimited") + TEST((s = S("\x09\x0A\x07\x0A\x05\x01\x02\x03\x04\x05"), + pb_decode_delimited(&s, IntegerContainer_fields, &dest)) && + dest.submsg.data_count == 5) + } + + { + pb_istream_t s = {0}; + void *data = NULL; + + COMMENT("Testing allocate_field") + TEST(allocate_field(&s, &data, 10, 10) && data != NULL); + TEST(allocate_field(&s, &data, 10, 20) && data != NULL); + + { + void *oldvalue = data; + size_t very_big = (size_t)-1; + size_t somewhat_big = very_big / 2 + 1; + size_t not_so_big = (size_t)1 << (4 * sizeof(size_t)); + + TEST(!allocate_field(&s, &data, very_big, 2) && data == oldvalue); + TEST(!allocate_field(&s, &data, somewhat_big, 2) && data == oldvalue); + TEST(!allocate_field(&s, &data, not_so_big, not_so_big) && data == oldvalue); + } + + pb_free(data); + } + + if (status != 0) + fprintf(stdout, "\n\nSome tests FAILED!\n"); + + return status; +} diff --git a/libs/nanopb/tests/encode_unittests/SConscript b/libs/nanopb/tests/encode_unittests/SConscript new file mode 100644 index 00000000..bf6d1404 --- /dev/null +++ b/libs/nanopb/tests/encode_unittests/SConscript @@ -0,0 +1,5 @@ +# Build and run the stand-alone unit tests for the nanopb encoder part. + +Import('env') +p = env.Program(["encode_unittests.c", "$COMMON/unittestproto.pb.c"]) +env.RunTest(p) diff --git a/libs/nanopb/tests/encode_unittests/encode_unittests.c b/libs/nanopb/tests/encode_unittests/encode_unittests.c new file mode 100644 index 00000000..583af5c6 --- /dev/null +++ b/libs/nanopb/tests/encode_unittests/encode_unittests.c @@ -0,0 +1,355 @@ +/* This includes the whole .c file to get access to static functions. */ +#include "pb_common.c" +#include "pb_encode.c" + +#include +#include +#include "unittests.h" +#include "unittestproto.pb.h" + +bool streamcallback(pb_ostream_t *stream, const uint8_t *buf, size_t count) +{ + /* Allow only 'x' to be written */ + while (count--) + { + if (*buf++ != 'x') + return false; + } + return true; +} + +bool fieldcallback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + int value = 0x55; + if (!pb_encode_tag_for_field(stream, field)) + return false; + return pb_encode_varint(stream, value); +} + +bool crazyfieldcallback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + /* This callback writes different amount of data the second time. */ + uint32_t *state = (uint32_t*)arg; + *state <<= 8; + if (!pb_encode_tag_for_field(stream, field)) + return false; + return pb_encode_varint(stream, *state); +} + +/* Check that expression x writes data y. + * Y is a string, which may contain null bytes. Null terminator is ignored. + */ +#define WRITES(x, y) \ +memset(buffer, 0xAA, sizeof(buffer)), \ +s = pb_ostream_from_buffer(buffer, sizeof(buffer)), \ +(x) && \ +memcmp(buffer, y, sizeof(y) - 1) == 0 && \ +buffer[sizeof(y) - 1] == 0xAA + +int main() +{ + int status = 0; + + { + uint8_t buffer1[] = "foobartest1234"; + uint8_t buffer2[sizeof(buffer1)]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer2, sizeof(buffer1)); + + COMMENT("Test pb_write and pb_ostream_t"); + TEST(pb_write(&stream, buffer1, sizeof(buffer1))); + TEST(memcmp(buffer1, buffer2, sizeof(buffer1)) == 0); + TEST(!pb_write(&stream, buffer1, 1)); + TEST(stream.bytes_written == sizeof(buffer1)); + } + + { + uint8_t buffer1[] = "xxxxxxx"; + pb_ostream_t stream = {&streamcallback, 0, SIZE_MAX, 0}; + + COMMENT("Test pb_write with custom callback"); + TEST(pb_write(&stream, buffer1, 5)); + buffer1[0] = 'a'; + TEST(!pb_write(&stream, buffer1, 5)); + } + + { + uint8_t buffer[30]; + pb_ostream_t s; + + COMMENT("Test pb_encode_varint") + TEST(WRITES(pb_encode_varint(&s, 0), "\0")); + TEST(WRITES(pb_encode_varint(&s, 1), "\1")); + TEST(WRITES(pb_encode_varint(&s, 0x7F), "\x7F")); + TEST(WRITES(pb_encode_varint(&s, 0x80), "\x80\x01")); + TEST(WRITES(pb_encode_varint(&s, UINT32_MAX), "\xFF\xFF\xFF\xFF\x0F")); + TEST(WRITES(pb_encode_varint(&s, UINT64_MAX), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01")); + } + + { + uint8_t buffer[30]; + pb_ostream_t s; + + COMMENT("Test pb_encode_tag") + TEST(WRITES(pb_encode_tag(&s, PB_WT_STRING, 5), "\x2A")); + TEST(WRITES(pb_encode_tag(&s, PB_WT_VARINT, 99), "\x98\x06")); + } + + { + uint8_t buffer[30]; + pb_ostream_t s; + pb_field_t field = {10, PB_LTYPE_SVARINT}; + + COMMENT("Test pb_encode_tag_for_field") + TEST(WRITES(pb_encode_tag_for_field(&s, &field), "\x50")); + + field.type = PB_LTYPE_FIXED64; + TEST(WRITES(pb_encode_tag_for_field(&s, &field), "\x51")); + + field.type = PB_LTYPE_STRING; + TEST(WRITES(pb_encode_tag_for_field(&s, &field), "\x52")); + + field.type = PB_LTYPE_FIXED32; + TEST(WRITES(pb_encode_tag_for_field(&s, &field), "\x55")); + } + + { + uint8_t buffer[30]; + pb_ostream_t s; + + COMMENT("Test pb_encode_string") + TEST(WRITES(pb_encode_string(&s, (const uint8_t*)"abcd", 4), "\x04""abcd")); + TEST(WRITES(pb_encode_string(&s, (const uint8_t*)"abcd\x00", 5), "\x05""abcd\x00")); + TEST(WRITES(pb_encode_string(&s, (const uint8_t*)"", 0), "\x00")); + } + + { + uint8_t buffer[30]; + pb_ostream_t s; + uint8_t value = 1; + int32_t max = INT32_MAX; + int32_t min = INT32_MIN; + int64_t lmax = INT64_MAX; + int64_t lmin = INT64_MIN; + pb_field_t field = {1, PB_LTYPE_VARINT, 0, 0, sizeof(value)}; + + COMMENT("Test pb_enc_varint and pb_enc_svarint") + TEST(WRITES(pb_enc_varint(&s, &field, &value), "\x01")); + + field.data_size = sizeof(max); + TEST(WRITES(pb_enc_svarint(&s, &field, &max), "\xfe\xff\xff\xff\x0f")); + TEST(WRITES(pb_enc_svarint(&s, &field, &min), "\xff\xff\xff\xff\x0f")); + + field.data_size = sizeof(lmax); + TEST(WRITES(pb_enc_svarint(&s, &field, &lmax), "\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01")); + TEST(WRITES(pb_enc_svarint(&s, &field, &lmin), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01")); + } + + { + uint8_t buffer[30]; + pb_ostream_t s; + float fvalue; + double dvalue; + + COMMENT("Test pb_enc_fixed32 using float") + fvalue = 0.0f; + TEST(WRITES(pb_enc_fixed32(&s, NULL, &fvalue), "\x00\x00\x00\x00")) + fvalue = 99.0f; + TEST(WRITES(pb_enc_fixed32(&s, NULL, &fvalue), "\x00\x00\xc6\x42")) + fvalue = -12345678.0f; + TEST(WRITES(pb_enc_fixed32(&s, NULL, &fvalue), "\x4e\x61\x3c\xcb")) + + COMMENT("Test pb_enc_fixed64 using double") + dvalue = 0.0; + TEST(WRITES(pb_enc_fixed64(&s, NULL, &dvalue), "\x00\x00\x00\x00\x00\x00\x00\x00")) + dvalue = 99.0; + TEST(WRITES(pb_enc_fixed64(&s, NULL, &dvalue), "\x00\x00\x00\x00\x00\xc0\x58\x40")) + dvalue = -12345678.0; + TEST(WRITES(pb_enc_fixed64(&s, NULL, &dvalue), "\x00\x00\x00\xc0\x29\x8c\x67\xc1")) + } + + { + uint8_t buffer[30]; + pb_ostream_t s; + struct { pb_size_t size; uint8_t bytes[5]; } value = {5, {'x', 'y', 'z', 'z', 'y'}}; + + COMMENT("Test pb_enc_bytes") + TEST(WRITES(pb_enc_bytes(&s, &BytesMessage_fields[0], &value), "\x05xyzzy")) + value.size = 0; + TEST(WRITES(pb_enc_bytes(&s, &BytesMessage_fields[0], &value), "\x00")) + } + + { + uint8_t buffer[30]; + pb_ostream_t s; + char value[30] = "xyzzy"; + + COMMENT("Test pb_enc_string") + TEST(WRITES(pb_enc_string(&s, &StringMessage_fields[0], &value), "\x05xyzzy")) + value[0] = '\0'; + TEST(WRITES(pb_enc_string(&s, &StringMessage_fields[0], &value), "\x00")) + memset(value, 'x', 30); + TEST(WRITES(pb_enc_string(&s, &StringMessage_fields[0], &value), "\x0Axxxxxxxxxx")) + } + + { + uint8_t buffer[10]; + pb_ostream_t s; + IntegerArray msg = {5, {1, 2, 3, 4, 5}}; + + COMMENT("Test pb_encode with int32 array") + + TEST(WRITES(pb_encode(&s, IntegerArray_fields, &msg), "\x0A\x05\x01\x02\x03\x04\x05")) + + msg.data_count = 0; + TEST(WRITES(pb_encode(&s, IntegerArray_fields, &msg), "")) + + msg.data_count = 10; + TEST(!pb_encode(&s, IntegerArray_fields, &msg)) + } + + { + uint8_t buffer[10]; + pb_ostream_t s; + FloatArray msg = {1, {99.0f}}; + + COMMENT("Test pb_encode with float array") + + TEST(WRITES(pb_encode(&s, FloatArray_fields, &msg), + "\x0A\x04\x00\x00\xc6\x42")) + + msg.data_count = 0; + TEST(WRITES(pb_encode(&s, FloatArray_fields, &msg), "")) + + msg.data_count = 3; + TEST(!pb_encode(&s, FloatArray_fields, &msg)) + } + + { + uint8_t buffer[50]; + pb_ostream_t s; + FloatArray msg = {1, {99.0f}}; + + COMMENT("Test array size limit in pb_encode") + + s = pb_ostream_from_buffer(buffer, sizeof(buffer)); + TEST((msg.data_count = 10) && pb_encode(&s, FloatArray_fields, &msg)) + + s = pb_ostream_from_buffer(buffer, sizeof(buffer)); + TEST((msg.data_count = 11) && !pb_encode(&s, FloatArray_fields, &msg)) + } + + { + uint8_t buffer[10]; + pb_ostream_t s; + CallbackArray msg; + + msg.data.funcs.encode = &fieldcallback; + + COMMENT("Test pb_encode with callback field.") + TEST(WRITES(pb_encode(&s, CallbackArray_fields, &msg), "\x08\x55")) + } + + { + uint8_t buffer[10]; + pb_ostream_t s; + IntegerContainer msg = {{5, {1,2,3,4,5}}}; + + COMMENT("Test pb_encode with packed array in a submessage.") + TEST(WRITES(pb_encode(&s, IntegerContainer_fields, &msg), + "\x0A\x07\x0A\x05\x01\x02\x03\x04\x05")) + } + + { + uint8_t buffer[32]; + pb_ostream_t s; + BytesMessage msg = {{3, "xyz"}}; + + COMMENT("Test pb_encode with bytes message.") + TEST(WRITES(pb_encode(&s, BytesMessage_fields, &msg), + "\x0A\x03xyz")) + + msg.data.size = 17; /* More than maximum */ + TEST(!pb_encode(&s, BytesMessage_fields, &msg)) + } + + + { + uint8_t buffer[20]; + pb_ostream_t s; + IntegerContainer msg = {{5, {1,2,3,4,5}}}; + + COMMENT("Test pb_encode_delimited.") + TEST(WRITES(pb_encode_delimited(&s, IntegerContainer_fields, &msg), + "\x09\x0A\x07\x0A\x05\x01\x02\x03\x04\x05")) + } + + { + IntegerContainer msg = {{5, {1,2,3,4,5}}}; + size_t size; + + COMMENT("Test pb_get_encoded_size.") + TEST(pb_get_encoded_size(&size, IntegerContainer_fields, &msg) && + size == 9); + } + + { + uint8_t buffer[10]; + pb_ostream_t s; + CallbackContainer msg; + CallbackContainerContainer msg2; + uint32_t state = 1; + + msg.submsg.data.funcs.encode = &fieldcallback; + msg2.submsg.submsg.data.funcs.encode = &fieldcallback; + + COMMENT("Test pb_encode with callback field in a submessage.") + TEST(WRITES(pb_encode(&s, CallbackContainer_fields, &msg), "\x0A\x02\x08\x55")) + TEST(WRITES(pb_encode(&s, CallbackContainerContainer_fields, &msg2), + "\x0A\x04\x0A\x02\x08\x55")) + + /* Misbehaving callback: varying output between calls */ + msg.submsg.data.funcs.encode = &crazyfieldcallback; + msg.submsg.data.arg = &state; + msg2.submsg.submsg.data.funcs.encode = &crazyfieldcallback; + msg2.submsg.submsg.data.arg = &state; + + TEST(!pb_encode(&s, CallbackContainer_fields, &msg)) + state = 1; + TEST(!pb_encode(&s, CallbackContainerContainer_fields, &msg2)) + } + + { + uint8_t buffer[StringMessage_size]; + pb_ostream_t s; + StringMessage msg = {"0123456789"}; + + s = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + COMMENT("Test that StringMessage_size is correct") + + TEST(pb_encode(&s, StringMessage_fields, &msg)); + TEST(s.bytes_written == StringMessage_size); + } + + { + uint8_t buffer[128]; + pb_ostream_t s; + StringPointerContainer msg = StringPointerContainer_init_zero; + char *strs[1] = {NULL}; + char zstr[] = "Z"; + + COMMENT("Test string pointer encoding."); + + msg.rep_str = strs; + msg.rep_str_count = 1; + TEST(WRITES(pb_encode(&s, StringPointerContainer_fields, &msg), "\x0a\x00")) + + strs[0] = zstr; + TEST(WRITES(pb_encode(&s, StringPointerContainer_fields, &msg), "\x0a\x01Z")) + } + + if (status != 0) + fprintf(stdout, "\n\nSome tests FAILED!\n"); + + return status; +} diff --git a/libs/nanopb/tests/enum_sizes/SConscript b/libs/nanopb/tests/enum_sizes/SConscript new file mode 100644 index 00000000..048592ed --- /dev/null +++ b/libs/nanopb/tests/enum_sizes/SConscript @@ -0,0 +1,12 @@ +# Test that different sizes of enum fields are properly encoded and decoded. + +Import('env') + +env.NanopbProto('enumsizes') + +p = env.Program(["enumsizes_unittests.c", + "enumsizes.pb.c", + "$COMMON/pb_encode.o", + "$COMMON/pb_decode.o", + "$COMMON/pb_common.o"]) +env.RunTest(p) diff --git a/libs/nanopb/tests/enum_sizes/enumsizes.proto b/libs/nanopb/tests/enum_sizes/enumsizes.proto new file mode 100644 index 00000000..a85d4160 --- /dev/null +++ b/libs/nanopb/tests/enum_sizes/enumsizes.proto @@ -0,0 +1,86 @@ +/* Test handling of enums with different value ranges. + * Depending on compiler and the packed_enum setting, the datatypes + * for enums can be either signed or unsigned. In past this has caused + * a bit of a problem for the encoder/decoder (issue #164). + */ + +syntax = "proto2"; + +import 'nanopb.proto'; + +option (nanopb_fileopt).long_names = false; + +enum UnpackedUint8 { + option (nanopb_enumopt).packed_enum = false; + UU8_MIN = 0; + UU8_MAX = 255; +} + +enum PackedUint8 { + option (nanopb_enumopt).packed_enum = true; + PU8_MIN = 0; + PU8_MAX = 255; +} + +enum UnpackedInt8 { + option (nanopb_enumopt).packed_enum = false; + UI8_MIN = -128; + UI8_MAX = 127; +} + +enum PackedInt8 { + option (nanopb_enumopt).packed_enum = true; + PI8_MIN = -128; + PI8_MAX = 127; +} + +enum UnpackedUint16 { + option (nanopb_enumopt).packed_enum = false; + UU16_MIN = 0; + UU16_MAX = 65535; +} + +enum PackedUint16 { + option (nanopb_enumopt).packed_enum = true; + PU16_MIN = 0; + PU16_MAX = 65535; +} + +enum UnpackedInt16 { + option (nanopb_enumopt).packed_enum = false; + UI16_MIN = -32768; + UI16_MAX = 32767; +} + +enum PackedInt16 { + option (nanopb_enumopt).packed_enum = true; + PI16_MIN = -32768; + PI16_MAX = 32767; +} + +/* Protobuf supports enums up to 32 bits. + * The 32 bit case is covered by HugeEnum in the alltypes test. + */ + +message PackedEnums { + required PackedUint8 u8_min = 1; + required PackedUint8 u8_max = 2; + required PackedInt8 i8_min = 3; + required PackedInt8 i8_max = 4; + required PackedUint16 u16_min = 5; + required PackedUint16 u16_max = 6; + required PackedInt16 i16_min = 7; + required PackedInt16 i16_max = 8; +} + +message UnpackedEnums { + required UnpackedUint8 u8_min = 1; + required UnpackedUint8 u8_max = 2; + required UnpackedInt8 i8_min = 3; + required UnpackedInt8 i8_max = 4; + required UnpackedUint16 u16_min = 5; + required UnpackedUint16 u16_max = 6; + required UnpackedInt16 i16_min = 7; + required UnpackedInt16 i16_max = 8; +} + diff --git a/libs/nanopb/tests/enum_sizes/enumsizes_unittests.c b/libs/nanopb/tests/enum_sizes/enumsizes_unittests.c new file mode 100644 index 00000000..5606895a --- /dev/null +++ b/libs/nanopb/tests/enum_sizes/enumsizes_unittests.c @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include "unittests.h" +#include "enumsizes.pb.h" + +int main() +{ + int status = 0; + + UnpackedEnums msg1 = { + UU8_MIN, UU8_MAX, + UI8_MIN, UI8_MAX, + UU16_MIN, UU16_MAX, + UI16_MIN, UI16_MAX, + }; + + PackedEnums msg2; + UnpackedEnums msg3; + uint8_t buf[256]; + size_t msgsize; + + COMMENT("Step 1: unpacked enums -> protobuf"); + { + pb_ostream_t s = pb_ostream_from_buffer(buf, sizeof(buf)); + TEST(pb_encode(&s, UnpackedEnums_fields, &msg1)); + msgsize = s.bytes_written; + } + + COMMENT("Step 2: protobuf -> packed enums"); + { + pb_istream_t s = pb_istream_from_buffer(buf, msgsize); + TEST(pb_decode(&s, PackedEnums_fields, &msg2)); + + TEST(msg1.u8_min == (int)msg2.u8_min); + TEST(msg1.u8_max == (int)msg2.u8_max); + TEST(msg1.i8_min == (int)msg2.i8_min); + TEST(msg1.i8_max == (int)msg2.i8_max); + TEST(msg1.u16_min == (int)msg2.u16_min); + TEST(msg1.u16_max == (int)msg2.u16_max); + TEST(msg1.i16_min == (int)msg2.i16_min); + TEST(msg1.i16_max == (int)msg2.i16_max); + } + + COMMENT("Step 3: packed enums -> protobuf"); + { + pb_ostream_t s = pb_ostream_from_buffer(buf, sizeof(buf)); + TEST(pb_encode(&s, PackedEnums_fields, &msg2)); + msgsize = s.bytes_written; + } + + COMMENT("Step 4: protobuf -> unpacked enums"); + { + pb_istream_t s = pb_istream_from_buffer(buf, msgsize); + TEST(pb_decode(&s, UnpackedEnums_fields, &msg3)); + + TEST(msg1.u8_min == (int)msg3.u8_min); + TEST(msg1.u8_max == (int)msg3.u8_max); + TEST(msg1.i8_min == (int)msg3.i8_min); + TEST(msg1.i8_max == (int)msg3.i8_max); + TEST(msg1.u16_min == (int)msg2.u16_min); + TEST(msg1.u16_max == (int)msg2.u16_max); + TEST(msg1.i16_min == (int)msg2.i16_min); + TEST(msg1.i16_max == (int)msg2.i16_max); + } + + if (status != 0) + fprintf(stdout, "\n\nSome tests FAILED!\n"); + + return status; +} diff --git a/libs/nanopb/tests/enum_to_string/SConscript b/libs/nanopb/tests/enum_to_string/SConscript new file mode 100644 index 00000000..e86fcca0 --- /dev/null +++ b/libs/nanopb/tests/enum_to_string/SConscript @@ -0,0 +1,7 @@ +# Test enum to string functionality + +Import('env') +env.NanopbProto("enum.proto") +p = env.Program(["enum_to_string.c", "enum.pb.c"]) +env.RunTest(p) + diff --git a/libs/nanopb/tests/enum_to_string/enum.proto b/libs/nanopb/tests/enum_to_string/enum.proto new file mode 100644 index 00000000..07c67363 --- /dev/null +++ b/libs/nanopb/tests/enum_to_string/enum.proto @@ -0,0 +1,19 @@ +/* Test enum to string function generation */ + +syntax = "proto2"; + +import "nanopb.proto"; + +option (nanopb_fileopt).enum_to_string = true; + +enum MyEnum { + VALUE1 = 1; + VALUE2 = 2; + VALUE15 = 15; +} + +enum MyShortNameEnum { + option (nanopb_enumopt).long_names = false; + MSNE_VALUE256 = 256; +} + diff --git a/libs/nanopb/tests/enum_to_string/enum_to_string.c b/libs/nanopb/tests/enum_to_string/enum_to_string.c new file mode 100644 index 00000000..c4fb31d4 --- /dev/null +++ b/libs/nanopb/tests/enum_to_string/enum_to_string.c @@ -0,0 +1,19 @@ +#include +#include "unittests.h" +#include "enum.pb.h" + +int main() +{ + int status = 0; + TEST(strcmp(MyEnum_name(MyEnum_VALUE1), "VALUE1") == 0); + TEST(strcmp(MyEnum_name(MyEnum_VALUE2), "VALUE2") == 0); + TEST(strcmp(MyEnum_name(MyEnum_VALUE15), "VALUE15") == 0); + TEST(strcmp(MyShortNameEnum_name(MSNE_VALUE256), "MSNE_VALUE256") == 0); + TEST(strcmp(MyShortNameEnum_name(9999), "unknown") == 0); + + if (status != 0) + fprintf(stdout, "\n\nSome tests FAILED!\n"); + + return status; +} + diff --git a/libs/nanopb/tests/extensions/SConscript b/libs/nanopb/tests/extensions/SConscript new file mode 100644 index 00000000..a2c87428 --- /dev/null +++ b/libs/nanopb/tests/extensions/SConscript @@ -0,0 +1,16 @@ +# Test the support for extension fields. + +Import("env") + +# We use the files from the alltypes test case +incpath = env.Clone() +incpath.Append(PROTOCPATH = '$BUILD/alltypes') +incpath.Append(CPPPATH = '$BUILD/alltypes') + +incpath.NanopbProto(["extensions", "extensions.options"]) +enc = incpath.Program(["encode_extensions.c", "extensions.pb.c", "$BUILD/alltypes/alltypes.pb$OBJSUFFIX", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) +dec = incpath.Program(["decode_extensions.c", "extensions.pb.c", "$BUILD/alltypes/alltypes.pb$OBJSUFFIX", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) + +env.RunTest(enc) +env.RunTest([dec, "encode_extensions.output"]) + diff --git a/libs/nanopb/tests/extensions/decode_extensions.c b/libs/nanopb/tests/extensions/decode_extensions.c new file mode 100644 index 00000000..e4374380 --- /dev/null +++ b/libs/nanopb/tests/extensions/decode_extensions.c @@ -0,0 +1,60 @@ +/* Test decoding of extension fields. */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "extensions.pb.h" +#include "test_helpers.h" + +#define TEST(x) if (!(x)) { \ + printf("Test " #x " failed.\n"); \ + return 2; \ + } + +int main(int argc, char **argv) +{ + uint8_t buffer[1024]; + size_t count; + pb_istream_t stream; + + AllTypes alltypes = {0}; + int32_t extensionfield1; + pb_extension_t ext1; + ExtensionMessage extensionfield2; + pb_extension_t ext2; + + /* Read the message data */ + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + stream = pb_istream_from_buffer(buffer, count); + + /* Add the extensions */ + alltypes.extensions = &ext1; + + ext1.type = &AllTypes_extensionfield1; + ext1.dest = &extensionfield1; + ext1.next = &ext2; + + ext2.type = &ExtensionMessage_AllTypes_extensionfield2; + ext2.dest = &extensionfield2; + ext2.next = NULL; + + /* Decode the message */ + if (!pb_decode(&stream, AllTypes_fields, &alltypes)) + { + printf("Parsing failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } + + /* Check that the extensions decoded properly */ + TEST(ext1.found) + TEST(extensionfield1 == 12345) + TEST(ext2.found) + TEST(strcmp(extensionfield2.test1, "test") == 0) + TEST(extensionfield2.test2 == 54321) + + return 0; +} + diff --git a/libs/nanopb/tests/extensions/encode_extensions.c b/libs/nanopb/tests/extensions/encode_extensions.c new file mode 100644 index 00000000..00745826 --- /dev/null +++ b/libs/nanopb/tests/extensions/encode_extensions.c @@ -0,0 +1,54 @@ +/* Tests extension fields. + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "extensions.pb.h" +#include "test_helpers.h" + +int main(int argc, char **argv) +{ + uint8_t buffer[1024]; + pb_ostream_t stream; + + AllTypes alltypes = {0}; + int32_t extensionfield1 = 12345; + pb_extension_t ext1; + ExtensionMessage extensionfield2 = {"test", 54321}; + pb_extension_t ext2; + + /* Set up the extensions */ + alltypes.extensions = &ext1; + + ext1.type = &AllTypes_extensionfield1; + ext1.dest = &extensionfield1; + ext1.next = &ext2; + + ext2.type = &ExtensionMessage_AllTypes_extensionfield2; + ext2.dest = &extensionfield2; + ext2.next = NULL; + + /* Set up the output stream */ + stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Now encode the message and check if we succeeded. */ + if (pb_encode(&stream, AllTypes_fields, &alltypes)) + { + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; /* Success */ + } + else + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; /* Failure */ + } + + /* Check that the field tags are properly generated */ + (void)AllTypes_extensionfield1_tag; + (void)ExtensionMessage_AllTypes_extensionfield2_tag; +} + diff --git a/libs/nanopb/tests/extensions/extensions.options b/libs/nanopb/tests/extensions/extensions.options new file mode 100644 index 00000000..a5cd61dd --- /dev/null +++ b/libs/nanopb/tests/extensions/extensions.options @@ -0,0 +1 @@ +* max_size:16 diff --git a/libs/nanopb/tests/extensions/extensions.proto b/libs/nanopb/tests/extensions/extensions.proto new file mode 100644 index 00000000..fcd5b43b --- /dev/null +++ b/libs/nanopb/tests/extensions/extensions.proto @@ -0,0 +1,19 @@ +syntax = "proto2"; + +import 'alltypes.proto'; + +extend AllTypes { + optional int32 AllTypes_extensionfield1 = 255 [default = 5]; +} + +message ExtensionMessage { + extend AllTypes { + optional ExtensionMessage AllTypes_extensionfield2 = 254; + // required ExtensionMessage AllTypes_extensionfield3 = 253; // No longer allowed by protobuf 3 + repeated ExtensionMessage AllTypes_extensionfield4 = 252; + } + + required string test1 = 1; + required int32 test2 = 2; +} + diff --git a/libs/nanopb/tests/extra_fields/SConscript b/libs/nanopb/tests/extra_fields/SConscript new file mode 100644 index 00000000..75ac5c5e --- /dev/null +++ b/libs/nanopb/tests/extra_fields/SConscript @@ -0,0 +1,16 @@ +# Test that the decoder properly handles unknown fields in the input. + +Import("env") + +dec = env.GetBuildPath('$BUILD/basic_buffer/${PROGPREFIX}decode_buffer${PROGSUFFIX}') +env.RunTest('person_with_extra_field.output', [dec, "person_with_extra_field.pb"]) +env.Compare(["person_with_extra_field.output", "person_with_extra_field.expected"]) + +dec = env.GetBuildPath('$BUILD/basic_stream/${PROGPREFIX}decode_stream${PROGSUFFIX}') +env.RunTest('person_with_extra_field_stream.output', [dec, "person_with_extra_field.pb"]) +env.Compare(["person_with_extra_field_stream.output", "person_with_extra_field.expected"]) + +# This uses the backwards compatibility alltypes test, so that +# alltypes_with_extra_fields.pb doesn't have to be remade so often. +dec2 = env.GetBuildPath('$BUILD/backwards_compatibility/${PROGPREFIX}decode_legacy${PROGSUFFIX}') +env.RunTest('alltypes_with_extra_fields.output', [dec2, 'alltypes_with_extra_fields.pb']) diff --git a/libs/nanopb/tests/extra_fields/alltypes_with_extra_fields.pb b/libs/nanopb/tests/extra_fields/alltypes_with_extra_fields.pb new file mode 100644 index 00000000..f9f53941 Binary files /dev/null and b/libs/nanopb/tests/extra_fields/alltypes_with_extra_fields.pb differ diff --git a/libs/nanopb/tests/extra_fields/person_with_extra_field.expected b/libs/nanopb/tests/extra_fields/person_with_extra_field.expected new file mode 100644 index 00000000..da9c32df --- /dev/null +++ b/libs/nanopb/tests/extra_fields/person_with_extra_field.expected @@ -0,0 +1,14 @@ +name: "Test Person 99" +id: 99 +email: "test@person.com" +phone { + number: "555-12345678" + type: MOBILE +} +phone { + number: "99-2342" +} +phone { + number: "1234-5678" + type: WORK +} diff --git a/libs/nanopb/tests/extra_fields/person_with_extra_field.pb b/libs/nanopb/tests/extra_fields/person_with_extra_field.pb new file mode 100644 index 00000000..ffb303dd Binary files /dev/null and b/libs/nanopb/tests/extra_fields/person_with_extra_field.pb differ diff --git a/libs/nanopb/tests/field_size_16/SConscript b/libs/nanopb/tests/field_size_16/SConscript new file mode 100644 index 00000000..ffb29c4e --- /dev/null +++ b/libs/nanopb/tests/field_size_16/SConscript @@ -0,0 +1,29 @@ +# Run the alltypes test case, but compile with PB_FIELD_16BIT=1. +# Also the .proto file has been modified to have high indexes. + +Import("env") + +# Take copy of the files for custom build. +c = Copy("$TARGET", "$SOURCE") +env.Command("encode_alltypes.c", "$BUILD/alltypes/encode_alltypes.c", c) +env.Command("decode_alltypes.c", "$BUILD/alltypes/decode_alltypes.c", c) + +env.NanopbProto(["alltypes", "alltypes.options"]) + +# Define the compilation options +opts = env.Clone() +opts.Append(CPPDEFINES = {'PB_FIELD_16BIT': 1}) + +# Build new version of core +strict = opts.Clone() +strict.Append(CFLAGS = strict['CORECFLAGS']) +strict.Object("pb_decode_fields16.o", "$NANOPB/pb_decode.c") +strict.Object("pb_encode_fields16.o", "$NANOPB/pb_encode.c") +strict.Object("pb_common_fields16.o", "$NANOPB/pb_common.c") + +# Now build and run the test normally. +enc = opts.Program(["encode_alltypes.c", "alltypes.pb.c", "pb_encode_fields16.o", "pb_common_fields16.o"]) +dec = opts.Program(["decode_alltypes.c", "alltypes.pb.c", "pb_decode_fields16.o", "pb_common_fields16.o"]) + +env.RunTest(enc) +env.RunTest([dec, "encode_alltypes.output"]) diff --git a/libs/nanopb/tests/field_size_16/alltypes.options b/libs/nanopb/tests/field_size_16/alltypes.options new file mode 100644 index 00000000..78dd08d1 --- /dev/null +++ b/libs/nanopb/tests/field_size_16/alltypes.options @@ -0,0 +1,4 @@ +* max_size:16 +* max_count:5 +*.*fbytes fixed_length:true max_size:4 + diff --git a/libs/nanopb/tests/field_size_16/alltypes.proto b/libs/nanopb/tests/field_size_16/alltypes.proto new file mode 100644 index 00000000..46ac46af --- /dev/null +++ b/libs/nanopb/tests/field_size_16/alltypes.proto @@ -0,0 +1,123 @@ +syntax = "proto2"; + +message SubMessage { + required string substuff1 = 1 [default = "1"]; + required int32 substuff2 = 2 [default = 2]; + optional fixed32 substuff3 = 65535 [default = 3]; +} + +message EmptyMessage { + +} + +enum HugeEnum { + Negative = -2147483647; /* protoc doesn't accept -2147483648 here */ + Positive = 2147483647; +} + +message Limits { + required int32 int32_min = 1; + required int32 int32_max = 2; + required uint32 uint32_min = 3; + required uint32 uint32_max = 4; + required int64 int64_min = 5; + required int64 int64_max = 6; + required uint64 uint64_min = 7; + required uint64 uint64_max = 8; + required HugeEnum enum_min = 9; + required HugeEnum enum_max = 10; +} + +enum MyEnum { + Zero = 0; + First = 1; + Second = 2; + Truth = 42; +} + +message AllTypes { + required int32 req_int32 = 1; + required int64 req_int64 = 2; + required uint32 req_uint32 = 3; + required uint64 req_uint64 = 4; + required sint32 req_sint32 = 5; + required sint64 req_sint64 = 6; + required bool req_bool = 7; + + required fixed32 req_fixed32 = 8; + required sfixed32 req_sfixed32= 9; + required float req_float = 10; + + required fixed64 req_fixed64 = 11; + required sfixed64 req_sfixed64= 12; + required double req_double = 13; + + required string req_string = 14; + required bytes req_bytes = 15; + required SubMessage req_submsg = 16; + required MyEnum req_enum = 17; + required EmptyMessage req_emptymsg = 18; + required bytes req_fbytes = 19; + + repeated int32 rep_int32 = 21; + repeated int64 rep_int64 = 22; + repeated uint32 rep_uint32 = 23; + repeated uint64 rep_uint64 = 24; + repeated sint32 rep_sint32 = 25; + repeated sint64 rep_sint64 = 26; + repeated bool rep_bool = 27; + + repeated fixed32 rep_fixed32 = 28; + repeated sfixed32 rep_sfixed32= 29; + repeated float rep_float = 30; + + repeated fixed64 rep_fixed64 = 10031; + repeated sfixed64 rep_sfixed64= 10032; + repeated double rep_double = 10033; + + repeated string rep_string = 10034; + repeated bytes rep_bytes = 10035; + repeated SubMessage rep_submsg = 10036; + repeated MyEnum rep_enum = 10037; + repeated EmptyMessage rep_emptymsg = 10038; + repeated bytes rep_fbytes = 10039; + + optional int32 opt_int32 = 10041 [default = 4041]; + optional int64 opt_int64 = 10042 [default = 4042]; + optional uint32 opt_uint32 = 10043 [default = 4043]; + optional uint64 opt_uint64 = 10044 [default = 4044]; + optional sint32 opt_sint32 = 10045 [default = 4045]; + optional sint64 opt_sint64 = 10046 [default = 4046]; + optional bool opt_bool = 10047 [default = false]; + + optional fixed32 opt_fixed32 = 10048 [default = 4048]; + optional sfixed32 opt_sfixed32= 10049 [default = 4049]; + optional float opt_float = 10050 [default = 4050]; + + optional fixed64 opt_fixed64 = 10051 [default = 4051]; + optional sfixed64 opt_sfixed64= 10052 [default = 4052]; + optional double opt_double = 10053 [default = 4053]; + + optional string opt_string = 10054 [default = "4054"]; + optional bytes opt_bytes = 10055 [default = "4055"]; + optional SubMessage opt_submsg = 10056; + optional MyEnum opt_enum = 10057 [default = Second]; + optional EmptyMessage opt_emptymsg = 10058; + optional bytes opt_fbytes = 10059 [default = "4059"]; + + oneof oneof + { + SubMessage oneof_msg1 = 10060; + EmptyMessage oneof_msg2 = 10061; + } + + // Check that extreme integer values are handled correctly + required Limits req_limits = 98; + + // Just to make sure that the size of the fields has been calculated + // properly, i.e. otherwise a bug in last field might not be detected. + required int32 end = 10099; + + extensions 200 to 255; +} + diff --git a/libs/nanopb/tests/field_size_16_proto3/SConscript b/libs/nanopb/tests/field_size_16_proto3/SConscript new file mode 100644 index 00000000..912c0389 --- /dev/null +++ b/libs/nanopb/tests/field_size_16_proto3/SConscript @@ -0,0 +1,34 @@ +# Version of AllTypes test case for protobuf 3 file format. + +Import("env") + +import re +match = None +if 'PROTOC_VERSION' in env: + match = re.search('([0-9]+).([0-9]+).([0-9]+)', env['PROTOC_VERSION']) + +if match: + version = map(int, match.groups()) + +# proto3 syntax is supported by protoc >= 3.0.0 +if env.GetOption('clean') or (match and version[0] >= 3): + + env.NanopbProto(["alltypes", "alltypes.options"]) + + # Define the compilation options + opts = env.Clone() + opts.Append(CPPDEFINES = {'PB_FIELD_16BIT': 1}) + + # Build new version of core + strict = opts.Clone() + strict.Append(CFLAGS = strict['CORECFLAGS']) + strict.Object("pb_decode_fields16.o", "$NANOPB/pb_decode.c") + strict.Object("pb_encode_fields16.o", "$NANOPB/pb_encode.c") + strict.Object("pb_common_fields16.o", "$NANOPB/pb_common.c") + + # Now build and run the test normally. + enc = opts.Program(["encode_alltypes.c", "alltypes.pb.c", "pb_encode_fields16.o", "pb_common_fields16.o"]) + dec = opts.Program(["decode_alltypes.c", "alltypes.pb.c", "pb_decode_fields16.o", "pb_common_fields16.o"]) + + env.RunTest(enc) + env.RunTest([dec, "encode_alltypes.output"]) diff --git a/libs/nanopb/tests/field_size_16_proto3/alltypes.options b/libs/nanopb/tests/field_size_16_proto3/alltypes.options new file mode 100644 index 00000000..edfbe788 --- /dev/null +++ b/libs/nanopb/tests/field_size_16_proto3/alltypes.options @@ -0,0 +1,4 @@ +* max_size:16 +* max_count:5 +*.*fbytes fixed_length:true max_size:4 +SubMessage.substuff1 max_size:256 diff --git a/libs/nanopb/tests/field_size_16_proto3/alltypes.proto b/libs/nanopb/tests/field_size_16_proto3/alltypes.proto new file mode 100644 index 00000000..f66109ec --- /dev/null +++ b/libs/nanopb/tests/field_size_16_proto3/alltypes.proto @@ -0,0 +1,100 @@ +syntax = "proto3"; +// package name placeholder + +message SubMessage { + string substuff1 = 1; + int32 substuff2 = 2; + fixed32 substuff3 = 3; +} + +message EmptyMessage { + +} + +enum HugeEnum { + HE_Zero = 0; + Negative = -2147483647; /* protoc doesn't accept -2147483648 here */ + Positive = 2147483647; +} + +message Limits { + int32 int32_min = 1; + int32 int32_max = 2; + uint32 uint32_min = 3; + uint32 uint32_max = 4; + int64 int64_min = 5; + int64 int64_max = 6; + uint64 uint64_min = 7; + uint64 uint64_max = 8; + HugeEnum enum_min = 9; + HugeEnum enum_max = 10; +} + +enum MyEnum { + Zero = 0; + First = 1; + Second = 2; + Truth = 42; +} + +message AllTypes { + int32 sng_int32 = 1; + int64 sng_int64 = 2; + uint32 sng_uint32 = 3; + uint64 sng_uint64 = 4; + sint32 sng_sint32 = 5; + sint64 sng_sint64 = 6; + bool sng_bool = 7; + + fixed32 sng_fixed32 = 8; + sfixed32 sng_sfixed32= 9; + float sng_float = 10; + + fixed64 sng_fixed64 = 11; + sfixed64 sng_sfixed64= 12; + double sng_double = 13; + + string sng_string = 14; + bytes sng_bytes = 15; + SubMessage sng_submsg = 16; + MyEnum sng_enum = 17; + EmptyMessage sng_emptymsg = 18; + bytes sng_fbytes = 19; + + repeated int32 rep_int32 = 21 [packed = true]; + repeated int64 rep_int64 = 22 [packed = true]; + repeated uint32 rep_uint32 = 23 [packed = true]; + repeated uint64 rep_uint64 = 24 [packed = true]; + repeated sint32 rep_sint32 = 25 [packed = true]; + repeated sint64 rep_sint64 = 26 [packed = true]; + repeated bool rep_bool = 27 [packed = true]; + + repeated fixed32 rep_fixed32 = 28 [packed = true]; + repeated sfixed32 rep_sfixed32= 29 [packed = true]; + repeated float rep_float = 30 [packed = true]; + + repeated fixed64 rep_fixed64 = 31 [packed = true]; + repeated sfixed64 rep_sfixed64= 32 [packed = true]; + repeated double rep_double = 33 [packed = true]; + + repeated string rep_string = 34; + repeated bytes rep_bytes = 35; + repeated SubMessage rep_submsg = 36; + repeated MyEnum rep_enum = 37 [packed = true]; + repeated EmptyMessage rep_emptymsg = 38; + repeated bytes rep_fbytes = 39; + + oneof oneof + { + SubMessage oneof_msg1 = 59; + EmptyMessage oneof_msg2 = 60; + } + + // Check that extreme integer values are handled correctly + Limits req_limits = 98; + + // Just to make sure that the size of the fields has been calculated + // properly, i.e. otherwise a bug in last field might not be detected. + int32 end = 99; +} + diff --git a/libs/nanopb/tests/field_size_16_proto3/decode_alltypes.c b/libs/nanopb/tests/field_size_16_proto3/decode_alltypes.c new file mode 100644 index 00000000..6611f8cc --- /dev/null +++ b/libs/nanopb/tests/field_size_16_proto3/decode_alltypes.c @@ -0,0 +1,167 @@ +/* Tests the decoding of all types. + * This is the counterpart of test_encode3. + * Run e.g. ./test_encode3 | ./test_decode3 + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +#define TEST(x) if (!(x)) { \ + printf("Test " #x " failed.\n"); \ + return false; \ + } + +/* This function is called once from main(), it handles + the decoding and checks the fields. */ +bool check_alltypes(pb_istream_t *stream, int mode) +{ + AllTypes alltypes = AllTypes_init_zero; + + /* Fill with garbage to better detect initialization errors */ + memset(&alltypes, 0xAA, sizeof(alltypes)); + + if (!pb_decode(stream, AllTypes_fields, &alltypes)) + return false; + + TEST(alltypes.rep_int32_count == 5 && alltypes.rep_int32[4] == -2001 && alltypes.rep_int32[0] == 0); + TEST(alltypes.rep_int64_count == 5 && alltypes.rep_int64[4] == -2002 && alltypes.rep_int64[0] == 0); + TEST(alltypes.rep_uint32_count == 5 && alltypes.rep_uint32[4] == 2003 && alltypes.rep_uint32[0] == 0); + TEST(alltypes.rep_uint64_count == 5 && alltypes.rep_uint64[4] == 2004 && alltypes.rep_uint64[0] == 0); + TEST(alltypes.rep_sint32_count == 5 && alltypes.rep_sint32[4] == -2005 && alltypes.rep_sint32[0] == 0); + TEST(alltypes.rep_sint64_count == 5 && alltypes.rep_sint64[4] == -2006 && alltypes.rep_sint64[0] == 0); + TEST(alltypes.rep_bool_count == 5 && alltypes.rep_bool[4] == true && alltypes.rep_bool[0] == false); + + TEST(alltypes.rep_fixed32_count == 5 && alltypes.rep_fixed32[4] == 2008 && alltypes.rep_fixed32[0] == 0); + TEST(alltypes.rep_sfixed32_count == 5 && alltypes.rep_sfixed32[4] == -2009 && alltypes.rep_sfixed32[0] == 0); + TEST(alltypes.rep_float_count == 5 && alltypes.rep_float[4] == 2010.0f && alltypes.rep_float[0] == 0.0f); + + TEST(alltypes.rep_fixed64_count == 5 && alltypes.rep_fixed64[4] == 2011 && alltypes.rep_fixed64[0] == 0); + TEST(alltypes.rep_sfixed64_count == 5 && alltypes.rep_sfixed64[4] == -2012 && alltypes.rep_sfixed64[0] == 0); + TEST(alltypes.rep_double_count == 5 && alltypes.rep_double[4] == 2013.0 && alltypes.rep_double[0] == 0.0); + + TEST(alltypes.rep_string_count == 5 && strcmp(alltypes.rep_string[4], "2014") == 0 && alltypes.rep_string[0][0] == '\0'); + TEST(alltypes.rep_bytes_count == 5 && alltypes.rep_bytes[4].size == 4 && alltypes.rep_bytes[0].size == 0); + TEST(memcmp(alltypes.rep_bytes[4].bytes, "2015", 4) == 0); + + TEST(alltypes.rep_submsg_count == 5); + TEST(strcmp(alltypes.rep_submsg[4].substuff1, "2016") == 0 && alltypes.rep_submsg[0].substuff1[0] == '\0'); + TEST(alltypes.rep_submsg[4].substuff2 == 2016 && alltypes.rep_submsg[0].substuff2 == 0); + TEST(alltypes.rep_submsg[4].substuff3 == 2016 && alltypes.rep_submsg[0].substuff3 == 0); + + TEST(alltypes.rep_enum_count == 5 && alltypes.rep_enum[4] == MyEnum_Truth && alltypes.rep_enum[0] == MyEnum_Zero); + TEST(alltypes.rep_emptymsg_count == 5); + + TEST(alltypes.rep_fbytes_count == 5); + TEST(alltypes.rep_fbytes[0][0] == 0 && alltypes.rep_fbytes[0][3] == 0); + TEST(memcmp(alltypes.rep_fbytes[4], "2019", 4) == 0); + + if (mode == 0) + { + /* Expect default values */ + TEST(alltypes.sng_int32 == 0); + TEST(alltypes.sng_int64 == 0); + TEST(alltypes.sng_uint32 == 0); + TEST(alltypes.sng_uint64 == 0); + TEST(alltypes.sng_sint32 == 0); + TEST(alltypes.sng_sint64 == 0); + TEST(alltypes.sng_bool == false); + + TEST(alltypes.sng_fixed32 == 0); + TEST(alltypes.sng_sfixed32 == 0); + TEST(alltypes.sng_float == 0.0f); + + TEST(alltypes.sng_fixed64 == 0); + TEST(alltypes.sng_sfixed64 == 0); + TEST(alltypes.sng_double == 0.0); + + TEST(strcmp(alltypes.sng_string, "") == 0); + TEST(alltypes.sng_bytes.size == 0); + TEST(strcmp(alltypes.sng_submsg.substuff1, "") == 0); + TEST(alltypes.sng_submsg.substuff2 == 0); + TEST(alltypes.sng_submsg.substuff3 == 0); + TEST(alltypes.sng_enum == MyEnum_Zero); + TEST(alltypes.sng_fbytes[0] == 0 && + alltypes.sng_fbytes[1] == 0 && + alltypes.sng_fbytes[2] == 0 && + alltypes.sng_fbytes[3] == 0); + + TEST(alltypes.which_oneof == 0); + } + else + { + /* Expect filled-in values */ + TEST(alltypes.sng_int32 == 3041); + TEST(alltypes.sng_int64 == 3042); + TEST(alltypes.sng_uint32 == 3043); + TEST(alltypes.sng_uint64 == 3044); + TEST(alltypes.sng_sint32 == 3045); + TEST(alltypes.sng_sint64 == 3046); + TEST(alltypes.sng_bool == true); + + TEST(alltypes.sng_fixed32 == 3048); + TEST(alltypes.sng_sfixed32 == 3049); + TEST(alltypes.sng_float == 3050.0f); + + TEST(alltypes.sng_fixed64 == 3051); + TEST(alltypes.sng_sfixed64 == 3052); + TEST(alltypes.sng_double == 3053.0); + + TEST(strcmp(alltypes.sng_string, "3054") == 0); + TEST(alltypes.sng_bytes.size == 4); + TEST(memcmp(alltypes.sng_bytes.bytes, "3055", 4) == 0); + TEST(strcmp(alltypes.sng_submsg.substuff1, "3056") == 0); + TEST(alltypes.sng_submsg.substuff2 == 3056); + TEST(alltypes.sng_submsg.substuff3 == 0); + TEST(alltypes.sng_enum == MyEnum_Truth); + TEST(memcmp(alltypes.sng_fbytes, "3059", 4) == 0); + + TEST(alltypes.which_oneof == AllTypes_oneof_msg1_tag); + TEST(strcmp(alltypes.oneof.oneof_msg1.substuff1, "4059") == 0); + TEST(alltypes.oneof.oneof_msg1.substuff2 == 4059); + } + + TEST(alltypes.req_limits.int32_min == INT32_MIN); + TEST(alltypes.req_limits.int32_max == INT32_MAX); + TEST(alltypes.req_limits.uint32_min == 0); + TEST(alltypes.req_limits.uint32_max == UINT32_MAX); + TEST(alltypes.req_limits.int64_min == INT64_MIN); + TEST(alltypes.req_limits.int64_max == INT64_MAX); + TEST(alltypes.req_limits.uint64_min == 0); + TEST(alltypes.req_limits.uint64_max == UINT64_MAX); + TEST(alltypes.req_limits.enum_min == HugeEnum_Negative); + TEST(alltypes.req_limits.enum_max == HugeEnum_Positive); + + TEST(alltypes.end == 1099); + + return true; +} + +int main(int argc, char **argv) +{ + uint8_t buffer[2048]; + size_t count; + pb_istream_t stream; + + /* Whether to expect the optional values or the default values. */ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Read the data into buffer */ + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + + /* Construct a pb_istream_t for reading from the buffer */ + stream = pb_istream_from_buffer(buffer, count); + + /* Decode and print out the stuff */ + if (!check_alltypes(&stream, mode)) + { + printf("Parsing failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } else { + return 0; + } +} diff --git a/libs/nanopb/tests/field_size_16_proto3/encode_alltypes.c b/libs/nanopb/tests/field_size_16_proto3/encode_alltypes.c new file mode 100644 index 00000000..1da06688 --- /dev/null +++ b/libs/nanopb/tests/field_size_16_proto3/encode_alltypes.c @@ -0,0 +1,111 @@ +/* Attempts to test all the datatypes supported by ProtoBuf3. + */ + +#include +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +int main(int argc, char **argv) +{ + int mode = (argc > 1) ? atoi(argv[1]) : 0; + + /* Initialize the structure with constants */ + AllTypes alltypes = AllTypes_init_zero; + + alltypes.rep_int32_count = 5; alltypes.rep_int32[4] = -2001; + alltypes.rep_int64_count = 5; alltypes.rep_int64[4] = -2002; + alltypes.rep_uint32_count = 5; alltypes.rep_uint32[4] = 2003; + alltypes.rep_uint64_count = 5; alltypes.rep_uint64[4] = 2004; + alltypes.rep_sint32_count = 5; alltypes.rep_sint32[4] = -2005; + alltypes.rep_sint64_count = 5; alltypes.rep_sint64[4] = -2006; + alltypes.rep_bool_count = 5; alltypes.rep_bool[4] = true; + + alltypes.rep_fixed32_count = 5; alltypes.rep_fixed32[4] = 2008; + alltypes.rep_sfixed32_count = 5; alltypes.rep_sfixed32[4] = -2009; + alltypes.rep_float_count = 5; alltypes.rep_float[4] = 2010.0f; + + alltypes.rep_fixed64_count = 5; alltypes.rep_fixed64[4] = 2011; + alltypes.rep_sfixed64_count = 5; alltypes.rep_sfixed64[4] = -2012; + alltypes.rep_double_count = 5; alltypes.rep_double[4] = 2013.0; + + alltypes.rep_string_count = 5; strcpy(alltypes.rep_string[4], "2014"); + alltypes.rep_bytes_count = 5; alltypes.rep_bytes[4].size = 4; + memcpy(alltypes.rep_bytes[4].bytes, "2015", 4); + + alltypes.rep_submsg_count = 5; + strcpy(alltypes.rep_submsg[4].substuff1, "2016"); + alltypes.rep_submsg[4].substuff2 = 2016; + alltypes.rep_submsg[4].substuff3 = 2016; + + alltypes.rep_enum_count = 5; alltypes.rep_enum[4] = MyEnum_Truth; + alltypes.rep_emptymsg_count = 5; + + alltypes.rep_fbytes_count = 5; + memcpy(alltypes.rep_fbytes[4], "2019", 4); + + alltypes.req_limits.int32_min = INT32_MIN; + alltypes.req_limits.int32_max = INT32_MAX; + alltypes.req_limits.uint32_min = 0; + alltypes.req_limits.uint32_max = UINT32_MAX; + alltypes.req_limits.int64_min = INT64_MIN; + alltypes.req_limits.int64_max = INT64_MAX; + alltypes.req_limits.uint64_min = 0; + alltypes.req_limits.uint64_max = UINT64_MAX; + alltypes.req_limits.enum_min = HugeEnum_Negative; + alltypes.req_limits.enum_max = HugeEnum_Positive; + + if (mode != 0) + { + /* Fill in values for singular fields */ + alltypes.sng_int32 = 3041; + alltypes.sng_int64 = 3042; + alltypes.sng_uint32 = 3043; + alltypes.sng_uint64 = 3044; + alltypes.sng_sint32 = 3045; + alltypes.sng_sint64 = 3046; + alltypes.sng_bool = true; + + alltypes.sng_fixed32 = 3048; + alltypes.sng_sfixed32 = 3049; + alltypes.sng_float = 3050.0f; + + alltypes.sng_fixed64 = 3051; + alltypes.sng_sfixed64 = 3052; + alltypes.sng_double = 3053.0; + + strcpy(alltypes.sng_string, "3054"); + alltypes.sng_bytes.size = 4; + memcpy(alltypes.sng_bytes.bytes, "3055", 4); + strcpy(alltypes.sng_submsg.substuff1, "3056"); + alltypes.sng_submsg.substuff2 = 3056; + alltypes.sng_enum = MyEnum_Truth; + memcpy(alltypes.sng_fbytes, "3059", 4); + + alltypes.which_oneof = AllTypes_oneof_msg1_tag; + strcpy(alltypes.oneof.oneof_msg1.substuff1, "4059"); + alltypes.oneof.oneof_msg1.substuff2 = 4059; + } + + alltypes.end = 1099; + + { + uint8_t buffer[AllTypes_size]; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Now encode it and check if we succeeded. */ + if (pb_encode(&stream, AllTypes_fields, &alltypes)) + { + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; /* Success */ + } + else + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; /* Failure */ + } + } +} diff --git a/libs/nanopb/tests/field_size_32/SConscript b/libs/nanopb/tests/field_size_32/SConscript new file mode 100644 index 00000000..0b8dc0e3 --- /dev/null +++ b/libs/nanopb/tests/field_size_32/SConscript @@ -0,0 +1,29 @@ +# Run the alltypes test case, but compile with PB_FIELD_32BIT=1. +# Also the .proto file has been modified to have high indexes. + +Import("env") + +# Take copy of the files for custom build. +c = Copy("$TARGET", "$SOURCE") +env.Command("encode_alltypes.c", "$BUILD/alltypes/encode_alltypes.c", c) +env.Command("decode_alltypes.c", "$BUILD/alltypes/decode_alltypes.c", c) + +env.NanopbProto(["alltypes", "alltypes.options"]) + +# Define the compilation options +opts = env.Clone() +opts.Append(CPPDEFINES = {'PB_FIELD_32BIT': 1}) + +# Build new version of core +strict = opts.Clone() +strict.Append(CFLAGS = strict['CORECFLAGS']) +strict.Object("pb_decode_fields32.o", "$NANOPB/pb_decode.c") +strict.Object("pb_encode_fields32.o", "$NANOPB/pb_encode.c") +strict.Object("pb_common_fields32.o", "$NANOPB/pb_common.c") + +# Now build and run the test normally. +enc = opts.Program(["encode_alltypes.c", "alltypes.pb.c", "pb_encode_fields32.o", "pb_common_fields32.o"]) +dec = opts.Program(["decode_alltypes.c", "alltypes.pb.c", "pb_decode_fields32.o", "pb_common_fields32.o"]) + +env.RunTest(enc) +env.RunTest([dec, "encode_alltypes.output"]) diff --git a/libs/nanopb/tests/field_size_32/alltypes.options b/libs/nanopb/tests/field_size_32/alltypes.options new file mode 100644 index 00000000..0d5ab12b --- /dev/null +++ b/libs/nanopb/tests/field_size_32/alltypes.options @@ -0,0 +1,3 @@ +* max_size:16 +* max_count:5 +*.*fbytes fixed_length:true max_size:4 diff --git a/libs/nanopb/tests/field_size_32/alltypes.proto b/libs/nanopb/tests/field_size_32/alltypes.proto new file mode 100644 index 00000000..ac76c8ef --- /dev/null +++ b/libs/nanopb/tests/field_size_32/alltypes.proto @@ -0,0 +1,123 @@ +syntax = "proto2"; + +message SubMessage { + required string substuff1 = 1 [default = "1"]; + required int32 substuff2 = 2 [default = 2]; + optional fixed32 substuff3 = 12365535 [default = 3]; +} + +message EmptyMessage { + +} + +enum HugeEnum { + Negative = -2147483647; /* protoc doesn't accept -2147483648 here */ + Positive = 2147483647; +} + +message Limits { + required int32 int32_min = 1; + required int32 int32_max = 2; + required uint32 uint32_min = 3; + required uint32 uint32_max = 4; + required int64 int64_min = 5; + required int64 int64_max = 6; + required uint64 uint64_min = 7; + required uint64 uint64_max = 8; + required HugeEnum enum_min = 9; + required HugeEnum enum_max = 10; +} + +enum MyEnum { + Zero = 0; + First = 1; + Second = 2; + Truth = 42; +} + +message AllTypes { + required int32 req_int32 = 1; + required int64 req_int64 = 2; + required uint32 req_uint32 = 3; + required uint64 req_uint64 = 4; + required sint32 req_sint32 = 5; + required sint64 req_sint64 = 6; + required bool req_bool = 7; + + required fixed32 req_fixed32 = 8; + required sfixed32 req_sfixed32= 9; + required float req_float = 10; + + required fixed64 req_fixed64 = 11; + required sfixed64 req_sfixed64= 12; + required double req_double = 13; + + required string req_string = 14; + required bytes req_bytes = 15; + required SubMessage req_submsg = 16; + required MyEnum req_enum = 17; + required EmptyMessage req_emptymsg = 18; + required bytes req_fbytes = 19; + + repeated int32 rep_int32 = 21; + repeated int64 rep_int64 = 22; + repeated uint32 rep_uint32 = 23; + repeated uint64 rep_uint64 = 24; + repeated sint32 rep_sint32 = 25; + repeated sint64 rep_sint64 = 26; + repeated bool rep_bool = 27; + + repeated fixed32 rep_fixed32 = 28; + repeated sfixed32 rep_sfixed32= 29; + repeated float rep_float = 30; + + repeated fixed64 rep_fixed64 = 10031; + repeated sfixed64 rep_sfixed64= 10032; + repeated double rep_double = 10033; + + repeated string rep_string = 10034; + repeated bytes rep_bytes = 10035; + repeated SubMessage rep_submsg = 10036; + repeated MyEnum rep_enum = 10037; + repeated EmptyMessage rep_emptymsg = 10038; + repeated bytes rep_fbytes = 10039; + + optional int32 opt_int32 = 10041 [default = 4041]; + optional int64 opt_int64 = 10042 [default = 4042]; + optional uint32 opt_uint32 = 10043 [default = 4043]; + optional uint64 opt_uint64 = 10044 [default = 4044]; + optional sint32 opt_sint32 = 10045 [default = 4045]; + optional sint64 opt_sint64 = 10046 [default = 4046]; + optional bool opt_bool = 10047 [default = false]; + + optional fixed32 opt_fixed32 = 10048 [default = 4048]; + optional sfixed32 opt_sfixed32= 10049 [default = 4049]; + optional float opt_float = 10050 [default = 4050]; + + optional fixed64 opt_fixed64 = 10051 [default = 4051]; + optional sfixed64 opt_sfixed64= 10052 [default = 4052]; + optional double opt_double = 10053 [default = 4053]; + + optional string opt_string = 10054 [default = "4054"]; + optional bytes opt_bytes = 10055 [default = "4055"]; + optional SubMessage opt_submsg = 10056; + optional MyEnum opt_enum = 10057 [default = Second]; + optional EmptyMessage opt_emptymsg = 10058; + optional bytes opt_fbytes = 10059 [default = "4059"]; + + oneof oneof + { + SubMessage oneof_msg1 = 10060; + EmptyMessage oneof_msg2 = 10061; + } + + // Check that extreme integer values are handled correctly + required Limits req_limits = 98; + + // Just to make sure that the size of the fields has been calculated + // properly, i.e. otherwise a bug in last field might not be detected. + required int32 end = 13432099; + + extensions 200 to 255; +} + diff --git a/libs/nanopb/tests/fuzztest/SConscript b/libs/nanopb/tests/fuzztest/SConscript new file mode 100644 index 00000000..d2fb689c --- /dev/null +++ b/libs/nanopb/tests/fuzztest/SConscript @@ -0,0 +1,43 @@ +# Run a fuzz test to verify robustness against corrupted/malicious data. + +Import("env", "malloc_env") + +def set_pkgname(src, dst, pkgname): + data = open(str(src)).read() + placeholder = '// package name placeholder' + assert placeholder in data + data = data.replace(placeholder, 'package %s;' % pkgname) + open(str(dst), 'w').write(data) + +# We want both pointer and static versions of the AllTypes message +# Prefix them with package name. +env.Command("alltypes_static.proto", "#alltypes/alltypes.proto", + lambda target, source, env: set_pkgname(source[0], target[0], 'alltypes_static')) +env.Command("alltypes_pointer.proto", "#alltypes/alltypes.proto", + lambda target, source, env: set_pkgname(source[0], target[0], 'alltypes_pointer')) + +p1 = env.NanopbProto(["alltypes_pointer", "alltypes_pointer.options"]) +p2 = env.NanopbProto(["alltypes_static", "alltypes_static.options"]) +fuzz = malloc_env.Program(["fuzztest.c", + "alltypes_pointer.pb.c", + "alltypes_static.pb.c", + "$COMMON/pb_encode_with_malloc.o", + "$COMMON/pb_decode_with_malloc.o", + "$COMMON/pb_common_with_malloc.o", + "$COMMON/malloc_wrappers.o"]) + +env.RunTest(fuzz) + +fuzzstub = malloc_env.Program(["fuzzstub.c", + "alltypes_pointer.pb.c", + "alltypes_static.pb.c", + "$COMMON/pb_encode_with_malloc.o", + "$COMMON/pb_decode_with_malloc.o", + "$COMMON/pb_common_with_malloc.o", + "$COMMON/malloc_wrappers.o"]) + +generate_message = malloc_env.Program(["generate_message.c", + "alltypes_static.pb.c", + "$COMMON/pb_encode.o", + "$COMMON/pb_common.o"]) + diff --git a/libs/nanopb/tests/fuzztest/alltypes_pointer.options b/libs/nanopb/tests/fuzztest/alltypes_pointer.options new file mode 100644 index 00000000..7e3ad1e5 --- /dev/null +++ b/libs/nanopb/tests/fuzztest/alltypes_pointer.options @@ -0,0 +1,3 @@ +# Generate all fields as pointers. +* type:FT_POINTER +*.*fbytes fixed_length:true max_size:4 diff --git a/libs/nanopb/tests/fuzztest/alltypes_static.options b/libs/nanopb/tests/fuzztest/alltypes_static.options new file mode 100644 index 00000000..e197e1df --- /dev/null +++ b/libs/nanopb/tests/fuzztest/alltypes_static.options @@ -0,0 +1,4 @@ +* max_size:32 +* max_count:8 +*.extensions type:FT_IGNORE +*.*fbytes fixed_length:true max_size:4 diff --git a/libs/nanopb/tests/fuzztest/fuzzstub.c b/libs/nanopb/tests/fuzztest/fuzzstub.c new file mode 100644 index 00000000..ec9e2afe --- /dev/null +++ b/libs/nanopb/tests/fuzztest/fuzzstub.c @@ -0,0 +1,189 @@ +/* Fuzz testing for the nanopb core. + * This can be used with external fuzzers, e.g. radamsa. + * It performs most of the same checks as fuzztest, but does not feature data generation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "alltypes_static.pb.h" +#include "alltypes_pointer.pb.h" + +#define BUFSIZE 4096 + +static bool do_static_decode(uint8_t *buffer, size_t msglen, bool assert_success) +{ + pb_istream_t stream; + bool status; + + alltypes_static_AllTypes *msg = malloc_with_check(sizeof(alltypes_static_AllTypes)); + stream = pb_istream_from_buffer(buffer, msglen); + status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg); + + if (!status && assert_success) + { + /* Anything that was successfully encoded, should be decodeable. + * One exception: strings without null terminator are encoded up + * to end of buffer, but refused on decode because the terminator + * would not fit. */ + if (strcmp(stream.errmsg, "string overflow") != 0) + assert(status); + } + + free_with_check(msg); + return status; +} + +static bool do_pointer_decode(uint8_t *buffer, size_t msglen, bool assert_success) +{ + pb_istream_t stream; + bool status; + alltypes_pointer_AllTypes *msg; + + msg = malloc_with_check(sizeof(alltypes_pointer_AllTypes)); + memset(msg, 0, sizeof(alltypes_pointer_AllTypes)); + stream = pb_istream_from_buffer(buffer, msglen); + + assert(get_alloc_count() == 0); + status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg); + + if (assert_success) + assert(status); + + pb_release(alltypes_pointer_AllTypes_fields, msg); + assert(get_alloc_count() == 0); + + free_with_check(msg); + + return status; +} + +/* Do a decode -> encode -> decode -> encode roundtrip */ +static void do_static_roundtrip(uint8_t *buffer, size_t msglen) +{ + bool status; + uint8_t *buf2 = malloc_with_check(BUFSIZE); + uint8_t *buf3 = malloc_with_check(BUFSIZE); + size_t msglen2, msglen3; + alltypes_static_AllTypes *msg1 = malloc_with_check(sizeof(alltypes_static_AllTypes)); + alltypes_static_AllTypes *msg2 = malloc_with_check(sizeof(alltypes_static_AllTypes)); + memset(msg1, 0, sizeof(alltypes_static_AllTypes)); + memset(msg2, 0, sizeof(alltypes_static_AllTypes)); + + { + pb_istream_t stream = pb_istream_from_buffer(buffer, msglen); + status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg1); + assert(status); + } + + { + pb_ostream_t stream = pb_ostream_from_buffer(buf2, BUFSIZE); + status = pb_encode(&stream, alltypes_static_AllTypes_fields, msg1); + assert(status); + msglen2 = stream.bytes_written; + } + + { + pb_istream_t stream = pb_istream_from_buffer(buf2, msglen2); + status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg2); + assert(status); + } + + { + pb_ostream_t stream = pb_ostream_from_buffer(buf3, BUFSIZE); + status = pb_encode(&stream, alltypes_static_AllTypes_fields, msg2); + assert(status); + msglen3 = stream.bytes_written; + } + + assert(msglen2 == msglen3); + assert(memcmp(buf2, buf3, msglen2) == 0); + + free_with_check(msg1); + free_with_check(msg2); + free_with_check(buf2); + free_with_check(buf3); +} + +/* Do decode -> encode -> decode -> encode roundtrip */ +static void do_pointer_roundtrip(uint8_t *buffer, size_t msglen) +{ + bool status; + uint8_t *buf2 = malloc_with_check(BUFSIZE); + uint8_t *buf3 = malloc_with_check(BUFSIZE); + size_t msglen2, msglen3; + alltypes_pointer_AllTypes *msg1 = malloc_with_check(sizeof(alltypes_pointer_AllTypes)); + alltypes_pointer_AllTypes *msg2 = malloc_with_check(sizeof(alltypes_pointer_AllTypes)); + memset(msg1, 0, sizeof(alltypes_pointer_AllTypes)); + memset(msg2, 0, sizeof(alltypes_pointer_AllTypes)); + + { + pb_istream_t stream = pb_istream_from_buffer(buffer, msglen); + status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg1); + assert(status); + } + + { + pb_ostream_t stream = pb_ostream_from_buffer(buf2, BUFSIZE); + status = pb_encode(&stream, alltypes_pointer_AllTypes_fields, msg1); + assert(status); + msglen2 = stream.bytes_written; + } + + { + pb_istream_t stream = pb_istream_from_buffer(buf2, msglen2); + status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg2); + assert(status); + } + + { + pb_ostream_t stream = pb_ostream_from_buffer(buf3, BUFSIZE); + status = pb_encode(&stream, alltypes_pointer_AllTypes_fields, msg2); + assert(status); + msglen3 = stream.bytes_written; + } + + assert(msglen2 == msglen3); + assert(memcmp(buf2, buf3, msglen2) == 0); + + pb_release(alltypes_pointer_AllTypes_fields, msg1); + pb_release(alltypes_pointer_AllTypes_fields, msg2); + free_with_check(msg1); + free_with_check(msg2); + free_with_check(buf2); + free_with_check(buf3); +} + +static void run_iteration() +{ + uint8_t *buffer = malloc_with_check(BUFSIZE); + size_t msglen; + bool status; + + msglen = fread(buffer, 1, BUFSIZE, stdin); + + status = do_static_decode(buffer, msglen, false); + + if (status) + do_static_roundtrip(buffer, msglen); + + status = do_pointer_decode(buffer, msglen, false); + + if (status) + do_pointer_roundtrip(buffer, msglen); + + free_with_check(buffer); +} + +int main(int argc, char **argv) +{ + run_iteration(); + + return 0; +} + diff --git a/libs/nanopb/tests/fuzztest/fuzztest.c b/libs/nanopb/tests/fuzztest/fuzztest.c new file mode 100644 index 00000000..ee851ec0 --- /dev/null +++ b/libs/nanopb/tests/fuzztest/fuzztest.c @@ -0,0 +1,432 @@ +/* Fuzz testing for the nanopb core. + * Attempts to verify all the properties defined in the security model document. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "alltypes_static.pb.h" +#include "alltypes_pointer.pb.h" + +static uint64_t random_seed; + +/* Uses xorshift64 here instead of rand() for both speed and + * reproducibility across platforms. */ +static uint32_t rand_word() +{ + random_seed ^= random_seed >> 12; + random_seed ^= random_seed << 25; + random_seed ^= random_seed >> 27; + return random_seed * 2685821657736338717ULL; +} + +/* Get a random integer in range, with approximately flat distribution. */ +static int rand_int(int min, int max) +{ + return rand_word() % (max + 1 - min) + min; +} + +static bool rand_bool() +{ + return rand_word() & 1; +} + +/* Get a random byte, with skewed distribution. + * Important corner cases like 0xFF, 0x00 and 0xFE occur more + * often than other values. */ +static uint8_t rand_byte() +{ + uint32_t w = rand_word(); + uint8_t b = w & 0xFF; + if (w & 0x100000) + b >>= (w >> 8) & 7; + if (w & 0x200000) + b <<= (w >> 12) & 7; + if (w & 0x400000) + b ^= 0xFF; + return b; +} + +/* Get a random length, with skewed distribution. + * Favors the shorter lengths, but always atleast 1. */ +static size_t rand_len(size_t max) +{ + uint32_t w = rand_word(); + size_t s; + if (w & 0x800000) + w &= 3; + else if (w & 0x400000) + w &= 15; + else if (w & 0x200000) + w &= 255; + + s = (w % max); + if (s == 0) + s = 1; + + return s; +} + +/* Fills a buffer with random data with skewed distribution. */ +static void rand_fill(uint8_t *buf, size_t count) +{ + while (count--) + *buf++ = rand_byte(); +} + +/* Fill with random protobuf-like data */ +static size_t rand_fill_protobuf(uint8_t *buf, size_t min_bytes, size_t max_bytes, int min_tag) +{ + pb_ostream_t stream = pb_ostream_from_buffer(buf, max_bytes); + + while(stream.bytes_written < min_bytes) + { + pb_wire_type_t wt = rand_int(0, 3); + if (wt == 3) wt = 5; /* Gap in values */ + + if (!pb_encode_tag(&stream, wt, rand_int(min_tag, min_tag + 512))) + break; + + if (wt == PB_WT_VARINT) + { + uint64_t value; + rand_fill((uint8_t*)&value, sizeof(value)); + pb_encode_varint(&stream, value); + } + else if (wt == PB_WT_64BIT) + { + uint64_t value; + rand_fill((uint8_t*)&value, sizeof(value)); + pb_encode_fixed64(&stream, &value); + } + else if (wt == PB_WT_32BIT) + { + uint32_t value; + rand_fill((uint8_t*)&value, sizeof(value)); + pb_encode_fixed32(&stream, &value); + } + else if (wt == PB_WT_STRING) + { + size_t len; + uint8_t *buf; + + if (min_bytes > stream.bytes_written) + len = rand_len(min_bytes - stream.bytes_written); + else + len = 0; + + buf = malloc(len); + pb_encode_varint(&stream, len); + rand_fill(buf, len); + pb_write(&stream, buf, len); + free(buf); + } + } + + return stream.bytes_written; +} + +/* Given a buffer of data, mess it up a bit */ +static void rand_mess(uint8_t *buf, size_t count) +{ + int m = rand_int(0, 3); + + if (m == 0) + { + /* Replace random substring */ + int s = rand_int(0, count - 1); + int l = rand_len(count - s); + rand_fill(buf + s, l); + } + else if (m == 1) + { + /* Swap random bytes */ + int a = rand_int(0, count - 1); + int b = rand_int(0, count - 1); + int x = buf[a]; + buf[a] = buf[b]; + buf[b] = x; + } + else if (m == 2) + { + /* Duplicate substring */ + int s = rand_int(0, count - 2); + int l = rand_len((count - s) / 2); + memcpy(buf + s + l, buf + s, l); + } + else if (m == 3) + { + /* Add random protobuf noise */ + int s = rand_int(0, count - 1); + int l = rand_len(count - s); + rand_fill_protobuf(buf + s, l, count - s, 1); + } +} + +/* Some default data to put in the message */ +static const alltypes_static_AllTypes initval = alltypes_static_AllTypes_init_default; + +#define BUFSIZE 4096 + +static bool do_static_encode(uint8_t *buffer, size_t *msglen) +{ + pb_ostream_t stream; + bool status; + + /* Allocate a message and fill it with defaults */ + alltypes_static_AllTypes *msg = malloc_with_check(sizeof(alltypes_static_AllTypes)); + memcpy(msg, &initval, sizeof(initval)); + + /* Apply randomness to the data before encoding */ + while (rand_int(0, 7)) + rand_mess((uint8_t*)msg, sizeof(alltypes_static_AllTypes)); + + stream = pb_ostream_from_buffer(buffer, BUFSIZE); + status = pb_encode(&stream, alltypes_static_AllTypes_fields, msg); + assert(stream.bytes_written <= BUFSIZE); + assert(stream.bytes_written <= alltypes_static_AllTypes_size); + + *msglen = stream.bytes_written; + pb_release(alltypes_static_AllTypes_fields, msg); + free_with_check(msg); + + return status; +} + +/* Append or prepend protobuf noise */ +static void do_protobuf_noise(uint8_t *buffer, size_t *msglen) +{ + int m = rand_int(0, 2); + size_t max_size = BUFSIZE - 32 - *msglen; + if (m == 1) + { + /* Prepend */ + uint8_t *tmp = malloc_with_check(BUFSIZE); + size_t s = rand_fill_protobuf(tmp, rand_len(max_size), BUFSIZE - *msglen, 512); + memmove(buffer + s, buffer, *msglen); + memcpy(buffer, tmp, s); + free_with_check(tmp); + *msglen += s; + } + else if (m == 2) + { + /* Append */ + size_t s = rand_fill_protobuf(buffer + *msglen, rand_len(max_size), BUFSIZE - *msglen, 512); + *msglen += s; + } +} + +static bool do_static_decode(uint8_t *buffer, size_t msglen, bool assert_success) +{ + pb_istream_t stream; + bool status; + + alltypes_static_AllTypes *msg = malloc_with_check(sizeof(alltypes_static_AllTypes)); + rand_fill((uint8_t*)msg, sizeof(alltypes_static_AllTypes)); + stream = pb_istream_from_buffer(buffer, msglen); + status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg); + + if (!status && assert_success) + { + /* Anything that was successfully encoded, should be decodeable. + * One exception: strings without null terminator are encoded up + * to end of buffer, but refused on decode because the terminator + * would not fit. */ + if (strcmp(stream.errmsg, "string overflow") != 0) + assert(status); + } + + free_with_check(msg); + return status; +} + +static bool do_pointer_decode(uint8_t *buffer, size_t msglen, bool assert_success) +{ + pb_istream_t stream; + bool status; + alltypes_pointer_AllTypes *msg; + + msg = malloc_with_check(sizeof(alltypes_pointer_AllTypes)); + memset(msg, 0, sizeof(alltypes_pointer_AllTypes)); + stream = pb_istream_from_buffer(buffer, msglen); + + assert(get_alloc_count() == 0); + status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg); + + if (assert_success) + assert(status); + + pb_release(alltypes_pointer_AllTypes_fields, msg); + assert(get_alloc_count() == 0); + + free_with_check(msg); + + return status; +} + +/* Do a decode -> encode -> decode -> encode roundtrip */ +static void do_static_roundtrip(uint8_t *buffer, size_t msglen) +{ + bool status; + uint8_t *buf2 = malloc_with_check(BUFSIZE); + uint8_t *buf3 = malloc_with_check(BUFSIZE); + size_t msglen2, msglen3; + alltypes_static_AllTypes *msg1 = malloc_with_check(sizeof(alltypes_static_AllTypes)); + alltypes_static_AllTypes *msg2 = malloc_with_check(sizeof(alltypes_static_AllTypes)); + memset(msg1, 0, sizeof(alltypes_static_AllTypes)); + memset(msg2, 0, sizeof(alltypes_static_AllTypes)); + + { + pb_istream_t stream = pb_istream_from_buffer(buffer, msglen); + status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg1); + assert(status); + } + + { + pb_ostream_t stream = pb_ostream_from_buffer(buf2, BUFSIZE); + status = pb_encode(&stream, alltypes_static_AllTypes_fields, msg1); + assert(status); + msglen2 = stream.bytes_written; + } + + { + pb_istream_t stream = pb_istream_from_buffer(buf2, msglen2); + status = pb_decode(&stream, alltypes_static_AllTypes_fields, msg2); + assert(status); + } + + { + pb_ostream_t stream = pb_ostream_from_buffer(buf3, BUFSIZE); + status = pb_encode(&stream, alltypes_static_AllTypes_fields, msg2); + assert(status); + msglen3 = stream.bytes_written; + } + + assert(msglen2 == msglen3); + assert(memcmp(buf2, buf3, msglen2) == 0); + + free_with_check(msg1); + free_with_check(msg2); + free_with_check(buf2); + free_with_check(buf3); +} + +/* Do decode -> encode -> decode -> encode roundtrip */ +static void do_pointer_roundtrip(uint8_t *buffer, size_t msglen) +{ + bool status; + uint8_t *buf2 = malloc_with_check(BUFSIZE); + uint8_t *buf3 = malloc_with_check(BUFSIZE); + size_t msglen2, msglen3; + alltypes_pointer_AllTypes *msg1 = malloc_with_check(sizeof(alltypes_pointer_AllTypes)); + alltypes_pointer_AllTypes *msg2 = malloc_with_check(sizeof(alltypes_pointer_AllTypes)); + memset(msg1, 0, sizeof(alltypes_pointer_AllTypes)); + memset(msg2, 0, sizeof(alltypes_pointer_AllTypes)); + + { + pb_istream_t stream = pb_istream_from_buffer(buffer, msglen); + status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg1); + assert(status); + } + + { + pb_ostream_t stream = pb_ostream_from_buffer(buf2, BUFSIZE); + status = pb_encode(&stream, alltypes_pointer_AllTypes_fields, msg1); + assert(status); + msglen2 = stream.bytes_written; + } + + { + pb_istream_t stream = pb_istream_from_buffer(buf2, msglen2); + status = pb_decode(&stream, alltypes_pointer_AllTypes_fields, msg2); + assert(status); + } + + { + pb_ostream_t stream = pb_ostream_from_buffer(buf3, BUFSIZE); + status = pb_encode(&stream, alltypes_pointer_AllTypes_fields, msg2); + assert(status); + msglen3 = stream.bytes_written; + } + + assert(msglen2 == msglen3); + assert(memcmp(buf2, buf3, msglen2) == 0); + + pb_release(alltypes_pointer_AllTypes_fields, msg1); + pb_release(alltypes_pointer_AllTypes_fields, msg2); + free_with_check(msg1); + free_with_check(msg2); + free_with_check(buf2); + free_with_check(buf3); +} + +static void run_iteration() +{ + uint8_t *buffer = malloc_with_check(BUFSIZE); + size_t msglen; + bool status; + + rand_fill(buffer, BUFSIZE); + + if (do_static_encode(buffer, &msglen)) + { + do_protobuf_noise(buffer, &msglen); + + status = do_static_decode(buffer, msglen, true); + + if (status) + do_static_roundtrip(buffer, msglen); + + status = do_pointer_decode(buffer, msglen, true); + + if (status) + do_pointer_roundtrip(buffer, msglen); + + /* Apply randomness to the encoded data */ + while (rand_bool()) + rand_mess(buffer, BUFSIZE); + + /* Apply randomness to encoded data length */ + if (rand_bool()) + msglen = rand_int(0, BUFSIZE); + + status = do_static_decode(buffer, msglen, false); + do_pointer_decode(buffer, msglen, status); + + if (status) + { + do_static_roundtrip(buffer, msglen); + do_pointer_roundtrip(buffer, msglen); + } + } + + free_with_check(buffer); +} + +int main(int argc, char **argv) +{ + int i; + if (argc > 1) + { + random_seed = atol(argv[1]); + } + else + { + random_seed = time(NULL); + } + + fprintf(stderr, "Random seed: %llu\n", (long long unsigned)random_seed); + + for (i = 0; i < 10000; i++) + { + run_iteration(); + } + + return 0; +} + diff --git a/libs/nanopb/tests/fuzztest/generate_message.c b/libs/nanopb/tests/fuzztest/generate_message.c new file mode 100644 index 00000000..6e492990 --- /dev/null +++ b/libs/nanopb/tests/fuzztest/generate_message.c @@ -0,0 +1,101 @@ +/* Generates a random, valid protobuf message. Useful to seed + * external fuzzers such as afl-fuzz. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "alltypes_static.pb.h" + +static uint64_t random_seed; + +/* Uses xorshift64 here instead of rand() for both speed and + * reproducibility across platforms. */ +static uint32_t rand_word() +{ + random_seed ^= random_seed >> 12; + random_seed ^= random_seed << 25; + random_seed ^= random_seed >> 27; + return random_seed * 2685821657736338717ULL; +} + +/* Fills a buffer with random data. */ +static void rand_fill(uint8_t *buf, size_t count) +{ + while (count--) + { + *buf++ = rand_word() & 0xff; + } +} + +/* Check that size/count fields do not exceed their max size. + * Otherwise we would have to loop pretty long in generate_message(). + * Note that there may still be a few encoding errors from submessages. + */ +static void limit_sizes(alltypes_static_AllTypes *msg) +{ + pb_field_iter_t iter; + pb_field_iter_begin(&iter, alltypes_static_AllTypes_fields, msg); + while (pb_field_iter_next(&iter)) + { + if (PB_LTYPE(iter.pos->type) == PB_LTYPE_BYTES) + { + ((pb_bytes_array_t*)iter.pData)->size %= iter.pos->data_size - PB_BYTES_ARRAY_T_ALLOCSIZE(0); + } + + if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REPEATED) + { + *((pb_size_t*)iter.pSize) %= iter.pos->array_size; + } + + if (PB_HTYPE(iter.pos->type) == PB_HTYPE_ONEOF) + { + /* Set the oneof to this message type with 50% chance. */ + if (rand_word() & 1) + { + *((pb_size_t*)iter.pSize) = iter.pos->tag; + } + } + } +} + +static void generate_message() +{ + alltypes_static_AllTypes msg; + uint8_t buf[8192]; + pb_ostream_t stream = {0}; + + do { + if (stream.errmsg) + fprintf(stderr, "Encoder error: %s\n", stream.errmsg); + + stream = pb_ostream_from_buffer(buf, sizeof(buf)); + rand_fill((void*)&msg, sizeof(msg)); + limit_sizes(&msg); + } while (!pb_encode(&stream, alltypes_static_AllTypes_fields, &msg)); + + fwrite(buf, 1, stream.bytes_written, stdout); +} + +int main(int argc, char **argv) +{ + if (argc > 1) + { + random_seed = atol(argv[1]); + } + else + { + random_seed = time(NULL); + } + + fprintf(stderr, "Random seed: %llu\n", (long long unsigned)random_seed); + + generate_message(); + + return 0; +} + diff --git a/libs/nanopb/tests/fuzztest/run_radamsa.sh b/libs/nanopb/tests/fuzztest/run_radamsa.sh new file mode 100755 index 00000000..52cd40a8 --- /dev/null +++ b/libs/nanopb/tests/fuzztest/run_radamsa.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +TMP=`tempfile` + +echo $TMP +while true +do + radamsa sample_data/* > $TMP + $1 < $TMP + test $? -gt 127 && break +done + diff --git a/libs/nanopb/tests/fuzztest/sample_data/sample1.pb b/libs/nanopb/tests/fuzztest/sample_data/sample1.pb new file mode 100644 index 00000000..07527885 Binary files /dev/null and b/libs/nanopb/tests/fuzztest/sample_data/sample1.pb differ diff --git a/libs/nanopb/tests/fuzztest/sample_data/sample2.pb b/libs/nanopb/tests/fuzztest/sample_data/sample2.pb new file mode 100644 index 00000000..cc89f91b Binary files /dev/null and b/libs/nanopb/tests/fuzztest/sample_data/sample2.pb differ diff --git a/libs/nanopb/tests/inline/SConscript b/libs/nanopb/tests/inline/SConscript new file mode 100644 index 00000000..34371fda --- /dev/null +++ b/libs/nanopb/tests/inline/SConscript @@ -0,0 +1,16 @@ +# Test that inlined bytes fields work. + +Import("env") + +env.NanopbProto("inline") +env.Object("inline.pb.c") + +env.Match(["inline.pb.h", "inline.expected"]) + +p = env.Program(["inline_unittests.c", + "inline.pb.c", + "$COMMON/pb_encode.o", + "$COMMON/pb_decode.o", + "$COMMON/pb_common.o"]) + +env.RunTest(p) diff --git a/libs/nanopb/tests/inline/inline.expected b/libs/nanopb/tests/inline/inline.expected new file mode 100644 index 00000000..593e972b --- /dev/null +++ b/libs/nanopb/tests/inline/inline.expected @@ -0,0 +1,3 @@ +pb_byte_t data\[32\]; +bool has_data; +pb_byte_t data\[64\]; diff --git a/libs/nanopb/tests/inline/inline.proto b/libs/nanopb/tests/inline/inline.proto new file mode 100644 index 00000000..6e511f0a --- /dev/null +++ b/libs/nanopb/tests/inline/inline.proto @@ -0,0 +1,17 @@ +/* Test nanopb option parsing. + * options.expected lists the patterns that are searched for in the output. + */ + +syntax = "proto2"; + +import "nanopb.proto"; + +message Message1 +{ + required bytes data = 1 [(nanopb).type = FT_INLINE, (nanopb).max_size = 32]; +} + +message Message2 +{ + optional bytes data = 1 [(nanopb).type = FT_INLINE, (nanopb).max_size = 64]; +} diff --git a/libs/nanopb/tests/inline/inline_unittests.c b/libs/nanopb/tests/inline/inline_unittests.c new file mode 100644 index 00000000..b5834c7e --- /dev/null +++ b/libs/nanopb/tests/inline/inline_unittests.c @@ -0,0 +1,73 @@ +#include +#include +#include +#include +#include "unittests.h" +#include "inline.pb.h" + +int main() +{ + int status = 0; + int i = 0; + COMMENT("Test inline byte fields"); + + { + Message1 msg1 = Message1_init_zero; + TEST(sizeof(msg1.data) == 32); + } + + { + Message1 msg1 = Message1_init_zero; + pb_byte_t msg1_buffer[Message1_size]; + pb_ostream_t ostream = pb_ostream_from_buffer(msg1_buffer, Message1_size); + Message1 msg1_deserialized = Message1_init_zero; + pb_istream_t istream = pb_istream_from_buffer(msg1_buffer, Message1_size); + + for (i = 0; i < 32; i++) { + msg1.data[i] = i; + } + + TEST(pb_encode(&ostream, Message1_fields, &msg1)); + TEST(ostream.bytes_written == Message1_size); + + TEST(pb_decode(&istream, Message1_fields, &msg1_deserialized)); + + TEST(istream.bytes_left == 0); + TEST(memcmp(&msg1_deserialized, &msg1, sizeof(msg1)) == 0); + } + + { + Message2 msg2 = {true, {0}}; + Message2 msg2_no_data = {false, {1}}; + pb_byte_t msg2_buffer[Message2_size]; + pb_ostream_t ostream = pb_ostream_from_buffer(msg2_buffer, Message2_size); + Message2 msg2_deserialized = Message2_init_zero; + pb_istream_t istream = pb_istream_from_buffer(msg2_buffer, Message2_size); + + for (i = 0; i < 64; i++) { + msg2.data[i] = i; + } + + TEST(pb_encode(&ostream, Message2_fields, &msg2)); + TEST(ostream.bytes_written == Message2_size); + + TEST(pb_decode(&istream, Message2_fields, &msg2_deserialized)); + + TEST(istream.bytes_left == 0); + TEST(memcmp(&msg2_deserialized, &msg2, sizeof(msg2)) == 0); + TEST(msg2_deserialized.has_data); + + memset(msg2_buffer, 0, sizeof(msg2_buffer)); + ostream = pb_ostream_from_buffer(msg2_buffer, Message2_size); + TEST(pb_encode(&ostream, Message2_fields, &msg2_no_data)); + istream = pb_istream_from_buffer(msg2_buffer, Message2_size); + TEST(pb_decode(&istream, Message2_fields, &msg2_deserialized)); + TEST(!msg2_deserialized.has_data); + TEST(memcmp(&msg2_deserialized, &msg2, sizeof(msg2)) != 0); + } + + if (status != 0) + fprintf(stdout, "\n\nSome tests FAILED!\n"); + + return status; +} diff --git a/libs/nanopb/tests/intsizes/SConscript b/libs/nanopb/tests/intsizes/SConscript new file mode 100644 index 00000000..a90680bc --- /dev/null +++ b/libs/nanopb/tests/intsizes/SConscript @@ -0,0 +1,12 @@ +# Test that the int_size option in .proto works. + +Import('env') + +env.NanopbProto('intsizes') + +p = env.Program(["intsizes_unittests.c", + "intsizes.pb.c", + "$COMMON/pb_encode.o", + "$COMMON/pb_decode.o", + "$COMMON/pb_common.o"]) +env.RunTest(p) diff --git a/libs/nanopb/tests/intsizes/intsizes.proto b/libs/nanopb/tests/intsizes/intsizes.proto new file mode 100644 index 00000000..91444d41 --- /dev/null +++ b/libs/nanopb/tests/intsizes/intsizes.proto @@ -0,0 +1,41 @@ +/* Test the integer size overriding in nanopb options. + * This allows to use 8- and 16-bit integer variables, which are not supported + * directly by Google Protobuf. + * + * The int_size setting will override the number of bits, but keep the type + * otherwise. E.g. uint32 + IS_8 => uint8_t + */ + +syntax = "proto2"; + +import 'nanopb.proto'; + +message IntSizes { + required int32 req_int8 = 1 [(nanopb).int_size = IS_8]; + required uint32 req_uint8 = 2 [(nanopb).int_size = IS_8]; + required sint32 req_sint8 = 3 [(nanopb).int_size = IS_8]; + required int32 req_int16 = 4 [(nanopb).int_size = IS_16]; + required uint32 req_uint16 = 5 [(nanopb).int_size = IS_16]; + required sint32 req_sint16 = 6 [(nanopb).int_size = IS_16]; + required int32 req_int32 = 7 [(nanopb).int_size = IS_32]; + required uint32 req_uint32 = 8 [(nanopb).int_size = IS_32]; + required sint32 req_sint32 = 9 [(nanopb).int_size = IS_32]; + required int32 req_int64 = 10 [(nanopb).int_size = IS_64]; + required uint32 req_uint64 = 11 [(nanopb).int_size = IS_64]; + required sint32 req_sint64 = 12 [(nanopb).int_size = IS_64]; +} + +message DefaultSizes { + required int32 req_int8 = 1 ; + required uint32 req_uint8 = 2 ; + required sint32 req_sint8 = 3 ; + required int32 req_int16 = 4 ; + required uint32 req_uint16 = 5 ; + required sint32 req_sint16 = 6 ; + required int32 req_int32 = 7 ; + required uint32 req_uint32 = 8 ; + required sint32 req_sint32 = 9 ; + required int64 req_int64 = 10; + required uint64 req_uint64 = 11; + required sint64 req_sint64 = 12; +} diff --git a/libs/nanopb/tests/intsizes/intsizes_unittests.c b/libs/nanopb/tests/intsizes/intsizes_unittests.c new file mode 100644 index 00000000..79ef0369 --- /dev/null +++ b/libs/nanopb/tests/intsizes/intsizes_unittests.c @@ -0,0 +1,122 @@ +#include +#include +#include +#include +#include "unittests.h" +#include "intsizes.pb.h" + +#define S(x) pb_istream_from_buffer((uint8_t*)x, sizeof(x) - 1) + +/* This is a macro instead of function in order to get the actual values + * into the TEST() lines in output */ +#define TEST_ROUNDTRIP(int8, uint8, sint8, \ + int16, uint16, sint16, \ + int32, uint32, sint32, \ + int64, uint64, sint64, expected_result) \ +{ \ + uint8_t buffer1[128], buffer2[128]; \ + size_t msgsize; \ + DefaultSizes msg1 = DefaultSizes_init_zero; \ + IntSizes msg2 = IntSizes_init_zero; \ + \ + msg1.req_int8 = int8; \ + msg1.req_uint8 = uint8; \ + msg1.req_sint8 = sint8; \ + msg1.req_int16 = int16; \ + msg1.req_uint16 = uint16; \ + msg1.req_sint16 = sint16; \ + msg1.req_int32 = int32; \ + msg1.req_uint32 = uint32; \ + msg1.req_sint32 = sint32; \ + msg1.req_int64 = int64; \ + msg1.req_uint64 = uint64; \ + msg1.req_sint64 = sint64; \ + \ + { \ + pb_ostream_t s = pb_ostream_from_buffer(buffer1, sizeof(buffer1)); \ + TEST(pb_encode(&s, DefaultSizes_fields, &msg1)); \ + msgsize = s.bytes_written; \ + } \ + \ + { \ + pb_istream_t s = pb_istream_from_buffer(buffer1, msgsize); \ + TEST(pb_decode(&s, IntSizes_fields, &msg2) == expected_result); \ + if (expected_result) \ + { \ + TEST( (int64_t)msg2.req_int8 == int8); \ + TEST((uint64_t)msg2.req_uint8 == uint8); \ + TEST( (int64_t)msg2.req_sint8 == sint8); \ + TEST( (int64_t)msg2.req_int16 == int16); \ + TEST((uint64_t)msg2.req_uint16 == uint16); \ + TEST( (int64_t)msg2.req_sint16 == sint16); \ + TEST( (int64_t)msg2.req_int32 == int32); \ + TEST((uint64_t)msg2.req_uint32 == uint32); \ + TEST( (int64_t)msg2.req_sint32 == sint32); \ + TEST( (int64_t)msg2.req_int64 == int64); \ + TEST((uint64_t)msg2.req_uint64 == uint64); \ + TEST( (int64_t)msg2.req_sint64 == sint64); \ + } \ + } \ + \ + if (expected_result) \ + { \ + pb_ostream_t s = pb_ostream_from_buffer(buffer2, sizeof(buffer2)); \ + TEST(pb_encode(&s, IntSizes_fields, &msg2)); \ + TEST(s.bytes_written == msgsize); \ + TEST(memcmp(buffer1, buffer2, msgsize) == 0); \ + } \ +} + +int main() +{ + int status = 0; + + { + IntSizes msg = IntSizes_init_zero; + + COMMENT("Test field sizes"); + TEST(sizeof(msg.req_int8) == 1); + TEST(sizeof(msg.req_uint8) == 1); + TEST(sizeof(msg.req_sint8) == 1); + TEST(sizeof(msg.req_int16) == 2); + TEST(sizeof(msg.req_uint16) == 2); + TEST(sizeof(msg.req_sint16) == 2); + TEST(sizeof(msg.req_int32) == 4); + TEST(sizeof(msg.req_uint32) == 4); + TEST(sizeof(msg.req_sint32) == 4); + TEST(sizeof(msg.req_int64) == 8); + TEST(sizeof(msg.req_uint64) == 8); + TEST(sizeof(msg.req_sint64) == 8); + } + + COMMENT("Test roundtrip at maximum value"); + TEST_ROUNDTRIP(127, 255, 127, + 32767, 65535, 32767, + INT32_MAX, UINT32_MAX, INT32_MAX, + INT64_MAX, UINT64_MAX, INT64_MAX, true); + + COMMENT("Test roundtrip at minimum value"); + TEST_ROUNDTRIP(-128, 0, -128, + -32768, 0, -32768, + INT32_MIN, 0, INT32_MIN, + INT64_MIN, 0, INT64_MIN, true); + + COMMENT("Test overflow detection"); + TEST_ROUNDTRIP(-129, 0, -128, + -32768, 0, -32768, + INT32_MIN, 0, INT32_MIN, + INT64_MIN, 0, INT64_MIN, false); + TEST_ROUNDTRIP(127, 256, 127, + 32767, 65535, 32767, + INT32_MAX, UINT32_MAX, INT32_MAX, + INT64_MAX, UINT64_MAX, INT64_MAX, false); + TEST_ROUNDTRIP(-128, 0, -128, + -32768, 0, -32769, + INT32_MIN, 0, INT32_MIN, + INT64_MIN, 0, INT64_MIN, false); + + if (status != 0) + fprintf(stdout, "\n\nSome tests FAILED!\n"); + + return status; +} \ No newline at end of file diff --git a/libs/nanopb/tests/io_errors/SConscript b/libs/nanopb/tests/io_errors/SConscript new file mode 100644 index 00000000..60146cc0 --- /dev/null +++ b/libs/nanopb/tests/io_errors/SConscript @@ -0,0 +1,15 @@ +# Simulate io errors when encoding and decoding + +Import("env") + +c = Copy("$TARGET", "$SOURCE") +env.Command("alltypes.proto", "#alltypes/alltypes.proto", c) + +env.NanopbProto(["alltypes", "alltypes.options"]) + +ioerr = env.Program(["io_errors.c", "alltypes.pb.c", + "$COMMON/pb_encode.o", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) + +env.RunTest("io_errors.output", [ioerr, "$BUILD/alltypes/encode_alltypes.output"]) + + diff --git a/libs/nanopb/tests/io_errors/alltypes.options b/libs/nanopb/tests/io_errors/alltypes.options new file mode 100644 index 00000000..0d5ab12b --- /dev/null +++ b/libs/nanopb/tests/io_errors/alltypes.options @@ -0,0 +1,3 @@ +* max_size:16 +* max_count:5 +*.*fbytes fixed_length:true max_size:4 diff --git a/libs/nanopb/tests/io_errors/io_errors.c b/libs/nanopb/tests/io_errors/io_errors.c new file mode 100644 index 00000000..76f35b08 --- /dev/null +++ b/libs/nanopb/tests/io_errors/io_errors.c @@ -0,0 +1,140 @@ +/* Simulate IO errors after each byte in a stream. + * Verifies proper error propagation. + */ + +#include +#include +#include +#include "alltypes.pb.h" +#include "test_helpers.h" + +typedef struct +{ + uint8_t *buffer; + size_t fail_after; +} faulty_stream_t; + +bool read_callback(pb_istream_t *stream, uint8_t *buf, size_t count) +{ + faulty_stream_t *state = stream->state; + + while (count--) + { + if (state->fail_after == 0) + PB_RETURN_ERROR(stream, "simulated"); + state->fail_after--; + *buf++ = *state->buffer++; + } + + return true; +} +bool write_callback(pb_ostream_t *stream, const uint8_t *buf, size_t count) +{ + faulty_stream_t *state = stream->state; + + while (count--) + { + if (state->fail_after == 0) + PB_RETURN_ERROR(stream, "simulated"); + state->fail_after--; + *state->buffer++ = *buf++; + } + + return true; +} + +int main() +{ + uint8_t buffer[2048]; + size_t msglen; + AllTypes msg = AllTypes_init_zero; + + /* Get some base data to run the tests with */ + SET_BINARY_MODE(stdin); + msglen = fread(buffer, 1, sizeof(buffer), stdin); + + /* Test IO errors on decoding */ + { + bool status; + pb_istream_t stream = {&read_callback, NULL, SIZE_MAX}; + faulty_stream_t fs; + size_t i; + + for (i = 0; i < msglen; i++) + { + stream.bytes_left = msglen; + stream.state = &fs; + fs.buffer = buffer; + fs.fail_after = i; + + status = pb_decode(&stream, AllTypes_fields, &msg); + if (status != false) + { + fprintf(stderr, "Unexpected success in decode\n"); + return 2; + } + else if (strcmp(stream.errmsg, "simulated") != 0) + { + fprintf(stderr, "Wrong error in decode: %s\n", stream.errmsg); + return 3; + } + } + + stream.bytes_left = msglen; + stream.state = &fs; + fs.buffer = buffer; + fs.fail_after = msglen; + status = pb_decode(&stream, AllTypes_fields, &msg); + + if (!status) + { + fprintf(stderr, "Decoding failed: %s\n", stream.errmsg); + return 4; + } + } + + /* Test IO errors on encoding */ + { + bool status; + pb_ostream_t stream = {&write_callback, NULL, SIZE_MAX, 0}; + faulty_stream_t fs; + size_t i; + + for (i = 0; i < msglen; i++) + { + stream.max_size = msglen; + stream.bytes_written = 0; + stream.state = &fs; + fs.buffer = buffer; + fs.fail_after = i; + + status = pb_encode(&stream, AllTypes_fields, &msg); + if (status != false) + { + fprintf(stderr, "Unexpected success in encode\n"); + return 5; + } + else if (strcmp(stream.errmsg, "simulated") != 0) + { + fprintf(stderr, "Wrong error in encode: %s\n", stream.errmsg); + return 6; + } + } + + stream.max_size = msglen; + stream.bytes_written = 0; + stream.state = &fs; + fs.buffer = buffer; + fs.fail_after = msglen; + status = pb_encode(&stream, AllTypes_fields, &msg); + + if (!status) + { + fprintf(stderr, "Encoding failed: %s\n", stream.errmsg); + return 7; + } + } + + return 0; +} + diff --git a/libs/nanopb/tests/io_errors_pointers/SConscript b/libs/nanopb/tests/io_errors_pointers/SConscript new file mode 100644 index 00000000..03727df9 --- /dev/null +++ b/libs/nanopb/tests/io_errors_pointers/SConscript @@ -0,0 +1,26 @@ +# Simulate io errors when encoding and decoding + +Import("env", "malloc_env") + +c = Copy("$TARGET", "$SOURCE") +env.Command("alltypes.proto", "#alltypes/alltypes.proto", c) +env.Command("io_errors.c", "#io_errors/io_errors.c", c) + +env.NanopbProto(["alltypes", "alltypes.options"]) + +ioerr = env.Program(["io_errors.c", "alltypes.pb.c", + "$COMMON/pb_encode_with_malloc.o", + "$COMMON/pb_decode_with_malloc.o", + "$COMMON/pb_common_with_malloc.o", + "$COMMON/malloc_wrappers.o"]) + +# Run tests under valgrind if available +valgrind = env.WhereIs('valgrind') +kwargs = {} +if valgrind: + kwargs['COMMAND'] = valgrind + kwargs['ARGS'] = ["-q", "--error-exitcode=99", ioerr[0].abspath] + +env.RunTest("io_errors.output", [ioerr, "$BUILD/alltypes/encode_alltypes.output"], **kwargs) + + diff --git a/libs/nanopb/tests/io_errors_pointers/alltypes.options b/libs/nanopb/tests/io_errors_pointers/alltypes.options new file mode 100644 index 00000000..7e3ad1e5 --- /dev/null +++ b/libs/nanopb/tests/io_errors_pointers/alltypes.options @@ -0,0 +1,3 @@ +# Generate all fields as pointers. +* type:FT_POINTER +*.*fbytes fixed_length:true max_size:4 diff --git a/libs/nanopb/tests/mem_release/SConscript b/libs/nanopb/tests/mem_release/SConscript new file mode 100644 index 00000000..6754e285 --- /dev/null +++ b/libs/nanopb/tests/mem_release/SConscript @@ -0,0 +1,13 @@ +Import("env", "malloc_env") + +env.NanopbProto("mem_release.proto") + +test = malloc_env.Program(["mem_release.c", + "mem_release.pb.c", + "$COMMON/pb_encode_with_malloc.o", + "$COMMON/pb_decode_with_malloc.o", + "$COMMON/pb_common_with_malloc.o", + "$COMMON/malloc_wrappers.o"]) + +env.RunTest(test) + diff --git a/libs/nanopb/tests/mem_release/mem_release.c b/libs/nanopb/tests/mem_release/mem_release.c new file mode 100644 index 00000000..dc6f87de --- /dev/null +++ b/libs/nanopb/tests/mem_release/mem_release.c @@ -0,0 +1,187 @@ +/* Make sure that all fields are freed in various scenarios. */ + +#include +#include +#include +#include +#include +#include "mem_release.pb.h" + +#define TEST(x) if (!(x)) { \ + fprintf(stderr, "Test " #x " on line %d failed.\n", __LINE__); \ + return false; \ + } + +static char *test_str_arr[] = {"1", "2", ""}; +static SubMessage test_msg_arr[] = {SubMessage_init_zero, SubMessage_init_zero}; +static pb_extension_t ext1, ext2; + +static void fill_TestMessage(TestMessage *msg) +{ + msg->static_req_submsg.dynamic_str = "12345"; + msg->static_req_submsg.dynamic_str_arr_count = 3; + msg->static_req_submsg.dynamic_str_arr = test_str_arr; + msg->static_req_submsg.dynamic_submsg_count = 2; + msg->static_req_submsg.dynamic_submsg = test_msg_arr; + msg->static_req_submsg.dynamic_submsg[1].dynamic_str = "abc"; + msg->static_opt_submsg.dynamic_str = "abc"; + msg->static_rep_submsg_count = 2; + msg->static_rep_submsg[1].dynamic_str = "abc"; + msg->has_static_opt_submsg = true; + msg->dynamic_submsg = &msg->static_req_submsg; + + msg->extensions = &ext1; + ext1.type = &dynamic_ext; + ext1.dest = &msg->static_req_submsg; + ext1.next = &ext2; + ext2.type = &static_ext; + ext2.dest = &msg->static_req_submsg; + ext2.next = NULL; +} + +/* Basic fields, nested submessages, extensions */ +static bool test_TestMessage() +{ + uint8_t buffer[256]; + size_t msgsize; + + /* Construct a message with various fields filled in */ + { + TestMessage msg = TestMessage_init_zero; + pb_ostream_t stream; + + fill_TestMessage(&msg); + + stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + if (!pb_encode(&stream, TestMessage_fields, &msg)) + { + fprintf(stderr, "Encode failed: %s\n", PB_GET_ERROR(&stream)); + return false; + } + msgsize = stream.bytes_written; + } + + /* Output encoded message for debug */ + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, msgsize, stdout); + + /* Decode memory using dynamic allocation */ + { + TestMessage msg = TestMessage_init_zero; + pb_istream_t stream; + SubMessage ext2_dest; + + msg.extensions = &ext1; + ext1.type = &dynamic_ext; + ext1.dest = NULL; + ext1.next = &ext2; + ext2.type = &static_ext; + ext2.dest = &ext2_dest; + ext2.next = NULL; + + stream = pb_istream_from_buffer(buffer, msgsize); + if (!pb_decode(&stream, TestMessage_fields, &msg)) + { + fprintf(stderr, "Decode failed: %s\n", PB_GET_ERROR(&stream)); + return false; + } + + /* Make sure it encodes back to same data */ + { + uint8_t buffer2[256]; + pb_ostream_t ostream = pb_ostream_from_buffer(buffer2, sizeof(buffer2)); + TEST(pb_encode(&ostream, TestMessage_fields, &msg)); + TEST(ostream.bytes_written == msgsize); + TEST(memcmp(buffer, buffer2, msgsize) == 0); + } + + /* Make sure that malloc counters work */ + TEST(get_alloc_count() > 0); + + /* Make sure that pb_release releases everything */ + pb_release(TestMessage_fields, &msg); + TEST(get_alloc_count() == 0); + + /* Check that double-free is a no-op */ + pb_release(TestMessage_fields, &msg); + TEST(get_alloc_count() == 0); + } + + return true; +} + +/* Oneofs */ +static bool test_OneofMessage() +{ + uint8_t buffer[256]; + size_t msgsize; + + { + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + /* Encode first with TestMessage */ + { + OneofMessage msg = OneofMessage_init_zero; + msg.which_msgs = OneofMessage_msg1_tag; + + fill_TestMessage(&msg.msgs.msg1); + + if (!pb_encode(&stream, OneofMessage_fields, &msg)) + { + fprintf(stderr, "Encode failed: %s\n", PB_GET_ERROR(&stream)); + return false; + } + } + + /* Encode second with SubMessage, invoking 'merge' behaviour */ + { + OneofMessage msg = OneofMessage_init_zero; + msg.which_msgs = OneofMessage_msg2_tag; + + msg.first = 999; + msg.msgs.msg2.dynamic_str = "ABCD"; + msg.last = 888; + + if (!pb_encode(&stream, OneofMessage_fields, &msg)) + { + fprintf(stderr, "Encode failed: %s\n", PB_GET_ERROR(&stream)); + return false; + } + } + msgsize = stream.bytes_written; + } + + { + OneofMessage msg = OneofMessage_init_zero; + pb_istream_t stream = pb_istream_from_buffer(buffer, msgsize); + if (!pb_decode(&stream, OneofMessage_fields, &msg)) + { + fprintf(stderr, "Decode failed: %s\n", PB_GET_ERROR(&stream)); + return false; + } + + TEST(msg.first == 999); + TEST(msg.which_msgs == OneofMessage_msg2_tag); + TEST(msg.msgs.msg2.dynamic_str); + TEST(strcmp(msg.msgs.msg2.dynamic_str, "ABCD") == 0); + TEST(msg.msgs.msg2.dynamic_str_arr == NULL); + TEST(msg.msgs.msg2.dynamic_submsg == NULL); + TEST(msg.last == 888); + + pb_release(OneofMessage_fields, &msg); + TEST(get_alloc_count() == 0); + pb_release(OneofMessage_fields, &msg); + TEST(get_alloc_count() == 0); + } + + return true; +} + +int main() +{ + if (test_TestMessage() && test_OneofMessage()) + return 0; + else + return 1; +} + diff --git a/libs/nanopb/tests/mem_release/mem_release.proto b/libs/nanopb/tests/mem_release/mem_release.proto new file mode 100644 index 00000000..0816dc22 --- /dev/null +++ b/libs/nanopb/tests/mem_release/mem_release.proto @@ -0,0 +1,35 @@ +syntax = "proto2"; +import "nanopb.proto"; + +message SubMessage +{ + optional string dynamic_str = 1 [(nanopb).type = FT_POINTER]; + repeated string dynamic_str_arr = 2 [(nanopb).type = FT_POINTER]; + repeated SubMessage dynamic_submsg = 3 [(nanopb).type = FT_POINTER]; +} + +message TestMessage +{ + required SubMessage static_req_submsg = 1 [(nanopb).type = FT_STATIC]; + optional SubMessage dynamic_submsg = 2 [(nanopb).type = FT_POINTER]; + optional SubMessage static_opt_submsg = 3 [(nanopb).type = FT_STATIC]; + repeated SubMessage static_rep_submsg = 4 [(nanopb).type = FT_STATIC, (nanopb).max_count=2]; + extensions 100 to 200; +} + +extend TestMessage +{ + optional SubMessage dynamic_ext = 100 [(nanopb).type = FT_POINTER]; + optional SubMessage static_ext = 101 [(nanopb).type = FT_STATIC]; +} + +message OneofMessage +{ + required int32 first = 1; + oneof msgs + { + TestMessage msg1 = 2; + SubMessage msg2 = 3; + } + required int32 last = 4; +} diff --git a/libs/nanopb/tests/message_sizes/SConscript b/libs/nanopb/tests/message_sizes/SConscript new file mode 100644 index 00000000..e7524e02 --- /dev/null +++ b/libs/nanopb/tests/message_sizes/SConscript @@ -0,0 +1,11 @@ +# Test the generation of message size #defines + +Import('env') + +incpath = env.Clone() +incpath.Append(PROTOCPATH = '#message_sizes') + +incpath.NanopbProto("messages1") +incpath.NanopbProto("messages2") + +incpath.Program(['dummy.c', 'messages1.pb.c', 'messages2.pb.c']) diff --git a/libs/nanopb/tests/message_sizes/dummy.c b/libs/nanopb/tests/message_sizes/dummy.c new file mode 100644 index 00000000..767ad463 --- /dev/null +++ b/libs/nanopb/tests/message_sizes/dummy.c @@ -0,0 +1,9 @@ +/* Just test that the file can be compiled successfully. */ + +#include "messages2.pb.h" + +int main() +{ + return xmit_size; +} + diff --git a/libs/nanopb/tests/message_sizes/messages1.proto b/libs/nanopb/tests/message_sizes/messages1.proto new file mode 100644 index 00000000..b66fad71 --- /dev/null +++ b/libs/nanopb/tests/message_sizes/messages1.proto @@ -0,0 +1,29 @@ +syntax = "proto2"; + +enum MessageStatus { + FAIL = 0; + OK = 1; +}; + +message MessageInfo { + required fixed32 msg_id = 1; + optional fixed32 interface_id = 2; +} + +message MessageResponseInfo { + required fixed64 interface_id = 1; + required fixed32 seq = 2; + required fixed32 msg_id = 3; +} + +message MessageHeader { + required MessageInfo info = 1; + optional MessageResponseInfo response_info = 2; + optional MessageResponse response = 3; +} + +message MessageResponse { + required MessageStatus status = 1; + required fixed32 seq = 2; +} + diff --git a/libs/nanopb/tests/message_sizes/messages2.proto b/libs/nanopb/tests/message_sizes/messages2.proto new file mode 100644 index 00000000..67614080 --- /dev/null +++ b/libs/nanopb/tests/message_sizes/messages2.proto @@ -0,0 +1,10 @@ +syntax = "proto2"; + +import 'nanopb.proto'; +import 'messages1.proto'; + +message xmit { + required MessageHeader header = 1; + required bytes data = 2 [(nanopb).max_size = 128]; +} + diff --git a/libs/nanopb/tests/missing_fields/SConscript b/libs/nanopb/tests/missing_fields/SConscript new file mode 100644 index 00000000..86ba0833 --- /dev/null +++ b/libs/nanopb/tests/missing_fields/SConscript @@ -0,0 +1,8 @@ +# Check that the decoder properly detects when required fields are missing. + +Import("env") + +env.NanopbProto("missing_fields") +test = env.Program(["missing_fields.c", "missing_fields.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_decode.o", "$COMMON/pb_common.o"]) +env.RunTest(test) + diff --git a/libs/nanopb/tests/missing_fields/missing_fields.c b/libs/nanopb/tests/missing_fields/missing_fields.c new file mode 100644 index 00000000..8aded827 --- /dev/null +++ b/libs/nanopb/tests/missing_fields/missing_fields.c @@ -0,0 +1,53 @@ +/* Checks that missing required fields are detected properly */ + +#include +#include +#include +#include "missing_fields.pb.h" + +int main() +{ + uint8_t buffer[512]; + size_t size; + + /* Create a message with one missing field */ + { + MissingField msg = {0}; + pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + if (!pb_encode(&stream, MissingField_fields, &msg)) + { + printf("Encode failed.\n"); + return 1; + } + + size = stream.bytes_written; + } + + /* Test that it decodes properly if we don't require that field */ + { + MissingField msg = {0}; + pb_istream_t stream = pb_istream_from_buffer(buffer, size); + + if (!pb_decode(&stream, MissingField_fields, &msg)) + { + printf("Decode failed: %s\n", PB_GET_ERROR(&stream)); + return 2; + } + } + + /* Test that it does *not* decode properly if we require the field */ + { + AllFields msg = {0}; + pb_istream_t stream = pb_istream_from_buffer(buffer, size); + + if (pb_decode(&stream, AllFields_fields, &msg)) + { + printf("Decode didn't detect missing field.\n"); + return 3; + } + } + + return 0; /* All ok */ +} + diff --git a/libs/nanopb/tests/missing_fields/missing_fields.proto b/libs/nanopb/tests/missing_fields/missing_fields.proto new file mode 100644 index 00000000..cc5e550b --- /dev/null +++ b/libs/nanopb/tests/missing_fields/missing_fields.proto @@ -0,0 +1,140 @@ +/* Test for one missing field among many */ + +syntax = "proto2"; + +message AllFields +{ + required int32 field1 = 1; + required int32 field2 = 2; + required int32 field3 = 3; + required int32 field4 = 4; + required int32 field5 = 5; + required int32 field6 = 6; + required int32 field7 = 7; + required int32 field8 = 8; + required int32 field9 = 9; + required int32 field10 = 10; + required int32 field11 = 11; + required int32 field12 = 12; + required int32 field13 = 13; + required int32 field14 = 14; + required int32 field15 = 15; + required int32 field16 = 16; + required int32 field17 = 17; + required int32 field18 = 18; + required int32 field19 = 19; + required int32 field20 = 20; + required int32 field21 = 21; + required int32 field22 = 22; + required int32 field23 = 23; + required int32 field24 = 24; + required int32 field25 = 25; + required int32 field26 = 26; + required int32 field27 = 27; + required int32 field28 = 28; + required int32 field29 = 29; + required int32 field30 = 30; + required int32 field31 = 31; + required int32 field32 = 32; + required int32 field33 = 33; + required int32 field34 = 34; + required int32 field35 = 35; + required int32 field36 = 36; + required int32 field37 = 37; + required int32 field38 = 38; + required int32 field39 = 39; + required int32 field40 = 40; + required int32 field41 = 41; + required int32 field42 = 42; + required int32 field43 = 43; + required int32 field44 = 44; + required int32 field45 = 45; + required int32 field46 = 46; + required int32 field47 = 47; + required int32 field48 = 48; + required int32 field49 = 49; + required int32 field50 = 50; + required int32 field51 = 51; + required int32 field52 = 52; + required int32 field53 = 53; + required int32 field54 = 54; + required int32 field55 = 55; + required int32 field56 = 56; + required int32 field57 = 57; + required int32 field58 = 58; + required int32 field59 = 59; + required int32 field60 = 60; + required int32 field61 = 61; + required int32 field62 = 62; + required int32 field63 = 63; + required int32 field64 = 64; +} + +message MissingField +{ + required int32 field1 = 1; + required int32 field2 = 2; + required int32 field3 = 3; + required int32 field4 = 4; + required int32 field5 = 5; + required int32 field6 = 6; + required int32 field7 = 7; + required int32 field8 = 8; + required int32 field9 = 9; + required int32 field10 = 10; + required int32 field11 = 11; + required int32 field12 = 12; + required int32 field13 = 13; + required int32 field14 = 14; + required int32 field15 = 15; + required int32 field16 = 16; + required int32 field17 = 17; + required int32 field18 = 18; + required int32 field19 = 19; + required int32 field20 = 20; + required int32 field21 = 21; + required int32 field22 = 22; + required int32 field23 = 23; + required int32 field24 = 24; + required int32 field25 = 25; + required int32 field26 = 26; + required int32 field27 = 27; + required int32 field28 = 28; + required int32 field29 = 29; + required int32 field30 = 30; + required int32 field31 = 31; + required int32 field32 = 32; + required int32 field33 = 33; + required int32 field34 = 34; + required int32 field35 = 35; + required int32 field36 = 36; + required int32 field37 = 37; + required int32 field38 = 38; + required int32 field39 = 39; + required int32 field40 = 40; + required int32 field41 = 41; + required int32 field42 = 42; + required int32 field43 = 43; + required int32 field44 = 44; + required int32 field45 = 45; + required int32 field46 = 46; + required int32 field47 = 47; + required int32 field48 = 48; + required int32 field49 = 49; + required int32 field50 = 50; + required int32 field51 = 51; + required int32 field52 = 52; + required int32 field53 = 53; + required int32 field54 = 54; + required int32 field55 = 55; + required int32 field56 = 56; + required int32 field57 = 57; + required int32 field58 = 58; + required int32 field59 = 59; + required int32 field60 = 60; + required int32 field61 = 61; + required int32 field62 = 62; +/* required int32 field63 = 63; */ + required int32 field64 = 64; +} + diff --git a/libs/nanopb/tests/multiple_files/SConscript b/libs/nanopb/tests/multiple_files/SConscript new file mode 100644 index 00000000..b1281e17 --- /dev/null +++ b/libs/nanopb/tests/multiple_files/SConscript @@ -0,0 +1,16 @@ +# Test that multiple .proto files don't cause name collisions. + +Import("env") + +incpath = env.Clone() +incpath.Append(PROTOCPATH = '#multiple_files') +incpath.Append(CPPPATH = '$BUILD/multiple_files') + +incpath.NanopbProto(["multifile1", "multifile1.options"]) +incpath.NanopbProto("multifile2") +incpath.NanopbProto("subdir/multifile2") +test = incpath.Program(["test_multiple_files.c", "multifile1.pb.c", + "multifile2.pb.c", "subdir/multifile2.pb.c"]) + +env.RunTest(test) + diff --git a/libs/nanopb/tests/multiple_files/multifile1.options b/libs/nanopb/tests/multiple_files/multifile1.options new file mode 100644 index 00000000..c44d2669 --- /dev/null +++ b/libs/nanopb/tests/multiple_files/multifile1.options @@ -0,0 +1 @@ +StaticMessage.repint32 max_count:5 diff --git a/libs/nanopb/tests/multiple_files/multifile1.proto b/libs/nanopb/tests/multiple_files/multifile1.proto new file mode 100644 index 00000000..18f2c672 --- /dev/null +++ b/libs/nanopb/tests/multiple_files/multifile1.proto @@ -0,0 +1,34 @@ +syntax = "proto2"; + +message SubMessage { + optional string stringvalue = 1; + repeated int32 int32value = 2; + repeated fixed32 fixed32value = 3; + repeated fixed64 fixed64value = 4; +} + +message TestMessage { + optional string stringvalue = 1; + repeated int32 int32value = 2; + repeated fixed32 fixed32value = 3; + repeated fixed64 fixed64value = 4; + optional SubMessage submsg = 5; + repeated string repeatedstring = 6; +} + +message StaticMessage { + repeated fixed32 repint32 = 1; +} + +enum SignedEnum { + SE_MIN = -128; + SE_MAX = 127; +} + +enum UnsignedEnum { + UE_MIN = 0; + UE_MAX = 255; +} + + + diff --git a/libs/nanopb/tests/multiple_files/multifile2.proto b/libs/nanopb/tests/multiple_files/multifile2.proto new file mode 100644 index 00000000..4af45fd9 --- /dev/null +++ b/libs/nanopb/tests/multiple_files/multifile2.proto @@ -0,0 +1,22 @@ +// Test if including generated header file for this file + implicit include of +// multifile2.pb.h still compiles. Used with test_compiles.c. +syntax = "proto2"; + +import "multifile1.proto"; + +message Callback2Message { + required TestMessage tstmsg = 1; + required SubMessage submsg = 2; +} + +message OneofMessage { + oneof msgs { + StaticMessage tstmsg = 1; + } +} + +message Enums { + required SignedEnum senum = 1; + required UnsignedEnum uenum = 2; +} + diff --git a/libs/nanopb/tests/multiple_files/subdir/multifile2.proto b/libs/nanopb/tests/multiple_files/subdir/multifile2.proto new file mode 100644 index 00000000..847a9290 --- /dev/null +++ b/libs/nanopb/tests/multiple_files/subdir/multifile2.proto @@ -0,0 +1,25 @@ +syntax = "proto2"; + +package subdir; + +import "multifile1.proto"; + +message Callback2Message { + required TestMessage tstmsg = 1; + required SubMessage submsg = 2; +} + +message OneofMessage { + oneof msgs { + StaticMessage tstmsg = 1; + } +} + +message Enums { + required SignedEnum senum = 1; + required UnsignedEnum uenum = 2; +} + +message SubdirMessage { + required int32 foo = 1 [default = 15]; +} diff --git a/libs/nanopb/tests/multiple_files/test_multiple_files.c b/libs/nanopb/tests/multiple_files/test_multiple_files.c new file mode 100644 index 00000000..70a3e596 --- /dev/null +++ b/libs/nanopb/tests/multiple_files/test_multiple_files.c @@ -0,0 +1,30 @@ +/* + * Tests if this still compiles when multiple .proto files are involved. + */ + +#include +#include +#include "unittests.h" +#include "multifile2.pb.h" +#include "subdir/multifile2.pb.h" + +int main() +{ + int status = 0; + + /* Test that included file options are properly loaded */ + TEST(OneofMessage_size == 27); + + /* Check that enum signedness is detected properly */ + TEST(PB_LTYPE(Enums_fields[0].type) == PB_LTYPE_VARINT); + TEST(PB_LTYPE(Enums_fields[1].type) == PB_LTYPE_UVARINT); + + /* Test that subdir file is correctly included */ + { + subdir_SubdirMessage foo = subdir_SubdirMessage_init_default; + TEST(foo.foo == 15); + /* TEST(subdir_OneofMessage_size == 27); */ /* TODO: Issue #172 */ + } + + return status; +} diff --git a/libs/nanopb/tests/no_errmsg/SConscript b/libs/nanopb/tests/no_errmsg/SConscript new file mode 100644 index 00000000..629bfa68 --- /dev/null +++ b/libs/nanopb/tests/no_errmsg/SConscript @@ -0,0 +1,28 @@ +# Run the alltypes test case, but compile with PB_NO_ERRMSG=1 + +Import("env") + +# Take copy of the files for custom build. +c = Copy("$TARGET", "$SOURCE") +env.Command("alltypes.pb.h", "$BUILD/alltypes/alltypes.pb.h", c) +env.Command("alltypes.pb.c", "$BUILD/alltypes/alltypes.pb.c", c) +env.Command("encode_alltypes.c", "$BUILD/alltypes/encode_alltypes.c", c) +env.Command("decode_alltypes.c", "$BUILD/alltypes/decode_alltypes.c", c) + +# Define the compilation options +opts = env.Clone() +opts.Append(CPPDEFINES = {'PB_NO_ERRMSG': 1}) + +# Build new version of core +strict = opts.Clone() +strict.Append(CFLAGS = strict['CORECFLAGS']) +strict.Object("pb_decode_noerr.o", "$NANOPB/pb_decode.c") +strict.Object("pb_encode_noerr.o", "$NANOPB/pb_encode.c") +strict.Object("pb_common_noerr.o", "$NANOPB/pb_common.c") + +# Now build and run the test normally. +enc = opts.Program(["encode_alltypes.c", "alltypes.pb.c", "pb_encode_noerr.o", "pb_common_noerr.o"]) +dec = opts.Program(["decode_alltypes.c", "alltypes.pb.c", "pb_decode_noerr.o", "pb_common_noerr.o"]) + +env.RunTest(enc) +env.RunTest([dec, "encode_alltypes.output"]) diff --git a/libs/nanopb/tests/no_messages/SConscript b/libs/nanopb/tests/no_messages/SConscript new file mode 100644 index 00000000..6492e2cf --- /dev/null +++ b/libs/nanopb/tests/no_messages/SConscript @@ -0,0 +1,7 @@ +# Test that a .proto file without any messages compiles fine. + +Import("env") + +env.NanopbProto("no_messages") +env.Object('no_messages.pb.c') + diff --git a/libs/nanopb/tests/no_messages/no_messages.proto b/libs/nanopb/tests/no_messages/no_messages.proto new file mode 100644 index 00000000..45bb2e66 --- /dev/null +++ b/libs/nanopb/tests/no_messages/no_messages.proto @@ -0,0 +1,9 @@ +/* Test that a file without any messages works. */ + +syntax = "proto2"; + +enum Test { + First = 1; +} + + diff --git a/libs/nanopb/tests/oneof/SConscript b/libs/nanopb/tests/oneof/SConscript new file mode 100644 index 00000000..22634fb0 --- /dev/null +++ b/libs/nanopb/tests/oneof/SConscript @@ -0,0 +1,33 @@ +# Test the 'oneof' feature for generating C unions. + +Import('env') + +import re + +match = None +if 'PROTOC_VERSION' in env: + match = re.search('([0-9]+).([0-9]+).([0-9]+)', env['PROTOC_VERSION']) + +if match: + version = map(int, match.groups()) + +# Oneof is supported by protoc >= 2.6.0 +if env.GetOption('clean') or (match and (version[0] > 2 or (version[0] == 2 and version[1] >= 6))): + env.NanopbProto('oneof') + + enc = env.Program(['encode_oneof.c', + 'oneof.pb.c', + '$COMMON/pb_encode.o', + '$COMMON/pb_common.o']) + + dec = env.Program(['decode_oneof.c', + 'oneof.pb.c', + '$COMMON/pb_decode.o', + '$COMMON/pb_common.o']) + + env.RunTest("message1.pb", enc, ARGS = ['1']) + env.RunTest("message1.txt", [dec, 'message1.pb'], ARGS = ['1']) + env.RunTest("message2.pb", enc, ARGS = ['2']) + env.RunTest("message2.txt", [dec, 'message2.pb'], ARGS = ['2']) + env.RunTest("message3.pb", enc, ARGS = ['3']) + env.RunTest("message3.txt", [dec, 'message3.pb'], ARGS = ['3']) diff --git a/libs/nanopb/tests/oneof/decode_oneof.c b/libs/nanopb/tests/oneof/decode_oneof.c new file mode 100644 index 00000000..37075cd6 --- /dev/null +++ b/libs/nanopb/tests/oneof/decode_oneof.c @@ -0,0 +1,131 @@ +/* Decode a message using oneof fields */ + +#include +#include +#include +#include +#include "oneof.pb.h" +#include "test_helpers.h" +#include "unittests.h" + +/* Test the 'OneOfMessage' */ +int test_oneof_1(pb_istream_t *stream, int option) +{ + OneOfMessage msg; + int status = 0; + + /* To better catch initialization errors */ + memset(&msg, 0xAA, sizeof(msg)); + + if (!pb_decode(stream, OneOfMessage_fields, &msg)) + { + printf("Decoding failed: %s\n", PB_GET_ERROR(stream)); + return 1; + } + + /* Check that the basic fields work normally */ + TEST(msg.prefix == 123); + TEST(msg.suffix == 321); + + /* Check that we got the right oneof according to command line */ + if (option == 1) + { + TEST(msg.which_values == OneOfMessage_first_tag); + TEST(msg.values.first == 999); + } + else if (option == 2) + { + TEST(msg.which_values == OneOfMessage_second_tag); + TEST(strcmp(msg.values.second, "abcd") == 0); + } + else if (option == 3) + { + TEST(msg.which_values == OneOfMessage_third_tag); + TEST(msg.values.third.array[0] == 1); + TEST(msg.values.third.array[1] == 2); + TEST(msg.values.third.array[2] == 3); + TEST(msg.values.third.array[3] == 4); + TEST(msg.values.third.array[4] == 5); + } + + return status; +} + + +/* Test the 'PlainOneOfMessage' */ +int test_oneof_2(pb_istream_t *stream, int option) +{ + PlainOneOfMessage msg = PlainOneOfMessage_init_zero; + int status = 0; + + if (!pb_decode(stream, PlainOneOfMessage_fields, &msg)) + { + printf("Decoding failed: %s\n", PB_GET_ERROR(stream)); + return 1; + } + + /* Check that we got the right oneof according to command line */ + if (option == 1) + { + TEST(msg.which_values == OneOfMessage_first_tag); + TEST(msg.values.first == 999); + } + else if (option == 2) + { + TEST(msg.which_values == OneOfMessage_second_tag); + TEST(strcmp(msg.values.second, "abcd") == 0); + } + else if (option == 3) + { + TEST(msg.which_values == OneOfMessage_third_tag); + TEST(msg.values.third.array[0] == 1); + TEST(msg.values.third.array[1] == 2); + TEST(msg.values.third.array[2] == 3); + TEST(msg.values.third.array[3] == 4); + TEST(msg.values.third.array[4] == 5); + } + + return status; +} + +int main(int argc, char **argv) +{ + uint8_t buffer[OneOfMessage_size]; + size_t count; + int option; + + if (argc != 2) + { + fprintf(stderr, "Usage: decode_oneof [number]\n"); + return 1; + } + option = atoi(argv[1]); + + SET_BINARY_MODE(stdin); + count = fread(buffer, 1, sizeof(buffer), stdin); + + if (!feof(stdin)) + { + printf("Message does not fit in buffer\n"); + return 1; + } + + { + int status = 0; + pb_istream_t stream; + + stream = pb_istream_from_buffer(buffer, count); + status = test_oneof_1(&stream, option); + + if (status != 0) + return status; + + stream = pb_istream_from_buffer(buffer, count); + status = test_oneof_2(&stream, option); + + if (status != 0) + return status; + } + + return 0; +} diff --git a/libs/nanopb/tests/oneof/encode_oneof.c b/libs/nanopb/tests/oneof/encode_oneof.c new file mode 100644 index 00000000..913d2d43 --- /dev/null +++ b/libs/nanopb/tests/oneof/encode_oneof.c @@ -0,0 +1,64 @@ +/* Encode a message using oneof fields */ + +#include +#include +#include +#include "oneof.pb.h" +#include "test_helpers.h" + +int main(int argc, char **argv) +{ + uint8_t buffer[OneOfMessage_size]; + OneOfMessage msg = OneOfMessage_init_zero; + pb_ostream_t stream; + int option; + + if (argc != 2) + { + fprintf(stderr, "Usage: encode_oneof [number]\n"); + return 1; + } + option = atoi(argv[1]); + + /* Prefix and suffix are used to test that the union does not disturb + * other fields in the same message. */ + msg.prefix = 123; + + /* We encode one of the 'values' fields based on command line argument */ + if (option == 1) + { + msg.which_values = OneOfMessage_first_tag; + msg.values.first = 999; + } + else if (option == 2) + { + msg.which_values = OneOfMessage_second_tag; + strcpy(msg.values.second, "abcd"); + } + else if (option == 3) + { + msg.which_values = OneOfMessage_third_tag; + msg.values.third.array_count = 5; + msg.values.third.array[0] = 1; + msg.values.third.array[1] = 2; + msg.values.third.array[2] = 3; + msg.values.third.array[3] = 4; + msg.values.third.array[4] = 5; + } + + msg.suffix = 321; + + stream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + + if (pb_encode(&stream, OneOfMessage_fields, &msg)) + { + SET_BINARY_MODE(stdout); + fwrite(buffer, 1, stream.bytes_written, stdout); + return 0; + } + else + { + fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream)); + return 1; + } +} diff --git a/libs/nanopb/tests/oneof/oneof.proto b/libs/nanopb/tests/oneof/oneof.proto new file mode 100644 index 00000000..b4fe56f2 --- /dev/null +++ b/libs/nanopb/tests/oneof/oneof.proto @@ -0,0 +1,32 @@ +syntax = "proto2"; + +import 'nanopb.proto'; + +message SubMessage +{ + repeated int32 array = 1 [(nanopb).max_count = 8]; +} + +/* Oneof in a message with other fields */ +message OneOfMessage +{ + required int32 prefix = 1; + oneof values + { + int32 first = 5; + string second = 6 [(nanopb).max_size = 8]; + SubMessage third = 7; + } + required int32 suffix = 99; +} + +/* Oneof in a message by itself */ +message PlainOneOfMessage +{ + oneof values + { + int32 first = 5; + string second = 6 [(nanopb).max_size = 8]; + SubMessage third = 7; + } +} \ No newline at end of file diff --git a/libs/nanopb/tests/options/SConscript b/libs/nanopb/tests/options/SConscript new file mode 100644 index 00000000..215e3bd0 --- /dev/null +++ b/libs/nanopb/tests/options/SConscript @@ -0,0 +1,12 @@ +# Test that the generator options work as expected. + +Import("env") + +env.NanopbProto("options") +env.Object('options.pb.c') +env.Match(['options.pb.h', 'options.expected']) + +env.NanopbProto("proto3_options") +env.Object('proto3_options.pb.c') +env.Match(['proto3_options.pb.h', 'proto3_options.expected']) + diff --git a/libs/nanopb/tests/options/options.expected b/libs/nanopb/tests/options/options.expected new file mode 100644 index 00000000..9e47e6a4 --- /dev/null +++ b/libs/nanopb/tests/options/options.expected @@ -0,0 +1,20 @@ +char filesize\[20\]; +char msgsize\[30\]; +char fieldsize\[40\]; +char fieldlen\[41\]; +pb_callback_t int32_callback; +\sEnumValue1 = 1 +Message5_EnumValue1 +} pb_packed my_packed_struct; +! skipped_field +! SkippedMessage +#define PB_MSG_103 Message3 +#define PB_MSG_104 Message4 +#define PB_MSG_105 Message5 +#define OPTIONS_MESSAGES \\ +\s+PB_MSG\(103,[0-9]*,Message3\) \\ +\s+PB_MSG\(104,-1,Message4\) \\ +\s+PB_MSG\(105,[0-9]*,Message5\) \\ +#define Message5_msgid 105 +! has_proto3field + diff --git a/libs/nanopb/tests/options/options.proto b/libs/nanopb/tests/options/options.proto new file mode 100644 index 00000000..c6ca5e25 --- /dev/null +++ b/libs/nanopb/tests/options/options.proto @@ -0,0 +1,98 @@ +/* Test nanopb option parsing. + * options.expected lists the patterns that are searched for in the output. + */ + +syntax = "proto2"; + +import "nanopb.proto"; + +// File level options +option (nanopb_fileopt).max_size = 20; + +message Message1 +{ + required string filesize = 1; +} + +// Message level options +message Message2 +{ + option (nanopb_msgopt).max_size = 30; + required string msgsize = 1; +} + +// Field level options +message Message3 +{ + option (nanopb_msgopt).msgid = 103; + required string fieldsize = 1 [(nanopb).max_size = 40]; + required string fieldlen = 2 [(nanopb).max_length = 40]; +} + +// Forced callback field +message Message4 +{ + option (nanopb_msgopt).msgid = 104; + required int32 int32_callback = 1 [(nanopb).type = FT_CALLBACK]; +} + +// Short enum names +enum Enum1 +{ + option (nanopb_enumopt).long_names = false; + EnumValue1 = 1; + EnumValue2 = 2; +} + +message EnumTest +{ + required Enum1 field = 1 [default = EnumValue2]; +} + +// Short enum names inside message +message Message5 +{ + option (nanopb_msgopt).msgid = 105; + enum Enum2 + { + option (nanopb_enumopt).long_names = false; + EnumValue1 = 1; + } + required Enum2 field = 1 [default = EnumValue1]; +} + +// Packed structure +message my_packed_struct +{ + option (nanopb_msgopt).packed_struct = true; + optional int32 myfield = 1; +} + +// Message with ignored field +message Message6 +{ + required int32 field1 = 1; + optional int32 skipped_field = 2 [(nanopb).type = FT_IGNORE]; +} + +// Message that is skipped +message SkippedMessage +{ + option (nanopb_msgopt).skip_message = true; + required int32 foo = 1; +} + +// Message with oneof field +message OneofMessage +{ + oneof foo { + int32 bar = 1; + } +} + +// Proto3-style optional field in proto2 file +message Proto3Field +{ + optional int32 proto3field = 1 [(nanopb).proto3 = true]; +} + diff --git a/libs/nanopb/tests/options/proto3_options.expected b/libs/nanopb/tests/options/proto3_options.expected new file mode 100644 index 00000000..cc2f29c0 --- /dev/null +++ b/libs/nanopb/tests/options/proto3_options.expected @@ -0,0 +1,4 @@ +! bool has_proto3_default +bool has_proto3_off +! bool has_proto3_on + diff --git a/libs/nanopb/tests/options/proto3_options.proto b/libs/nanopb/tests/options/proto3_options.proto new file mode 100644 index 00000000..1017f046 --- /dev/null +++ b/libs/nanopb/tests/options/proto3_options.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; + +import "nanopb.proto"; + +message Message1 +{ + int32 proto3_default = 1; + int32 proto3_off = 2 [(nanopb).proto3 = false]; + int32 proto3_on = 3 [(nanopb).proto3 = true]; +} + diff --git a/libs/nanopb/tests/package_name/SConscript b/libs/nanopb/tests/package_name/SConscript new file mode 100644 index 00000000..4afc5037 --- /dev/null +++ b/libs/nanopb/tests/package_name/SConscript @@ -0,0 +1,38 @@ +# Check that alltypes test case works also when the .proto file defines +# a package name. + +Import("env") + +def set_pkgname(src, dst, pkgname): + data = open(str(src)).read() + placeholder = '// package name placeholder' + assert placeholder in data + data = data.replace(placeholder, 'package %s;' % pkgname) + open(str(dst), 'w').write(data) + +# Build a modified alltypes.proto +env.Command("alltypes.proto", "#alltypes/alltypes.proto", + lambda target, source, env: set_pkgname(source[0], target[0], 'test.package')) +env.Command("alltypes.options", "#alltypes/alltypes.options", Copy("$TARGET", "$SOURCE")) +env.NanopbProto(["alltypes", "alltypes.options"]) + +# Build a modified encode_alltypes.c +def modify_c(target, source, env): + '''Add package name to type names in .c file.''' + + data = open(str(source[0]), 'r').read() + + type_names = ['AllTypes', 'MyEnum', 'HugeEnum'] + for name in type_names: + data = data.replace(name, 'test_package_' + name) + + open(str(target[0]), 'w').write(data) + return 0 +env.Command("encode_alltypes.c", "#alltypes/encode_alltypes.c", modify_c) + +# Encode and compare results to original alltypes testcase +enc = env.Program(["encode_alltypes.c", "alltypes.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_common.o"]) +refdec = "$BUILD/alltypes/decode_alltypes$PROGSUFFIX" +env.RunTest(enc) +env.Compare(["encode_alltypes.output", "$BUILD/alltypes/encode_alltypes.output"]) + diff --git a/libs/nanopb/tests/regression/issue_118/SConscript b/libs/nanopb/tests/regression/issue_118/SConscript new file mode 100644 index 00000000..833d9dec --- /dev/null +++ b/libs/nanopb/tests/regression/issue_118/SConscript @@ -0,0 +1,12 @@ +# Regression test for Issue 118: Short enum names in imported proto files are not honoured + +Import("env") +env = env.Clone() +env.Append(PROTOCPATH = "#regression/issue_118") + +env.NanopbProto("enumdef") +env.Object('enumdef.pb.c') + +env.NanopbProto(["enumuse", "enumdef.proto"]) +env.Object('enumuse.pb.c') + diff --git a/libs/nanopb/tests/regression/issue_118/enumdef.proto b/libs/nanopb/tests/regression/issue_118/enumdef.proto new file mode 100644 index 00000000..46845bc9 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_118/enumdef.proto @@ -0,0 +1,8 @@ +syntax = "proto2"; + +import 'nanopb.proto'; + +enum MyEnum { + option (nanopb_enumopt).long_names = false; + FOOBAR = 1; +} diff --git a/libs/nanopb/tests/regression/issue_118/enumuse.proto b/libs/nanopb/tests/regression/issue_118/enumuse.proto new file mode 100644 index 00000000..4afc4521 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_118/enumuse.proto @@ -0,0 +1,7 @@ +syntax = "proto2"; + +import 'enumdef.proto'; + +message MyMessage { + required MyEnum myenum = 1 [default = FOOBAR]; +} diff --git a/libs/nanopb/tests/regression/issue_125/SConscript b/libs/nanopb/tests/regression/issue_125/SConscript new file mode 100644 index 00000000..f2155e63 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_125/SConscript @@ -0,0 +1,9 @@ +# Regression test for Issue 125: Wrong identifier name for extension fields + +Import("env") + +env.NanopbProto(["extensionbug", "extensionbug.options"]) +env.Object('extensionbug.pb.c') + +env.Match(['extensionbug.pb.h', 'extensionbug.expected']) + diff --git a/libs/nanopb/tests/regression/issue_125/extensionbug.expected b/libs/nanopb/tests/regression/issue_125/extensionbug.expected new file mode 100644 index 00000000..fc213354 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_125/extensionbug.expected @@ -0,0 +1,3 @@ +pb_extension_type_t Message2_extras +uint32_t field2 + diff --git a/libs/nanopb/tests/regression/issue_125/extensionbug.options b/libs/nanopb/tests/regression/issue_125/extensionbug.options new file mode 100644 index 00000000..30b464a4 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_125/extensionbug.options @@ -0,0 +1,4 @@ +* type:FT_IGNORE + +Message2.extras type:FT_STATIC +Message2.field2 type:FT_STATIC diff --git a/libs/nanopb/tests/regression/issue_125/extensionbug.proto b/libs/nanopb/tests/regression/issue_125/extensionbug.proto new file mode 100644 index 00000000..fd1e74f1 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_125/extensionbug.proto @@ -0,0 +1,18 @@ +syntax = "proto2"; + +message Message1 +{ + optional uint32 fieldA = 1; + extensions 30 to max; +} + +message Message2 +{ + extend Message1 + { + optional Message2 extras = 30; + } + + optional uint32 field1 = 1; + optional uint32 field2 = 2; +} diff --git a/libs/nanopb/tests/regression/issue_141/SConscript b/libs/nanopb/tests/regression/issue_141/SConscript new file mode 100644 index 00000000..b6526bed --- /dev/null +++ b/libs/nanopb/tests/regression/issue_141/SConscript @@ -0,0 +1,8 @@ +# Regression test for issue 141: wrong encoded size #define for oneof messages + +Import("env") + +env.NanopbProto("testproto") +env.Object('testproto.pb.c') +env.Match(['testproto.pb.h', 'testproto.expected']) + diff --git a/libs/nanopb/tests/regression/issue_141/testproto.expected b/libs/nanopb/tests/regression/issue_141/testproto.expected new file mode 100644 index 00000000..75bc195c --- /dev/null +++ b/libs/nanopb/tests/regression/issue_141/testproto.expected @@ -0,0 +1,7 @@ +define SubMessage_size \s* 88 +define OneOfMessage_size \s* 113 +define topMessage_size \s* 70 +define MyMessage1_size \s* 46 +define MyMessage2_size \s* 8 +define MyMessage3_size \s* 5 +define MyMessage4_size \s* 18 diff --git a/libs/nanopb/tests/regression/issue_141/testproto.proto b/libs/nanopb/tests/regression/issue_141/testproto.proto new file mode 100644 index 00000000..a445c68a --- /dev/null +++ b/libs/nanopb/tests/regression/issue_141/testproto.proto @@ -0,0 +1,52 @@ +syntax = "proto2"; + +import 'nanopb.proto'; + +message SubMessage +{ + repeated int32 array = 1 [(nanopb).max_count = 8]; +} + +message OneOfMessage +{ + required int32 prefix = 1; + oneof values + { + int32 first = 5; + string second = 6 [(nanopb).max_size = 8]; + SubMessage third = 7; + } + required int32 suffix = 99; +} + +message topMessage { + required int32 start = 1; + oneof msg { + MyMessage1 msg1 = 2; + MyMessage2 msg2 = 3; + } + required int32 end = 4; +} + +message MyMessage1 { + required uint32 n1 = 1; + required uint32 n2 = 2; + required string s = 3 [(nanopb).max_size = 32]; +} + +message MyMessage2 { + required uint32 num = 1; + required bool b = 2; +} + +message MyMessage3 { + required bool bbb = 1; + required string ss = 2 [(nanopb).max_size = 1]; +} + +message MyMessage4 { + required bool bbbb = 1; + required string sss = 2 [(nanopb).max_size = 2]; + required uint32 num = 3; + required uint32 num2 = 4; +} diff --git a/libs/nanopb/tests/regression/issue_145/SConscript b/libs/nanopb/tests/regression/issue_145/SConscript new file mode 100644 index 00000000..0b793a7a --- /dev/null +++ b/libs/nanopb/tests/regression/issue_145/SConscript @@ -0,0 +1,9 @@ +# Regression test for Issue 145: Allow /* */ and // comments in .options files + +Import("env") + +env.NanopbProto(["comments", "comments.options"]) +env.Object('comments.pb.c') + +env.Match(['comments.pb.h', 'comments.expected']) + diff --git a/libs/nanopb/tests/regression/issue_145/comments.expected b/libs/nanopb/tests/regression/issue_145/comments.expected new file mode 100644 index 00000000..7f874587 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_145/comments.expected @@ -0,0 +1,3 @@ +char foo\[5\]; +char bar\[16\]; + diff --git a/libs/nanopb/tests/regression/issue_145/comments.options b/libs/nanopb/tests/regression/issue_145/comments.options new file mode 100644 index 00000000..89959ba2 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_145/comments.options @@ -0,0 +1,6 @@ +/* Block comment */ +# Line comment +// Line comment +DummyMessage.foo /* Block comment */ max_size:5 +DummyMessage.bar max_size:16 # Line comment ### + diff --git a/libs/nanopb/tests/regression/issue_145/comments.proto b/libs/nanopb/tests/regression/issue_145/comments.proto new file mode 100644 index 00000000..621779f5 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_145/comments.proto @@ -0,0 +1,7 @@ +syntax = "proto2"; + +message DummyMessage { + required string foo = 1; + required string bar = 2; +} + diff --git a/libs/nanopb/tests/regression/issue_166/SConscript b/libs/nanopb/tests/regression/issue_166/SConscript new file mode 100644 index 00000000..c50b9193 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_166/SConscript @@ -0,0 +1,13 @@ +# Verify that the maximum encoded size is calculated properly +# for enums. + +Import('env') + +env.NanopbProto('enums') + +p = env.Program(["enum_encoded_size.c", + "enums.pb.c", + "$COMMON/pb_encode.o", + "$COMMON/pb_common.o"]) +env.RunTest(p) + diff --git a/libs/nanopb/tests/regression/issue_166/enum_encoded_size.c b/libs/nanopb/tests/regression/issue_166/enum_encoded_size.c new file mode 100644 index 00000000..84e1c7de --- /dev/null +++ b/libs/nanopb/tests/regression/issue_166/enum_encoded_size.c @@ -0,0 +1,43 @@ +#include +#include +#include +#include "unittests.h" +#include "enums.pb.h" + +int main() +{ + int status = 0; + + uint8_t buf[256]; + SignedMsg msg1; + UnsignedMsg msg2; + pb_ostream_t s; + + { + COMMENT("Test negative value of signed enum"); + /* Negative value should take up the maximum size */ + msg1.value = SignedEnum_SE_MIN; + s = pb_ostream_from_buffer(buf, sizeof(buf)); + TEST(pb_encode(&s, SignedMsg_fields, &msg1)); + TEST(s.bytes_written == SignedMsg_size); + + COMMENT("Test positive value of signed enum"); + /* Positive value should be smaller */ + msg1.value = SignedEnum_SE_MAX; + s = pb_ostream_from_buffer(buf, sizeof(buf)); + TEST(pb_encode(&s, SignedMsg_fields, &msg1)); + TEST(s.bytes_written < SignedMsg_size); + } + + { + COMMENT("Test positive value of unsigned enum"); + /* This should take up the maximum size */ + msg2.value = UnsignedEnum_UE_MAX; + s = pb_ostream_from_buffer(buf, sizeof(buf)); + TEST(pb_encode(&s, UnsignedMsg_fields, &msg2)); + TEST(s.bytes_written == UnsignedMsg_size); + } + + return status; +} + diff --git a/libs/nanopb/tests/regression/issue_166/enums.proto b/libs/nanopb/tests/regression/issue_166/enums.proto new file mode 100644 index 00000000..36948044 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_166/enums.proto @@ -0,0 +1,18 @@ +syntax = "proto2"; + +enum SignedEnum { + SE_MIN = -1; + SE_MAX = 255; +} + +enum UnsignedEnum { + UE_MAX = 65536; +} + +message SignedMsg { + required SignedEnum value = 1; +} + +message UnsignedMsg { + required UnsignedEnum value = 1; +} diff --git a/libs/nanopb/tests/regression/issue_172/SConscript b/libs/nanopb/tests/regression/issue_172/SConscript new file mode 100644 index 00000000..49c919e8 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_172/SConscript @@ -0,0 +1,16 @@ +# Verify that _size define is generated for messages that have +# includes from another directory. + +Import('env') + +incpath = env.Clone() +incpath.Append(PROTOCPATH="#regression/issue_172/submessage") +incpath.Append(CPPPATH="$BUILD/regression/issue_172/submessage") +incpath.NanopbProto('test') +incpath.NanopbProto(['submessage/submessage', 'submessage/submessage.options']) + +p = incpath.Program(["msg_size.c", + "test.pb.c", + "submessage/submessage.pb.c"]) + + diff --git a/libs/nanopb/tests/regression/issue_172/msg_size.c b/libs/nanopb/tests/regression/issue_172/msg_size.c new file mode 100644 index 00000000..be45acb4 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_172/msg_size.c @@ -0,0 +1,9 @@ +#include "test.pb.h" + +PB_STATIC_ASSERT(testmessage_size >= 1+1+1+1+16, TESTMESSAGE_SIZE_IS_WRONG) + +int main() +{ + return 0; +} + diff --git a/libs/nanopb/tests/regression/issue_172/submessage/submessage.options b/libs/nanopb/tests/regression/issue_172/submessage/submessage.options new file mode 100644 index 00000000..12fb1984 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_172/submessage/submessage.options @@ -0,0 +1 @@ +submessage.data max_size: 16 diff --git a/libs/nanopb/tests/regression/issue_172/submessage/submessage.proto b/libs/nanopb/tests/regression/issue_172/submessage/submessage.proto new file mode 100644 index 00000000..ce6804af --- /dev/null +++ b/libs/nanopb/tests/regression/issue_172/submessage/submessage.proto @@ -0,0 +1,4 @@ +syntax = "proto2"; +message submessage { + required bytes data = 1; +} diff --git a/libs/nanopb/tests/regression/issue_172/test.proto b/libs/nanopb/tests/regression/issue_172/test.proto new file mode 100644 index 00000000..fbd97be5 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_172/test.proto @@ -0,0 +1,6 @@ +syntax = "proto2"; +import "submessage.proto"; + +message testmessage { + optional submessage sub = 1; +} diff --git a/libs/nanopb/tests/regression/issue_188/SConscript b/libs/nanopb/tests/regression/issue_188/SConscript new file mode 100644 index 00000000..6bc32712 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_188/SConscript @@ -0,0 +1,6 @@ +# Regression test for issue with Enums inside OneOf. + +Import('env') + +env.NanopbProto('oneof') + diff --git a/libs/nanopb/tests/regression/issue_188/oneof.proto b/libs/nanopb/tests/regression/issue_188/oneof.proto new file mode 100644 index 00000000..e37f5c02 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_188/oneof.proto @@ -0,0 +1,29 @@ +syntax = "proto2"; + +message MessageOne +{ + required uint32 one = 1; + required uint32 two = 2; + required uint32 three = 3; + required int32 four = 4; +} + +enum EnumTwo +{ + SOME_ENUM_1 = 1; + SOME_ENUM_2 = 5; + SOME_ENUM_3 = 6; + SOME_ENUM_4 = 9; + SOME_ENUM_5 = 10; + SOME_ENUM_6 = 12; + SOME_ENUM_7 = 39; + SOME_ENUM_8 = 401; +} + +message OneofMessage +{ + oneof payload { + MessageOne message = 1; + EnumTwo enum = 2; + } +} diff --git a/libs/nanopb/tests/regression/issue_195/SConscript b/libs/nanopb/tests/regression/issue_195/SConscript new file mode 100644 index 00000000..78326d32 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_195/SConscript @@ -0,0 +1,10 @@ +# Regression test for Issue 195: Message size not calculated if a submessage includes +# bytes. Basically a non-working #define being generated. + +Import("env") + +env.NanopbProto(["test"]) +env.Object('test.pb.c') + +env.Match(['test.pb.h', 'test.expected']) + diff --git a/libs/nanopb/tests/regression/issue_195/test.expected b/libs/nanopb/tests/regression/issue_195/test.expected new file mode 100644 index 00000000..83ea7ab8 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_195/test.expected @@ -0,0 +1 @@ +/\* TestMessage_size depends diff --git a/libs/nanopb/tests/regression/issue_195/test.proto b/libs/nanopb/tests/regression/issue_195/test.proto new file mode 100644 index 00000000..7a77d69d --- /dev/null +++ b/libs/nanopb/tests/regression/issue_195/test.proto @@ -0,0 +1,8 @@ +message TestMessage { + required uint32 id = 1; + required bytes payload = 2; +} +message EncapsulatedMessage { + required uint32 id = 1; + required TestMessage test = 2; +} diff --git a/libs/nanopb/tests/regression/issue_203/SConscript b/libs/nanopb/tests/regression/issue_203/SConscript new file mode 100644 index 00000000..8b4d6cc7 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_203/SConscript @@ -0,0 +1,9 @@ +# Regression test for issue with multiple files generated at once + +Import('env') + +env.Command(['file1.pb.c', 'file1.pb.h', 'file2.pb.c', 'file2.pb.h'], ['file1.proto', 'file2.proto'], + env['NANOPB_PROTO_CMD']) + +env.Object('file1.pb.c') +env.Object('file2.pb.c') diff --git a/libs/nanopb/tests/regression/issue_203/file1.proto b/libs/nanopb/tests/regression/issue_203/file1.proto new file mode 100644 index 00000000..dae250b8 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_203/file1.proto @@ -0,0 +1,10 @@ +syntax = "proto2"; + +message SubMessage1 { + required int32 foo = 1; +} + +message Message1 { + required SubMessage1 bar = 1; +} + diff --git a/libs/nanopb/tests/regression/issue_203/file2.proto b/libs/nanopb/tests/regression/issue_203/file2.proto new file mode 100644 index 00000000..513b0f0d --- /dev/null +++ b/libs/nanopb/tests/regression/issue_203/file2.proto @@ -0,0 +1,10 @@ +syntax = "proto2"; + +message SubMessage2 { + required int32 foo = 1; +} + +message Message2 { + required SubMessage2 bar = 1; +} + diff --git a/libs/nanopb/tests/regression/issue_205/SConscript b/libs/nanopb/tests/regression/issue_205/SConscript new file mode 100644 index 00000000..ed8899dd --- /dev/null +++ b/libs/nanopb/tests/regression/issue_205/SConscript @@ -0,0 +1,14 @@ +# Check that pb_release() correctly handles corrupted size fields of +# static arrays. + +Import('env', 'malloc_env') + +env.NanopbProto('size_corruption') + +p = malloc_env.Program(["size_corruption.c", + "size_corruption.pb.c", + "$COMMON/pb_decode_with_malloc.o", + "$COMMON/pb_common_with_malloc.o", + "$COMMON/malloc_wrappers.o"]) +env.RunTest(p) + diff --git a/libs/nanopb/tests/regression/issue_205/size_corruption.c b/libs/nanopb/tests/regression/issue_205/size_corruption.c new file mode 100644 index 00000000..08cef457 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_205/size_corruption.c @@ -0,0 +1,12 @@ +#include "size_corruption.pb.h" +#include + +int main() +{ + MainMessage msg = MainMessage_init_zero; + msg.bar_count = (pb_size_t)-1; + pb_release(MainMessage_fields, &msg); + + return 0; +} + diff --git a/libs/nanopb/tests/regression/issue_205/size_corruption.proto b/libs/nanopb/tests/regression/issue_205/size_corruption.proto new file mode 100644 index 00000000..6c9c2453 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_205/size_corruption.proto @@ -0,0 +1,11 @@ +syntax = "proto2"; +import 'nanopb.proto'; + +message SubMessage { + repeated int32 foo = 1 [(nanopb).type = FT_POINTER]; +} + +message MainMessage { + repeated SubMessage bar = 1 [(nanopb).max_count = 5]; +} + diff --git a/libs/nanopb/tests/regression/issue_227/SConscript b/libs/nanopb/tests/regression/issue_227/SConscript new file mode 100644 index 00000000..10741240 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_227/SConscript @@ -0,0 +1,14 @@ +# Regression test for Issue 227:Using proto3 type fields can cause unaligned access +# NOTE: This test will only detect problems when run with clang sanitizer (which +# is done regularly by a jenkins run). + +Import('env') + +env.NanopbProto('unaligned_uint64') + +p = env.Program(["unaligned_uint64.c", + "unaligned_uint64.pb.c", + "$COMMON/pb_encode.o", + "$COMMON/pb_common.o"]) +env.RunTest(p) + diff --git a/libs/nanopb/tests/regression/issue_227/unaligned_uint64.c b/libs/nanopb/tests/regression/issue_227/unaligned_uint64.c new file mode 100644 index 00000000..17c1d779 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_227/unaligned_uint64.c @@ -0,0 +1,14 @@ +#include "unaligned_uint64.pb.h" +#include + +int main() +{ + uint8_t buf[128]; + pb_ostream_t stream = pb_ostream_from_buffer(buf, sizeof(buf)); + MainMessage msg = MainMessage_init_zero; + msg.bar[0] = 'A'; + pb_encode(&stream, MainMessage_fields, &msg); + + return 0; +} + diff --git a/libs/nanopb/tests/regression/issue_227/unaligned_uint64.proto b/libs/nanopb/tests/regression/issue_227/unaligned_uint64.proto new file mode 100644 index 00000000..f0269f60 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_227/unaligned_uint64.proto @@ -0,0 +1,8 @@ +syntax = "proto3"; +import 'nanopb.proto'; + +message MainMessage { + string foo = 1 [(nanopb).max_size = 3]; + string bar = 2 [(nanopb).max_size = 8]; +} + diff --git a/libs/nanopb/tests/regression/issue_229/SConscript b/libs/nanopb/tests/regression/issue_229/SConscript new file mode 100644 index 00000000..b0f8376d --- /dev/null +++ b/libs/nanopb/tests/regression/issue_229/SConscript @@ -0,0 +1,13 @@ +# Regression test for Issue 229: problem encoding message that has +# multiple oneof fields +Import('env') + +env.NanopbProto('multiple_oneof') + +p = env.Program(["multiple_oneof.c", + "multiple_oneof.pb.c", + "$COMMON/pb_decode.o", + "$COMMON/pb_encode.o", + "$COMMON/pb_common.o"]) +env.RunTest(p) + diff --git a/libs/nanopb/tests/regression/issue_229/multiple_oneof.c b/libs/nanopb/tests/regression/issue_229/multiple_oneof.c new file mode 100644 index 00000000..902248d0 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_229/multiple_oneof.c @@ -0,0 +1,35 @@ +#include "multiple_oneof.pb.h" +#include +#include +#include + +int main() +{ + int status = 0; + uint8_t buf[128]; + size_t msglen; + + { + pb_ostream_t stream = pb_ostream_from_buffer(buf, sizeof(buf)); + MainMessage msg = MainMessage_init_zero; + msg.which_oneof1 = MainMessage_oneof1_uint32_tag; + msg.oneof1.oneof1_uint32 = 1234; + msg.which_oneof2 = MainMessage_oneof2_uint32_tag; + msg.oneof2.oneof2_uint32 = 5678; + TEST(pb_encode(&stream, MainMessage_fields, &msg)); + msglen = stream.bytes_written; + } + + { + pb_istream_t stream = pb_istream_from_buffer(buf, msglen); + MainMessage msg = MainMessage_init_zero; + TEST(pb_decode(&stream, MainMessage_fields, &msg)); + TEST(msg.which_oneof1 == MainMessage_oneof1_uint32_tag); + TEST(msg.oneof1.oneof1_uint32 == 1234); + TEST(msg.which_oneof2 == MainMessage_oneof2_uint32_tag); + TEST(msg.oneof2.oneof2_uint32 == 5678); + } + + return status; +} + diff --git a/libs/nanopb/tests/regression/issue_229/multiple_oneof.proto b/libs/nanopb/tests/regression/issue_229/multiple_oneof.proto new file mode 100644 index 00000000..22373e1d --- /dev/null +++ b/libs/nanopb/tests/regression/issue_229/multiple_oneof.proto @@ -0,0 +1,11 @@ +syntax = "proto2"; + +message MainMessage { + oneof oneof1 { + uint32 oneof1_uint32 = 1; + } + oneof oneof2 { + uint32 oneof2_uint32 = 2; + } +} + diff --git a/libs/nanopb/tests/regression/issue_242/SConscript b/libs/nanopb/tests/regression/issue_242/SConscript new file mode 100644 index 00000000..000063ef --- /dev/null +++ b/libs/nanopb/tests/regression/issue_242/SConscript @@ -0,0 +1,13 @@ +# Regression test for Issue 242: pb_encode does not encode tag for +# extension fields that is all zeros +Import('env') + +env.NanopbProto('zero_value') + +p = env.Program(["zero_value.c", + "zero_value.pb.c", + "$COMMON/pb_decode.o", + "$COMMON/pb_encode.o", + "$COMMON/pb_common.o"]) +env.RunTest(p) + diff --git a/libs/nanopb/tests/regression/issue_242/zero_value.c b/libs/nanopb/tests/regression/issue_242/zero_value.c new file mode 100644 index 00000000..b3d96b7a --- /dev/null +++ b/libs/nanopb/tests/regression/issue_242/zero_value.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include +#include "zero_value.pb.h" + +int main() +{ + int status = 0; + + COMMENT("Test extension fields with zero values"); + { + uint8_t buffer[256] = {0}; + pb_ostream_t ostream; + int32_t value = 0; + Extendable source = {0}; + + pb_extension_t source_ext = {0}; + source_ext.type = &opt_int32; + source_ext.dest = &value; + source.extensions = &source_ext; + + ostream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + TEST(pb_encode(&ostream, Extendable_fields, &source)); + + TEST(ostream.bytes_written == 2); + TEST(memcmp(buffer, "\x58\x00", 2) == 0); + } + + /* Note: There never was a bug here, but this check is included + * in the regression test because the logic is closely related. + */ + COMMENT("Test pointer fields with zero values"); + { + uint8_t buffer[256] = {0}; + pb_ostream_t ostream; + int32_t value = 0; + PointerMessage source = {0}; + + source.opt_int32 = &value; + + ostream = pb_ostream_from_buffer(buffer, sizeof(buffer)); + TEST(pb_encode(&ostream, PointerMessage_fields, &source)); + + TEST(ostream.bytes_written == 2); + TEST(memcmp(buffer, "\x58\x00", 2) == 0); + } + + return status; +} + diff --git a/libs/nanopb/tests/regression/issue_242/zero_value.proto b/libs/nanopb/tests/regression/issue_242/zero_value.proto new file mode 100644 index 00000000..020a39a5 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_242/zero_value.proto @@ -0,0 +1,15 @@ +syntax = "proto2"; +import "nanopb.proto"; + +message Extendable { + extensions 10 to 100; +} + +extend Extendable { + optional int32 opt_int32 = 11; +} + +message PointerMessage { + optional int32 opt_int32 = 11 [(nanopb).type = FT_POINTER]; +} + diff --git a/libs/nanopb/tests/regression/issue_247/SConscript b/libs/nanopb/tests/regression/issue_247/SConscript new file mode 100644 index 00000000..b41e9f29 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_247/SConscript @@ -0,0 +1,14 @@ +# Test that pb_check_proto3_default_value() correctly skips padding +# bytes in submessage structures. + +Import("env") + +env.NanopbProto("padding") + +p = env.Program(["padding.c", + "padding.pb.c", + "$COMMON/pb_encode.o", + "$COMMON/pb_common.o"]) + +env.RunTest(p) + diff --git a/libs/nanopb/tests/regression/issue_247/padding.c b/libs/nanopb/tests/regression/issue_247/padding.c new file mode 100644 index 00000000..8860179d --- /dev/null +++ b/libs/nanopb/tests/regression/issue_247/padding.c @@ -0,0 +1,32 @@ +#include +#include +#include +#include "padding.pb.h" + +int main() +{ + int status = 0; + + TestMessage msg; + + /* Set padding bytes to garbage */ + memset(&msg, 0xAA, sizeof(msg)); + + /* Set all meaningful fields to 0 */ + msg.submsg.boolfield = false; + msg.submsg.intfield = 0; + + /* Test encoding */ + { + pb_byte_t buf[128] = {0}; + pb_ostream_t stream = pb_ostream_from_buffer(buf, sizeof(buf)); + TEST(pb_encode(&stream, TestMessage_fields, &msg)); + + /* Because all fields have zero values, proto3 encoder + * shouldn't write out anything. */ + TEST(stream.bytes_written == 0); + } + + return status; +} + diff --git a/libs/nanopb/tests/regression/issue_247/padding.proto b/libs/nanopb/tests/regression/issue_247/padding.proto new file mode 100644 index 00000000..20bddac3 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_247/padding.proto @@ -0,0 +1,12 @@ +syntax = "proto3"; +import "nanopb.proto"; + +message SubMessage { + bool boolfield = 1; + int64 intfield = 2; +} + +message TestMessage { + SubMessage submsg = 1; +} + diff --git a/libs/nanopb/tests/regression/issue_249/SConscript b/libs/nanopb/tests/regression/issue_249/SConscript new file mode 100644 index 00000000..ba667129 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_249/SConscript @@ -0,0 +1,12 @@ +# Regression test for Issue 249: proto3 mode pb_decode() corrupts callback fields +Import('env') + +env.NanopbProto('test') + +p = env.Program(["test.c", + "test.pb.c", + "$COMMON/pb_decode.o", + "$COMMON/pb_encode.o", + "$COMMON/pb_common.o"]) +env.RunTest(p) + diff --git a/libs/nanopb/tests/regression/issue_249/test.c b/libs/nanopb/tests/regression/issue_249/test.c new file mode 100644 index 00000000..a37180fd --- /dev/null +++ b/libs/nanopb/tests/regression/issue_249/test.c @@ -0,0 +1,59 @@ +#include "test.pb.h" +#include +#include +#include + +static bool write_array(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) +{ + int i; + for (i = 0; i < 5; i++) + { + if (!pb_encode_tag_for_field(stream, field)) + return false; + if (!pb_encode_varint(stream, 1000 + i)) + return false; + } + + return true; +} + +static bool read_array(pb_istream_t *stream, const pb_field_t *field, void **arg) +{ + uint32_t i; + int *sum = *arg; + + if (!pb_decode_varint32(stream, &i)) + return false; + + *sum += i; + + return true; +} + +int main() +{ + int status = 0; + pb_byte_t buf[128] = {0}; + pb_size_t msglen; + + { + MainMessage msg = MainMessage_init_zero; + pb_ostream_t stream = pb_ostream_from_buffer(buf, sizeof(buf)); + msg.submsg.foo.funcs.encode = &write_array; + TEST(pb_encode(&stream, MainMessage_fields, &msg)); + msglen = stream.bytes_written; + } + + { + MainMessage msg = MainMessage_init_zero; + pb_istream_t stream = pb_istream_from_buffer(buf, msglen); + int sum = 0; + msg.submsg.foo.funcs.decode = &read_array; + msg.submsg.foo.arg = ∑ + TEST(pb_decode(&stream, MainMessage_fields, &msg)); + TEST(sum == 1000 + 1001 + 1002 + 1003 + 1004); + } + + return status; +} + diff --git a/libs/nanopb/tests/regression/issue_249/test.proto b/libs/nanopb/tests/regression/issue_249/test.proto new file mode 100644 index 00000000..eaa2abde --- /dev/null +++ b/libs/nanopb/tests/regression/issue_249/test.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; + +message SubMessage { + repeated int32 foo = 1; +} + +message MainMessage { + SubMessage submsg = 1; +} + diff --git a/libs/nanopb/tests/regression/issue_253/SConscript b/libs/nanopb/tests/regression/issue_253/SConscript new file mode 100644 index 00000000..5a16948c --- /dev/null +++ b/libs/nanopb/tests/regression/issue_253/SConscript @@ -0,0 +1,15 @@ +# Regression test for Issue 253: Wrong calculated message maximum size + +Import('env') + +env.NanopbProto('short_array') + +p = env.Program(['short_array.c', + 'short_array.pb.c', + "$COMMON/pb_decode.o", + "$COMMON/pb_encode.o", + "$COMMON/pb_common.o"]) + +env.RunTest(p) + + diff --git a/libs/nanopb/tests/regression/issue_253/short_array.c b/libs/nanopb/tests/regression/issue_253/short_array.c new file mode 100644 index 00000000..5ed6c3f7 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_253/short_array.c @@ -0,0 +1,24 @@ +#include +#include +#include "short_array.pb.h" + +int main() +{ + int status = 0; + + COMMENT("Test message length calculation for short arrays"); + { + uint8_t buffer[TestMessage_size] = {0}; + pb_ostream_t ostream = pb_ostream_from_buffer(buffer, TestMessage_size); + TestMessage msg = TestMessage_init_zero; + + msg.rep_uint32_count = 1; + msg.rep_uint32[0] = (1 << 31); + + TEST(pb_encode(&ostream, TestMessage_fields, &msg)); + TEST(ostream.bytes_written == TestMessage_size); + } + + return status; +} + diff --git a/libs/nanopb/tests/regression/issue_253/short_array.proto b/libs/nanopb/tests/regression/issue_253/short_array.proto new file mode 100644 index 00000000..5a5d8a3d --- /dev/null +++ b/libs/nanopb/tests/regression/issue_253/short_array.proto @@ -0,0 +1,7 @@ +syntax = "proto2"; +import "nanopb.proto"; + +message TestMessage { + repeated uint32 rep_uint32 = 1 [(nanopb).max_count = 1]; +} + diff --git a/libs/nanopb/tests/regression/issue_256/SConscript b/libs/nanopb/tests/regression/issue_256/SConscript new file mode 100644 index 00000000..b2c3e864 --- /dev/null +++ b/libs/nanopb/tests/regression/issue_256/SConscript @@ -0,0 +1,16 @@ +# Regression test for Issue 256: Proto3 mode skips submessages even when +# later array fields have non-zero value + +Import('env') + +env.NanopbProto('submsg_array') + +p = env.Program(['submsg_array.c', + 'submsg_array.pb.c', + "$COMMON/pb_decode.o", + "$COMMON/pb_encode.o", + "$COMMON/pb_common.o"]) + +env.RunTest(p) + + diff --git a/libs/nanopb/tests/regression/issue_256/submsg_array.c b/libs/nanopb/tests/regression/issue_256/submsg_array.c new file mode 100644 index 00000000..c63bd30a --- /dev/null +++ b/libs/nanopb/tests/regression/issue_256/submsg_array.c @@ -0,0 +1,38 @@ +#include +#include +#include +#include "submsg_array.pb.h" + +int main() +{ + int status = 0; + + COMMENT("Test encoding for submessage with array"); + { + uint8_t buffer[TestMessage_size] = {0}; + pb_ostream_t ostream = pb_ostream_from_buffer(buffer, TestMessage_size); + TestMessage msg = TestMessage_init_zero; + + msg.submsg.rep_uint32_count = 3; + msg.submsg.rep_uint32[0] = 0; + msg.submsg.rep_uint32[1] = 1; + msg.submsg.rep_uint32[2] = 2; + + TEST(pb_encode(&ostream, TestMessage_fields, &msg)); + TEST(ostream.bytes_written > 0); + + { + pb_istream_t istream = pb_istream_from_buffer(buffer, ostream.bytes_written); + TestMessage msg2 = TestMessage_init_zero; + + TEST(pb_decode(&istream, TestMessage_fields, &msg2)); + TEST(msg2.submsg.rep_uint32_count == 3); + TEST(msg2.submsg.rep_uint32[0] == 0); + TEST(msg2.submsg.rep_uint32[1] == 1); + TEST(msg2.submsg.rep_uint32[2] == 2); + } + } + + return status; +} + diff --git a/libs/nanopb/tests/regression/issue_256/submsg_array.proto b/libs/nanopb/tests/regression/issue_256/submsg_array.proto new file mode 100644 index 00000000..4964a05f --- /dev/null +++ b/libs/nanopb/tests/regression/issue_256/submsg_array.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; +import "nanopb.proto"; + +message SubMessage { + repeated uint32 rep_uint32 = 1 [(nanopb).max_count = 3]; +} + +message TestMessage { + SubMessage submsg = 1; +} + diff --git a/libs/nanopb/tests/site_scons/site_init.py b/libs/nanopb/tests/site_scons/site_init.py new file mode 100644 index 00000000..da5f6d65 --- /dev/null +++ b/libs/nanopb/tests/site_scons/site_init.py @@ -0,0 +1,109 @@ +import subprocess +import sys +import re + +try: + # Make terminal colors work on windows + import colorama + colorama.init() +except ImportError: + pass + +def add_nanopb_builders(env): + '''Add the necessary builder commands for nanopb tests.''' + + # Build command that runs a test program and saves the output + def run_test(target, source, env): + if len(source) > 1: + infile = open(str(source[1])) + else: + infile = None + + if env.has_key("COMMAND"): + args = [env["COMMAND"]] + else: + args = [str(source[0])] + + if env.has_key('ARGS'): + args.extend(env['ARGS']) + + print 'Command line: ' + str(args) + pipe = subprocess.Popen(args, + stdin = infile, + stdout = open(str(target[0]), 'w'), + stderr = sys.stderr) + result = pipe.wait() + if result == 0: + print '\033[32m[ OK ]\033[0m Ran ' + args[0] + else: + print '\033[31m[FAIL]\033[0m Program ' + args[0] + ' returned ' + str(result) + return result + + run_test_builder = Builder(action = run_test, + suffix = '.output') + env.Append(BUILDERS = {'RunTest': run_test_builder}) + + # Build command that decodes a message using protoc + def decode_actions(source, target, env, for_signature): + esc = env['ESCAPE'] + dirs = ' '.join(['-I' + esc(env.GetBuildPath(d)) for d in env['PROTOCPATH']]) + return '$PROTOC $PROTOCFLAGS %s --decode=%s %s <%s >%s' % ( + dirs, env['MESSAGE'], esc(str(source[1])), esc(str(source[0])), esc(str(target[0]))) + + decode_builder = Builder(generator = decode_actions, + suffix = '.decoded') + env.Append(BUILDERS = {'Decode': decode_builder}) + + # Build command that encodes a message using protoc + def encode_actions(source, target, env, for_signature): + esc = env['ESCAPE'] + dirs = ' '.join(['-I' + esc(env.GetBuildPath(d)) for d in env['PROTOCPATH']]) + return '$PROTOC $PROTOCFLAGS %s --encode=%s %s <%s >%s' % ( + dirs, env['MESSAGE'], esc(str(source[1])), esc(str(source[0])), esc(str(target[0]))) + + encode_builder = Builder(generator = encode_actions, + suffix = '.encoded') + env.Append(BUILDERS = {'Encode': encode_builder}) + + # Build command that asserts that two files be equal + def compare_files(target, source, env): + data1 = open(str(source[0]), 'rb').read() + data2 = open(str(source[1]), 'rb').read() + if data1 == data2: + print '\033[32m[ OK ]\033[0m Files equal: ' + str(source[0]) + ' and ' + str(source[1]) + return 0 + else: + print '\033[31m[FAIL]\033[0m Files differ: ' + str(source[0]) + ' and ' + str(source[1]) + return 1 + + compare_builder = Builder(action = compare_files, + suffix = '.equal') + env.Append(BUILDERS = {'Compare': compare_builder}) + + # Build command that checks that each pattern in source2 is found in source1. + def match_files(target, source, env): + data = open(str(source[0]), 'rU').read() + patterns = open(str(source[1])) + for pattern in patterns: + if pattern.strip(): + invert = False + if pattern.startswith('! '): + invert = True + pattern = pattern[2:] + + status = re.search(pattern.strip(), data, re.MULTILINE) + + if not status and not invert: + print '\033[31m[FAIL]\033[0m Pattern not found in ' + str(source[0]) + ': ' + pattern + return 1 + elif status and invert: + print '\033[31m[FAIL]\033[0m Pattern should not exist, but does in ' + str(source[0]) + ': ' + pattern + return 1 + else: + print '\033[32m[ OK ]\033[0m All patterns found in ' + str(source[0]) + return 0 + + match_builder = Builder(action = match_files, suffix = '.matched') + env.Append(BUILDERS = {'Match': match_builder}) + + diff --git a/libs/nanopb/tests/site_scons/site_tools/nanopb.py b/libs/nanopb/tests/site_scons/site_tools/nanopb.py new file mode 100644 index 00000000..c72a45d3 --- /dev/null +++ b/libs/nanopb/tests/site_scons/site_tools/nanopb.py @@ -0,0 +1,126 @@ +''' +Scons Builder for nanopb .proto definitions. + +This tool will locate the nanopb generator and use it to generate .pb.c and +.pb.h files from the .proto files. + +Basic example +------------- +# Build myproto.pb.c and myproto.pb.h from myproto.proto +myproto = env.NanopbProto("myproto") + +# Link nanopb core to the program +env.Append(CPPPATH = "$NANOB") +myprog = env.Program(["myprog.c", myproto, "$NANOPB/pb_encode.c", "$NANOPB/pb_decode.c"]) + +Configuration options +--------------------- +Normally, this script is used in the test environment of nanopb and it locates +the nanopb generator by a relative path. If this script is used in another +application, the path to nanopb root directory has to be defined: + +env.SetDefault(NANOPB = "path/to/nanopb") + +Additionally, the path to protoc and the options to give to protoc can be +defined manually: + +env.SetDefault(PROTOC = "path/to/protoc") +env.SetDefault(PROTOCFLAGS = "--plugin=protoc-gen-nanopb=path/to/protoc-gen-nanopb") +''' + +import SCons.Action +import SCons.Builder +import SCons.Util +import os.path + +class NanopbWarning(SCons.Warnings.Warning): + pass +SCons.Warnings.enableWarningClass(NanopbWarning) + +def _detect_nanopb(env): + '''Find the path to nanopb root directory.''' + if env.has_key('NANOPB'): + # Use nanopb dir given by user + return env['NANOPB'] + + p = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) + if os.path.isdir(p) and os.path.isfile(os.path.join(p, 'pb.h')): + # Assume we are running under tests/site_scons/site_tools + return p + + raise SCons.Errors.StopError(NanopbWarning, + "Could not find the nanopb root directory") + +def _detect_protoc(env): + '''Find the path to the protoc compiler.''' + if env.has_key('PROTOC'): + # Use protoc defined by user + return env['PROTOC'] + + n = _detect_nanopb(env) + p1 = os.path.join(n, 'generator-bin', 'protoc' + env['PROGSUFFIX']) + if os.path.exists(p1): + # Use protoc bundled with binary package + return env['ESCAPE'](p1) + + p = env.WhereIs('protoc') + if p: + # Use protoc from path + return env['ESCAPE'](p) + + raise SCons.Errors.StopError(NanopbWarning, + "Could not find the protoc compiler") + +def _detect_protocflags(env): + '''Find the options to use for protoc.''' + if env.has_key('PROTOCFLAGS'): + return env['PROTOCFLAGS'] + + p = _detect_protoc(env) + n = _detect_nanopb(env) + p1 = os.path.join(n, 'generator-bin', 'protoc' + env['PROGSUFFIX']) + if p == env['ESCAPE'](p1): + # Using the bundled protoc, no options needed + return '' + + e = env['ESCAPE'] + if env['PLATFORM'] == 'win32': + return e('--plugin=protoc-gen-nanopb=' + os.path.join(n, 'generator', 'protoc-gen-nanopb.bat')) + else: + return e('--plugin=protoc-gen-nanopb=' + os.path.join(n, 'generator', 'protoc-gen-nanopb')) + +def _nanopb_proto_actions(source, target, env, for_signature): + esc = env['ESCAPE'] + dirs = ' '.join(['-I' + esc(env.GetBuildPath(d)) for d in env['PROTOCPATH']]) + return '$PROTOC $PROTOCFLAGS %s --nanopb_out=. %s' % (dirs, esc(str(source[0]))) + +def _nanopb_proto_emitter(target, source, env): + basename = os.path.splitext(str(source[0]))[0] + target.append(basename + '.pb.h') + + if os.path.exists(basename + '.options'): + source.append(basename + '.options') + + return target, source + +_nanopb_proto_builder = SCons.Builder.Builder( + generator = _nanopb_proto_actions, + suffix = '.pb.c', + src_suffix = '.proto', + emitter = _nanopb_proto_emitter) + +def generate(env): + '''Add Builder for nanopb protos.''' + + env['NANOPB'] = _detect_nanopb(env) + env['PROTOC'] = _detect_protoc(env) + env['PROTOCFLAGS'] = _detect_protocflags(env) + + env.SetDefault(PROTOCPATH = ['.', os.path.join(env['NANOPB'], 'generator', 'proto')]) + + env.SetDefault(NANOPB_PROTO_CMD = '$PROTOC $PROTOCFLAGS --nanopb_out=. $SOURCES') + env['BUILDERS']['NanopbProto'] = _nanopb_proto_builder + +def exists(env): + return _detect_protoc(env) and _detect_protoc_opts(env) + diff --git a/libs/nanopb/tests/special_characters/SConscript b/libs/nanopb/tests/special_characters/SConscript new file mode 100644 index 00000000..2309cf2e --- /dev/null +++ b/libs/nanopb/tests/special_characters/SConscript @@ -0,0 +1,6 @@ +# Test that special characters in .proto filenames work. + +Import('env') + +env.NanopbProto("funny-proto+name has.characters.proto") +env.Object("funny-proto+name has.characters.pb.c") diff --git a/libs/nanopb/tests/special_characters/funny-proto+name has.characters.proto b/libs/nanopb/tests/special_characters/funny-proto+name has.characters.proto new file mode 100644 index 00000000..26b2cb1b --- /dev/null +++ b/libs/nanopb/tests/special_characters/funny-proto+name has.characters.proto @@ -0,0 +1 @@ +syntax="proto2"; diff --git a/libs/nanopb/tests/splint/SConscript b/libs/nanopb/tests/splint/SConscript new file mode 100644 index 00000000..cd4b5b9d --- /dev/null +++ b/libs/nanopb/tests/splint/SConscript @@ -0,0 +1,16 @@ +# Check the nanopb core using splint + +Import('env') + +p = env.WhereIs('splint') + +if p: + env.Command('pb_decode.splint', '$NANOPB/pb_decode.c', + 'splint -f splint/splint.rc $SOURCE 2> $TARGET') + + env.Command('pb_encode.splint', '$NANOPB/pb_encode.c', + 'splint -f splint/splint.rc $SOURCE 2> $TARGET') + + env.Command('pb_common.splint', '$NANOPB/pb_common.c', + 'splint -f splint/splint.rc $SOURCE 2> $TARGET') + diff --git a/libs/nanopb/tests/splint/splint.rc b/libs/nanopb/tests/splint/splint.rc new file mode 100644 index 00000000..e47d3c21 --- /dev/null +++ b/libs/nanopb/tests/splint/splint.rc @@ -0,0 +1,37 @@ ++checks ++partial ++matchanyintegral ++strictlib +-nullassign +-predboolint +-predboolptr ++ptrnegate +-switchloopbreak ++ignoresigns +-infloopsuncon +-type + +# splint's memory checks don't quite work without annotations +-mustfreeonly +-compmempass +-nullret +-observertrans +-statictrans +-compdestroy +-nullpass +-nullstate +-compdef +-usereleased +-temptrans +-dependenttrans +-kepttrans +-branchstate +-immediatetrans +-mustfreefresh + +# These tests give false positives, compiler typically has +# better warnings for these. +-noret +-noeffect +-usedef + diff --git a/libs/nanopb/tools/make_linux_package.sh b/libs/nanopb/tools/make_linux_package.sh new file mode 100755 index 00000000..aea1c567 --- /dev/null +++ b/libs/nanopb/tools/make_linux_package.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +# Run this script in the top nanopb directory to create a binary package +# for Linux users. + +set -e +set -x + +VERSION=`git describe --always`-linux-x86 +DEST=dist/$VERSION + +rm -rf $DEST +mkdir -p $DEST + +# Export the files from newest commit +git archive HEAD | tar x -C $DEST + +# Rebuild the Python .proto files +make -BC $DEST/generator/proto + +# Make the nanopb generator available as a protoc plugin +cp $DEST/generator/nanopb_generator.py $DEST/generator/protoc-gen-nanopb.py + +# Package the Python libraries +( cd $DEST/generator; bbfreeze nanopb_generator.py protoc-gen-nanopb.py ) +mv $DEST/generator/dist $DEST/generator-bin + +# Remove temp file +rm $DEST/generator/protoc-gen-nanopb.py + +# Package the protoc compiler +cp `which protoc` $DEST/generator-bin/protoc.bin +LIBPROTOC=$(ldd `which protoc` | grep -o '/.*libprotoc[^ ]*') +LIBPROTOBUF=$(ldd `which protoc` | grep -o '/.*libprotobuf[^ ]*') +cp $LIBPROTOC $LIBPROTOBUF $DEST/generator-bin/ +cat > $DEST/generator-bin/protoc << EOF +#!/bin/bash +SCRIPTDIR=\$(dirname "\$0") +export LD_LIBRARY_PATH=\$SCRIPTDIR +export PATH=\$SCRIPTDIR:\$PATH +exec "\$SCRIPTDIR/protoc.bin" "\$@" +EOF +chmod +x $DEST/generator-bin/protoc + +# Remove debugging symbols to reduce size of package +( cd $DEST/generator-bin; strip *.so *.so.* ) + +# Tar it all up +( cd dist; tar -czf $VERSION.tar.gz $VERSION ) + diff --git a/libs/nanopb/tools/make_mac_package.sh b/libs/nanopb/tools/make_mac_package.sh new file mode 100755 index 00000000..32bba5cc --- /dev/null +++ b/libs/nanopb/tools/make_mac_package.sh @@ -0,0 +1,49 @@ +#!/bin/bash + +# Run this script in the top nanopb directory to create a binary package +# for Mac OS X users. + +# Requires: protobuf, python-protobuf, pyinstaller + +set -e +set -x + +VERSION=`git describe --always`-macosx-x86 +DEST=dist/$VERSION + +rm -rf $DEST +mkdir -p $DEST + +# Export the files from newest commit +git archive HEAD | tar x -C $DEST + +# Rebuild the Python .proto files +make -BC $DEST/generator/proto + +# Package the Python libraries +( cd $DEST/generator; pyinstaller nanopb_generator.py ) +mv $DEST/generator/dist/nanopb_generator $DEST/generator-bin + +# Remove temp files +rm -rf $DEST/generator/dist $DEST/generator/build $DEST/generator/nanopb_generator.spec + +# Make the nanopb generator available as a protoc plugin +cp $DEST/generator-bin/nanopb_generator $DEST/generator-bin/protoc-gen-nanopb + +# Package the protoc compiler +cp `which protoc` $DEST/generator-bin/protoc.bin +LIBPROTOC=$(otool -L `which protoc` | grep -o '/.*libprotoc[^ ]*') +LIBPROTOBUF=$(otool -L `which protoc` | grep -o '/.*libprotobuf[^ ]*') +cp $LIBPROTOC $LIBPROTOBUF $DEST/generator-bin/ +cat > $DEST/generator-bin/protoc << EOF +#!/bin/bash +SCRIPTDIR=\$(dirname "\$0") +export DYLD_LIBRARY_PATH=\$SCRIPTDIR +export PATH=\$SCRIPTDIR:\$PATH +exec "\$SCRIPTDIR/protoc.bin" "\$@" +EOF +chmod +x $DEST/generator-bin/protoc + +# Tar it all up +( cd dist; tar -czf $VERSION.tar.gz $VERSION ) + diff --git a/libs/nanopb/tools/make_windows_package.sh b/libs/nanopb/tools/make_windows_package.sh new file mode 100755 index 00000000..72de6f33 --- /dev/null +++ b/libs/nanopb/tools/make_windows_package.sh @@ -0,0 +1,55 @@ +#!/bin/bash + +# Run this script in the top nanopb directory to create a binary package +# for Windows users. This script is designed to run under MingW/MSYS bash +# and requires the following tools: git, make, zip, unix2dos + +set -e +set -x + +VERSION=`git describe --always`-windows-x86 +DEST=dist/$VERSION + +rm -rf $DEST +mkdir -p $DEST + +# Export the files from newest commit +git archive HEAD | tar x -C $DEST + +# Rebuild the Python .proto files +make -BC $DEST/generator/proto + +# Make the nanopb generator available as a protoc plugin +cp $DEST/generator/nanopb_generator.py $DEST/generator/protoc-gen-nanopb.py + +# Package the Python libraries +( cd $DEST/generator; bbfreeze nanopb_generator.py protoc-gen-nanopb.py ) +mv $DEST/generator/dist $DEST/generator-bin + +# Remove temp file +rm $DEST/generator/protoc-gen-nanopb.py + +# The python interpreter requires MSVCR90.dll. +# FIXME: Find a way around hardcoding this path +cp /c/windows/winsxs/x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4974_none_50940634bcb759cb/MSVCR90.DLL $DEST/generator-bin/ +cat > $DEST/generator-bin/Microsoft.VC90.CRT.manifest < + + + + KSaO8M0iCtPF6YEr79P1dZsnomY= ojDmTgpYMFRKJYkPcM6ckpYkWUU= tVogb8kezDre2mXShlIqpp8ErIg= + +EOF + +# Package the protoc compiler +cp `which protoc.exe` $DEST/generator-bin/ +cp `which MSVCR100.DLL` $DEST/generator-bin/ +cp `which MSVCP100.DLL` $DEST/generator-bin/ + +# Convert line breaks for convenience +find $DEST -name '*.c' -o -name '*.h' -o -name '*.txt' \ + -o -name '*.proto' -o -name '*.py' -o -name '*.options' \ + -exec unix2dos '{}' \; + +# Zip it all up +( cd dist; zip -r $VERSION.zip $VERSION ) diff --git a/libs/nanopb/tools/set_version.sh b/libs/nanopb/tools/set_version.sh new file mode 100755 index 00000000..729ca0d7 --- /dev/null +++ b/libs/nanopb/tools/set_version.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +# Run this from the top directory of nanopb tree. +# e.g. user@localhost:~/nanopb$ tools/set_version.sh nanopb-0.1.9-dev +# It sets the version number in pb.h and generator/nanopb_generator.py. + +sed -i -e 's/nanopb_version\s*=\s*"[^"]*"/nanopb_version = "'$1'"/' generator/nanopb_generator.py +sed -i -e 's/#define\s*NANOPB_VERSION\s*.*/#define NANOPB_VERSION '$1'/' pb.h +sed -i -e 's/set(\s*nanopb_VERSION_STRING\s*[^)]*)/set(nanopb_VERSION_STRING '$1')/' CMakeLists.txt + +VERSION_ONLY=$(echo $1 | sed 's/nanopb-//') +sed -i -e 's/"version":\s*"[^"]*"/"version": "'$VERSION_ONLY'"/' library.json + diff --git a/libs/openxc-message-format/.gitignore b/libs/openxc-message-format/.gitignore new file mode 100644 index 00000000..b25c15b8 --- /dev/null +++ b/libs/openxc-message-format/.gitignore @@ -0,0 +1 @@ +*~ diff --git a/libs/openxc-message-format/CHANGELOG.md b/libs/openxc-message-format/CHANGELOG.md new file mode 100644 index 00000000..294826cd --- /dev/null +++ b/libs/openxc-message-format/CHANGELOG.md @@ -0,0 +1,57 @@ +# OpenXC Message Format Changelog + +## v0.7.0 + +* Improvement: Increase diagnostic response payload size to accommodate + multi-frame diagnostic responses. +* Feature: Added command to get device's platform + +## v0.6.0 + +* Feature: Added MessagePack support for BTLE connections. +* Feature: Support for vehicle message timestamps (changed previous uptime). +* Feature: Support for C5 SD Card. +* Feature: Support for C5 RTC. +* Fix: Update submodule from code.google to github. + +## v0.5.0 + +* Feature: Support for C5 Cellular device. New uptime message. + +## v0.4 + +* BREAKING: Removed factor and offset from diagnostic requests to minimize the number of + fields, and since this is such an uncommon use case and one that can be + handled by the client receiving the data. We may add them back in the future. +* BREAKING: Require an 'action' to diagnostic request commands, e.g. cancel or add. +* BREAKING: Rename "raw" messages to the more precise "CAN messages". +* BREAKING: Rename "translated" messages to "simple messages". +* BREAKING: Remove redundant `type` field from simple messages (formerly + translated messages). The type can be inferred implicitly through the types of + the value and event fields. +* Feature: Add a command for controlling CAN message passthrough. +* Feature: Add a command for controlling CAN controller acceptance filter bypass. +* Feature: Add a command to change the payload format. +* Feature: Add a command to control whether pre-defined, recurring OBD-II + requests are enabled. +* Improvement: Add `extras` field to JSON messages. +* Improvement: Add an optional 'status' field to all command responses. +* Improvement: Build protobuf generated files with nanopb v0.3.1. +* Improvement: Allow explicitly setting CAN message frame format (i.e. standard + or extended frame). +* Fix: Expand range of mode field to a full byte (#10) + +## v0.3 + +* Add diagnostic message request/response format. +* Officially add Protcol Buffer encoding. +* Change JSON delimiter to ```\0``` for both input and output. +* Officially document version and device ID commands. + +## v0.2 + +* Add a RAW can message format. + +## v0.1 + +* Initial release. diff --git a/libs/openxc-message-format/CMakeLists.txt b/libs/openxc-message-format/CMakeLists.txt new file mode 100644 index 00000000..f6964e8a --- /dev/null +++ b/libs/openxc-message-format/CMakeLists.txt @@ -0,0 +1,43 @@ +########################################################################### +# Copyright 2015, 2016, 2017 IoT.bzh +# +# author: Fulup Ar Foll +# contrib: Romain Forlot +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +########################################################################### + +# Add target to project dependency list +PROJECT_TARGET_ADD(openxc-message-format) + + # Define project Target + add_library(${TARGET_NAME} STATIC + gen/cpp/openxc.pb.c + ${PROJECT_LIBDIR}/nanopb/pb_encode.c + ${PROJECT_LIBDIR}/nanopb/pb_decode.c + ${PROJECT_LIBDIR}/nanopb/pb_common.c) + + # Binder exposes a unique public entry point + SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + OUTPUT_NAME ${TARGET_NAME} + ) + + # Define target includes + TARGET_INCLUDE_DIRECTORIES(${TARGET_NAME} + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/gen/cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../nanopb + ) + + # Library dependencies (include updates automatically) + TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${link_libraries}) diff --git a/libs/openxc-message-format/JSON.mkd b/libs/openxc-message-format/JSON.mkd new file mode 100644 index 00000000..d320aad0 --- /dev/null +++ b/libs/openxc-message-format/JSON.mkd @@ -0,0 +1,435 @@ +# OpenXC JSON Message Format + +Each JSON message published by a VI is delimited with a `\0 ` character. + +## Table of Contents +1. [Vehicle Messages](#vehicle-messages) +2. [CAN Message](#can-message) +3. [Diagnostic Message](#diagnostic-message) +4. [Commands](#commands) +5. [Extra Values](#extra-values) + +## Vehicle Messages + +### Simple Vehicle Message + +There may not be a 1:1 relationship between input and output signals - i.e. +engine timing CAN signals may be summarized in an "engine performance" metric on +the abstract side of the interface. + +The expected format of a single valued message is: + + {"name": "steering_wheel_angle", "value": 45} + +### Evented Simple Vehicle Message + +The expected format of an event message is: + + {"name": "button_event", "value": "up", "event": "pressed"} + +This format is good for something like a button event, where there are two +discrete pieces of information in the measurement. + +## CAN Message + +The format for a plain CAN message: + + {"bus": 1, "id": 1234, "data": "0x12345678"} + +**bus** - the numerical identifier of the CAN bus where this message originated, + most likely 1 or 2 (for a vehicle interface with 2 CAN controllers). + +**id** - the CAN message ID + +**data** - up to 8 bytes of data from the CAN message's payload, represented as + a hexidecimal number in a string. Many JSON parser cannot handle 64-bit + integers, which is why we are not using a numerical data type. Each byte in + the string *must* be represented with 2 characters, e.g. `0x1` is `0x01` - the + complete string must have an even number of characters. The `0x` prefix is + optional. + +**format** - (optional) explicitly set the frame format for the CAN message, one + of `standard` or `extended`. If the `id` is greater than `0x7ff`, the extended + frame format will be selected automatically. + +## Diagnostic Message + +### Requests + +A diagnostic request is added or cancelled with a JSON object like this example: + + { "command": "diagnostic_request", + "action": "add", + "diagnostic_request": { + "bus": 1, + "message_id": 1234, + "mode": 1, + "pid": 5, + "payload": "0x1234", + "multiple_responses": false, + "frequency": 1, + "name": "my_pid" + } + } + } + +* The `command` must be `diagnostic_request.` +* The `action` must be included, and must be one of: + * `add` - create a new one-off or recurring diagnostic request. + * `cancel` - cancel an existing request. +* The details of the request must be included in the `request` field, using + the sub-fields defined below. + +A diagnostic request's `bus`, `id`, `mode` and `pid` (or lack of a `pid`) +combine to create a unique key to identify a request. These four fields will be +referred to as the key of the diagnostic request. For example, to create a +simple one-time diagnostic request: + + { "command": "diagnostic_request", + "action": "add", + "diagnostic_request": { + "bus": 1, + "message_id": 1234, + "mode": 1, + "pid": 5 + } + } + } + +Requests are completed after any responses are received (unless +`multiple_responses` is set), or the request has timed out after a certain +number of seconds. After a request is completed, you can re-`create` the same +key to make another request. + +Requests with a `frequency` are added as *recurring* requests, e.g. to add the +previous example as a recurring request at 1Hz: + + { "command": "diagnostic_request", + "action": "add", + "diagnostic_request": { + "bus": 1, + "message_id": 1234, + "mode": 1, + "pid": 5, + "frequency": 1 + } + } + } + +To cancel a recurring request, send a `cancel` action with the same key, e.g.: + + { "command": "diagnostic_request", + "action": "cancel", + "diagnostic_request": { + "bus": 1, + "message_id": 1234, + "mode": 1, + "pid": 5 + } + } + } + +Simultaneous recurring requests for the same key at different rates (e.g. 1Hz +*and* 2Hz) is not supported. However, non-recurring ("one-off") requests may +exist in parallel with a recurring request for the same key. + +**bus** - the numerical identifier of the CAN bus where this request should be + sent, most likely 1 or 2 (for a vehicle interface with 2 CAN controllers). + +**message_id** - the CAN message ID for the request. + +**mode** - the OBD-II mode of the request - 0x1 through 0xff (1 through 9 are the + standardized modes and 0x22 is a common proprietary mode). + +**pid** - (optional) the PID for the request, if applicable. + +**payload** - (optional) up to 7 bytes of data for the request's payload + represented as a hexadecimal number in a string. Many JSON parser cannot + handle 64-bit integers, which is why we are not using a numerical data type. + Each byte in the string *must* be represented with 2 characters, e.g. `0x1` + is `0x01` - the complete string must have an even number of characters. The + `0x` prefix is optional. + +**name** - (optional, defaults to nothing) A human readable, string name for + this request. If provided, the response will have a `name` field (much like a + simple vehicle message) with this value in place of `bus`, `id`, `mode` and + `pid`. + +**multiple_responses** - (optional, false by default) if true, request will stay + active for a full 100ms, even after receiving a diagnostic response message. + This is useful for requests to the functional broadcast message ID + (`0x7df`) when you need to get responses from multiple modules. It's possible + to set this to `true` for non-broadcast requests, but in practice you won't + see any additional responses after the first and it will just take up memory + in the VI for longer. + +**frequency** - (optional) Make this request a recurring request, at a this + frequency in Hz. To send a single non-recurring request, leave this field out. + +**decoded_type** - (optional, defaults to "obd2" if the request is a recognized +OBD-II mode 1 request, otherwise "none") If specified, the valid values are +`"none"` and `"obd2"`. If `obd2`, the payload will be decoded according to the +OBD-II specification and returned in the `value` field. Set this to `none` to +manually override the OBD-II decoding feature for a known PID. + +### Responses + +Requests to add or cancel a diagnostic request are first acknowledged by the VI, +before any responses to the request are returned. The response uses the standard +command response format: + + { "command_response": "diagnostic_request", "status": true} + +**status** - true if the request was successfully created or cancelled. + +When a node on the network response to the request and the result is published +by the VI, the result looks like: + + {"bus": 1, + "message_id": 1234, + "mode": 1, + "pid": 5, + "success": true, + "payload": "0x1234", + "value": 4660} + +and to an unsuccessful request, with the `negative_response_code` and no `pid` +echo: + + {"bus": 1, + "message_id": 1234, + "mode": 1, + "success": false, + "negative_response_code": 17} + +**bus** - the numerical identifier of the CAN bus where this response was + received. + +**message_id** - the CAN message ID for this response. + +**mode** - the OBD-II mode of the original diagnostic request. + +**pid** - (optional) the PID for the request, if applicable. + +**success** - true if the response received was a positive response. If this + field is false, the remote node returned an error and the + `negative_response_code` field should be populated. + +**negative_response_code** - (optional) If requested node returned an error, + `success` will be `false` and this field will contain the negative response + code (NRC). + +Finally, the `payload` and `value` fields are mutually exclusive: + +**payload** - (optional) up to 7 bytes of data returned in the response, + represented as a hexadecimal number in a string. Many JSON parser cannot + handle 64-bit integers, which is why we are not using a numerical data type. + +**value** - (optional) if the response had a payload, this may be the + payload interpreted as an integer. + +The response to a simple PID request would look like this: + + {"success": true, "bus": 1, "message_id": 1234, "mode": 1, "pid": 5, "payload": "0x2"} + +## Commands + +In addition to the `diagnostic_request` command described earlier, there are +other possible values for the `command` field. + +All commands immediately return a `command_response`, e.g.: + + { "command_response": "version", "message": "v6.0-dev (default)", "status": true} + +**command_response** - an echo of the command this is a ACKing. + +**status** - true if the command was understood and performed succesfully. + +**message** - (optional) a string message from the VI, e.g. to return a version + descriptor or error message. + +### Version Query + +The `version` command triggers the VI to inject a firmware version identifier +response into the outgoing data stream. + +**Request** + + { "command": "version"} + +**Response** + + { "command_response": "version", "message": "v6.0-dev (default)", "status": true} + +### Device ID Query + +The `device_id` command triggers the VI to inject a unique device ID (e.g. the +MAC address of an included Bluetooth module) into into the outgoing data stream. + +If no device ID is available, the response message will be "Unknown". + +**Request** + + { "command": "device_id"} + +**Response** + + { "command_response": "device_id", "message": "0012345678", "status": true} + +### Passthrough CAN Mode + +The `passthrough` command controls whether low-level CAN messages are passed +through from the CAN bus through the VI to the output stream. If the CAN +acceptance filter is in bypass mode and passthrough is enabled, the output +stream will include all received CAN messages. If the bypass filter is enabled, +only those CAN messages that have been pre-defined in the firmware are +forwarded. + +**Request** + + { "command": "passthrough", + "bus": 1, + "enabled": true + } + +**Response** + +If the bus in the request was valid and the passthrough mode was changed, the +`status` field in the response will be `true`. If `false`, the passthrough mode +was not changed. + + { "command_response": "passthrough", "status": true} + +### Acceptance Filter Bypass + +The `af_bypass` command controls whether the CAN message acceptance filter is +bypassed for each CAN controller. By default, hardware acceptance filter (AF) is +enabled in the VI - only previously defined CAN message IDs will be received. +Send this command with `bypass: true` to force the filters to bypassed. + +If `passthrough` mode is also enabled, when the AF is bypassed, the output will +include all CAN messages received. + +**Request** + + { "command": "af_bypass", + "bus": 1, + "bypass": true + } + +**Response** + +If the bus in the request was valid and the AF mode was changed, the `status` +field in the response will be `true`. If `false`, the passthrough mode was not +changed. + + { "command_response": "af_bypass", "status": true} + +### Payload Format Control + +The `payload_format` command determines the format for output data from the VI +and the expected format of commands sent to the VI. + +Valid formats are `json` and `protobuf`. + +**Request** + + { "command": "payload_format", + "format": "json" + } + +**Response** + +If the format was changed successfully, the `status` in the response will be +`true`. The response will be in the original message format, and all subsequent +messages will be in the new format. + + { "command_response": "payload_format", "status": true} + +### Automatic Pre-Defined OBD-II PID Requests + +The `predefined_obd2` command enables and disables the querying for and +translating of a set of pre-defined OBD-II PIDs from the attached vehicle. When +enabled, the VI will query the vehicle to see if these PIDs are claimed to be +supported and for those that are, it will set up recurring requests. The +responses will be output as simple vehicle messages, with the names defined in +the "Signals Defined from Diagnostic Messages" section below. + +**Request** + + { "command": "predefined_obd2", + "enabled": true + } + +**Response** + +If the predefined requests were enabled or disabled successfully, the `status` in +the response will be `true`. + + { "command_response": "predefined_obd2", "status": true} + +### C5 Cellular Configuration + +The ModemConfigurationCommand message allows users to change certain aspects of modem operation on-the-fly (at runtime). The modem configuration settings are stored in flash memory and are untouched by the bootloader during a software update (assuming the correct cellular_c5 linker file is used during compilation of vi-firmware). Thus, new modem settings persistent across power cycles. + +The ModemConfigurationCommand message provides three sub-messages for particular groups of modem settings. These are NetworkOperatorSettings, NetworkDataSettings, and ServerConnectSettings. These configuration messages are described in great detail within the [c5_cellular_config](https://github.com/openxc/vi-firmware/docs/advanced/c5_cell_config.html) documentation. + +Currently, only the ServerConnectSettings sub-message is supported in the vi-firmware's command interpreter. All other settings are currently compile-time only. + +The ServerConnectSettings part of ModemConfigurationCommand allows the user to set the host server name and port that the device will use when opening a TCP socket to upload data. This destination must be running an HTTP server similar to [OpenXCWebServer](https://github.com/openxc/openxc-azure-webserver), which defines a set of supported HTTP transactions where the body is comprised of data in the familiar OpenXC Message Format. + +**Request** + + { "command": "modem_configuration", + "server": { + "host": "www.myhost.com", + "port": 10000 + } + } + +**Response** + + { "command_response": "modem_configuration", "status": true} + +## C5 SD Card Status + +In order to check the status of the SD card, the following command is available: + + { "command": "sd_mount_status"} + +Command response if the SD card is mounted correctly: + + { "command_response": "sd_mount_status", "status": true} + +If the SD card is full, not enabled, or connected as a MSD, the device will respond with: + + { "command_response": "sd_mount_status", "status": false} + +For more info see [c5_msd](https://github.com/openxc/vi-firmware/docs/advanced/msd.html). + +## C5 RTC Configuration + +To set the current time of the RTC, the following + + { "command": "rtc_configuration", "unix_time": "1448551563"} + +The response is + + { "command_response": "rtc_configuration", "status": true} + +For more info see [c5_rtc](https://github.com/openxc/vi-firmware/docs/advanced/rtc.html). + +## Extra Values + +Any of the following JSON objects may optionally include an `extras` +field. The value may be any valid JSON object or array. The client libraries +will do their best to parse this information into a generic format and pass it +to your application. For example: + + {"name": "steering_wheel_angle", + "value": 45, + "extras": { + "calibrated": false + } + } + diff --git a/libs/openxc-message-format/LICENSE b/libs/openxc-message-format/LICENSE new file mode 100644 index 00000000..9a30ce45 --- /dev/null +++ b/libs/openxc-message-format/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2012 Ford Motor Company +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/libs/openxc-message-format/Makefile b/libs/openxc-message-format/Makefile new file mode 100644 index 00000000..7b968e63 --- /dev/null +++ b/libs/openxc-message-format/Makefile @@ -0,0 +1,11 @@ +nanopb: proto + make -C libs/nanopb/generator/proto + python libs/nanopb/generator/nanopb_generator.py gen/cpp/openxc.pb -f openxc.options + +proto: openxc.proto + @mkdir -p gen/java + @mkdir -p gen/python + @mkdir -p gen/cpp + protoc -I . -I gen -ogen/cpp/openxc.pb --python_out=gen/python --java_out=gen/java $? + +all: nanopb proto diff --git a/libs/openxc-message-format/README.md b/libs/openxc-message-format/README.md new file mode 100644 index 00000000..77758b83 --- /dev/null +++ b/libs/openxc-message-format/README.md @@ -0,0 +1,177 @@ +# OpenXC Message Format Specification + +Version: v0.6.0 + +This specification is a part of the [OpenXC platform][OpenXC]. + +An OpenXC vehicle interface sends generic vehicle data over one or more output +interfaces (e.g. USB or Bluetooth) as JSON or Protocol Buffers (protobuf). + +## JSON + +The JSON format is the most flexible and easiest to use. The format is fully +specified in the [JSON.mkd](JSON.mkd) file in this repository. +a more flexible option than binary, but is less compact and +therefore takes more bandwidth and processing power. + +The JSON format is best for most developers, as it is fairly efficient and very +flexible. + +## Binary (Protocol Buffers) + +The binary format is encoded using [Google Protocol +Buffers](https://code.google.com/p/protobuf/). The format is specified in the +file [openxc.proto](openxc.proto). The descriptions of the messages can be foud +in the JSON specs - the binary format mirrors this. + +The binary messages are published by the VI using the standard length-delimited +method (any protobuf library should support this). + +The binary format is best if you need to maximize the amount of data that can be +sent from the VI, trading off flexibility for efficiency. + +## Message Pack +MessagePack is an efficient binary serialization format. It lets you exchange data +among multiple languages like JSON, but it's faster and smaller. Small integers are +encoded into a single byte, and typical short strings require only one extra byte +in addition to the strings themselves + +For protocol specification visit: +https://github.com/msgpack/msgpack/blob/master/spec.md + +We are using the following lib: +https://github.com/camgunz/cmp + +MessagePack provides a binary alternative to ProtoBuf. There are pros & cons to each +so you can decide what works best for your project. + +## Trace File Format + +An OpenXC vehicle trace file is a plaintext file that contains JSON objects, +separated by newlines (which may be either `\r\n` or `\n`, depending on the +platform the trace file was recorded). + +The first line may be a metadata object, although this is optional: + +``` +{"metadata": { + "version": "v3.0", + "vehicle_interface_id": "7ABF", + "vehicle": { + "make": "Ford", + "model": "Mustang", + "trim": "V6 Premium", + "year": 2013 + }, + "description": "highway drive to work", + "driver_name": "TJ Giuli", + "vehicle_id": "17N1039247929" +} +``` + +The following lines are OpenXC messages with a `timestamp` field added, e.g.: + + {"timestamp": 1385133351.285525, "name": "steering_wheel_angle", "value": 45} + +The timestamp is in [UNIX time](http://en.wikipedia.org/wiki/Unix_time) +(i.e. seconds since the UNIX epoch, 00:00:00 UTC, 1/1/1970). + +## Official Signals + +These signal names are a part of the OpenXC specification, although some +manufacturers may support custom message names. + +* steering_wheel_angle + * numerical, -600 to +600 degrees + * 10Hz +* torque_at_transmission + * numerical, -500 to 1500 Nm + * 10Hz +* engine_speed + * numerical, 0 to 16382 RPM + * 10Hz +* vehicle_speed + * numerical, 0 to 655 km/h (this will be positive even if going in reverse + as it's not a velocity, although you can use the gear status to figure out + direction) + * 10Hz +* accelerator_pedal_position + * percentage + * 10Hz +* parking_brake_status + * boolean, (true == brake engaged) + * 1Hz, but sent immediately on change +* brake_pedal_status + * boolean (True == pedal pressed) + * 1Hz, but sent immediately on change +* transmission_gear_position + * states: first, second, third, fourth, fifth, sixth, seventh, eighth, + ninth, tenth, reverse, neutral + * 1Hz, but sent immediately on change +* gear_lever_position + * states: neutral, park, reverse, drive, sport, low, first, second, third, + fourth, fifth, sixth, seventh, eighth, ninth, tenth + * 1Hz, but sent immediately on change +* odometer + * Numerical, km + 0 to 16777214.000 km, with about .2m resolution + * 10Hz +* ignition_status + * states: off, accessory, run, start + * 1Hz, but sent immediately on change +* fuel_level + * percentage + * 2Hz +* fuel_consumed_since_restart + * numerical, 0 - 4294967295.0 L (this goes to 0 every time the vehicle + restarts, like a trip meter) + * 10Hz +* door_status + * Value is State: driver, passenger, rear_left, rear_right. + * Event is boolean: true == ajar + * 1Hz, but sent immediately on change +* headlamp_status + * boolean, true is on + * 1Hz, but sent immediately on change +* high_beam_status + * boolean, true is on + * 1Hz, but sent immediately on change +* windshield_wiper_status + * boolean, true is on + * 1Hz, but sent immediately on change +* latitude + * numerical, -89.0 to 89.0 degrees with standard GPS accuracy + * 1Hz +* longitude + * numerical, -179.0 to 179.0 degrees with standard GPS accuracy + * 1Hz + +## Signals from Diagnostic Messages + +This set of signals is often retreived from OBD-II requests. The units can be +found in the [OBD-II standard](http://en.wikipedia.org/wiki/OBD-II_PIDs#Mode_01). + +* engine_load +* engine_coolant_temperature +* barometric_pressure +* commanded_throttle_position +* throttle_position +* fuel_level +* intake_air_temperature +* intake_manifold_pressure +* running_time +* fuel_pressure +* mass_airflow +* accelerator_pedal_position +* ethanol_fuel_percentage +* engine_oil_temperature +* engine_torque + +License +======= + +Copyright (c) 2012-2014 Ford Motor Company + +Licensed under the BSD license. + +[OpenXC]: http://openxcplatform.com diff --git a/libs/openxc-message-format/benchmark/proto/.gitignore b/libs/openxc-message-format/benchmark/proto/.gitignore new file mode 100644 index 00000000..0520d7d2 --- /dev/null +++ b/libs/openxc-message-format/benchmark/proto/.gitignore @@ -0,0 +1 @@ +*_pb2.py diff --git a/libs/openxc-message-format/benchmark/proto/compare_sizes.py b/libs/openxc-message-format/benchmark/proto/compare_sizes.py new file mode 100755 index 00000000..0ed445fd --- /dev/null +++ b/libs/openxc-message-format/benchmark/proto/compare_sizes.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python + +from __future__ import division +import sys +import numbers + +import openxc_pb2 +import json + +def sizeof_fmt(num): + for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']: + if num < 1024.0: + return "%3.1f%s" % (num, unit) + num /= 1024.0 + +total_raw_can_size = 0 +total_raw_json_size = 0 +total_raw_binary_size = 0 +total_translated_json_size = 0 +total_translated_binary_size = 0 + +for trace_file in sys.argv[1:]: + for line in open(trace_file): + try: + json_message = json.loads(line) + except ValueError: + continue + + del json_message['timestamp'] + + message = openxc_pb2.VehicleMessage() + + if 'id' and 'data' in json_message: + # rough approx. that CAN messages are 10 bytes - they could be less + # but most of ours are full 64+11 bits + total_raw_can_size += 10 + total_raw_json_size += len(json.dumps(json_message)) + message.type = openxc_pb2.VehicleMessage.RAW + message.raw_message.message_id = json_message['id'] + message.raw_message.data = int(json_message['data'], 0) + total_raw_binary_size += len(message.SerializeToString()) + else: + message.type = openxc_pb2.VehicleMessage.TRANSLATED + message.translated_message.name = json_message['name'] + if 'event' in json_message: + message.translated_message.string_value = json_message['value'] + if isinstance(json_message['event'], bool): + message.translated_message.type = openxc_pb2.TranslatedMessage.EVENTED_BOOL + message.translated_message.boolean_event = json_message['event'] + elif isinstance(json_message['event'], numbers.Number): + message.translated_message.type = openxc_pb2.TranslatedMessage.EVENTED_NUM + message.translated_message.numeric_value = json_message['event'] + else: + message.translated_message.type = openxc_pb2.TranslatedMessage.EVENTED_STRING + message.translated_message.string_value = json_message['event'] + else: + if isinstance(json_message['value'], bool): + message.translated_message.type = openxc_pb2.TranslatedMessage.BOOL + message.translated_message.boolean_value = json_message['value'] + elif isinstance(json_message['value'], numbers.Number): + message.translated_message.type = openxc_pb2.TranslatedMessage.NUM + message.translated_message.numeric_value = json_message['value'] + else: + message.translated_message.type = openxc_pb2.TranslatedMessage.STRING + message.translated_message.string_value = json_message['value'] + total_translated_json_size += len(json.dumps(json_message)) + total_translated_binary_size += len(message.SerializeToString()) + + +print("For the %d trace files given..." % len(sys.argv[1:])) +print("Total transferred raw CAN size is %s" % sizeof_fmt(total_raw_can_size)) +print("Total transferred raw JSON size is %s" % sizeof_fmt(total_raw_json_size)) +print("Total transferred raw binary size is %s" % sizeof_fmt(total_raw_binary_size)) +print("Total transferred translated JSON size is %s" % + sizeof_fmt(total_translated_json_size)) +print("Total transferred translated binary size is %s" % + sizeof_fmt(total_translated_binary_size)) + +total_json_size = total_raw_json_size + total_translated_json_size +print("Total transferred JSON size is %s" % sizeof_fmt(total_json_size)) +total_binary_size = total_raw_binary_size + total_translated_binary_size +print("Total transferred binary size is %s" % sizeof_fmt(total_binary_size)) + +if total_raw_can_size > 0: + print("Binary encoding adds %f%% overhead to raw CAN messages" % ( + total_raw_binary_size / total_raw_can_size * 100 - 100)) + print("JSON encoding adds %f%% overhead to raw CAN messages" % ( + total_raw_json_size / total_raw_can_size * 100 - 100)) +if total_raw_json_size > 0: + print("Binary encoding is %f%% smaller than JSON for raw messages" % ( + 100 - (total_raw_binary_size / total_raw_json_size * 100))) +if total_translated_json_size > 0: + print("Binary encoding is %f%% smaller than JSON for translated messages" % ( + 100 - (total_translated_binary_size / total_translated_json_size * 100))) +print("Binary encoding is %f%% smaller than JSON overall" % ( + 100 - (total_binary_size / total_json_size * 100))) diff --git a/libs/openxc-message-format/gen/README.mkd b/libs/openxc-message-format/gen/README.mkd new file mode 100644 index 00000000..e607772d --- /dev/null +++ b/libs/openxc-message-format/gen/README.mkd @@ -0,0 +1,11 @@ +Generated Files +================ + +This directory holds generated implementation files for the Protocol Buffer +objects defined in openxc.proto. The definitions don't change very often, and so +it makes more sense to keep a compiled version in the repository for each +major build environment rather than requiring each developer to get the protobuf +dependencies. + +I've also not found a good way to incorporate protobuf generation with our +Makefile build system in the openxc/vi-firmware project. diff --git a/libs/openxc-message-format/gen/cpp/openxc.pb b/libs/openxc-message-format/gen/cpp/openxc.pb new file mode 100644 index 00000000..104c2065 Binary files /dev/null and b/libs/openxc-message-format/gen/cpp/openxc.pb differ diff --git a/libs/openxc-message-format/gen/cpp/openxc.pb.c b/libs/openxc-message-format/gen/cpp/openxc.pb.c new file mode 100644 index 00000000..9b90c36b --- /dev/null +++ b/libs/openxc-message-format/gen/cpp/openxc.pb.c @@ -0,0 +1,184 @@ +/* Automatically generated nanopb constant definitions */ +/* Generated by nanopb-0.3.1 at Wed Sep 14 16:47:53 2016. */ + +#include "openxc.pb.h" + +#if PB_PROTO_HEADER_VERSION != 30 +#error Regenerate this file with the current version of nanopb generator. +#endif + + + +const pb_field_t openxc_VehicleMessage_fields[8] = { + PB_FIELD( 1, ENUM , OPTIONAL, STATIC , FIRST, openxc_VehicleMessage, type, type, 0), + PB_FIELD( 2, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_VehicleMessage, can_message, type, &openxc_CanMessage_fields), + PB_FIELD( 3, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_VehicleMessage, simple_message, can_message, &openxc_SimpleMessage_fields), + PB_FIELD( 4, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_VehicleMessage, diagnostic_response, simple_message, &openxc_DiagnosticResponse_fields), + PB_FIELD( 5, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_VehicleMessage, control_command, diagnostic_response, &openxc_ControlCommand_fields), + PB_FIELD( 6, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_VehicleMessage, command_response, control_command, &openxc_CommandResponse_fields), + PB_FIELD( 7, UINT64 , OPTIONAL, STATIC , OTHER, openxc_VehicleMessage, timestamp, command_response, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_CanMessage_fields[5] = { + PB_FIELD( 1, INT32 , OPTIONAL, STATIC , FIRST, openxc_CanMessage, bus, bus, 0), + PB_FIELD( 2, UINT32 , OPTIONAL, STATIC , OTHER, openxc_CanMessage, id, bus, 0), + PB_FIELD( 3, BYTES , OPTIONAL, STATIC , OTHER, openxc_CanMessage, data, id, 0), + PB_FIELD( 4, ENUM , OPTIONAL, STATIC , OTHER, openxc_CanMessage, frame_format, data, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_ControlCommand_fields[9] = { + PB_FIELD( 1, ENUM , OPTIONAL, STATIC , FIRST, openxc_ControlCommand, type, type, 0), + PB_FIELD( 2, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_ControlCommand, diagnostic_request, type, &openxc_DiagnosticControlCommand_fields), + PB_FIELD( 3, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_ControlCommand, passthrough_mode_request, diagnostic_request, &openxc_PassthroughModeControlCommand_fields), + PB_FIELD( 4, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_ControlCommand, acceptance_filter_bypass_command, passthrough_mode_request, &openxc_AcceptanceFilterBypassCommand_fields), + PB_FIELD( 5, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_ControlCommand, payload_format_command, acceptance_filter_bypass_command, &openxc_PayloadFormatCommand_fields), + PB_FIELD( 6, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_ControlCommand, predefined_obd2_requests_command, payload_format_command, &openxc_PredefinedObd2RequestsCommand_fields), + PB_FIELD( 7, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_ControlCommand, modem_configuration_command, predefined_obd2_requests_command, &openxc_ModemConfigurationCommand_fields), + PB_FIELD( 8, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_ControlCommand, rtc_configuration_command, modem_configuration_command, &openxc_RTCConfigurationCommand_fields), + PB_LAST_FIELD +}; + +const pb_field_t openxc_DiagnosticControlCommand_fields[3] = { + PB_FIELD( 1, MESSAGE , OPTIONAL, STATIC , FIRST, openxc_DiagnosticControlCommand, request, request, &openxc_DiagnosticRequest_fields), + PB_FIELD( 2, ENUM , OPTIONAL, STATIC , OTHER, openxc_DiagnosticControlCommand, action, request, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_PassthroughModeControlCommand_fields[3] = { + PB_FIELD( 1, INT32 , OPTIONAL, STATIC , FIRST, openxc_PassthroughModeControlCommand, bus, bus, 0), + PB_FIELD( 2, BOOL , OPTIONAL, STATIC , OTHER, openxc_PassthroughModeControlCommand, enabled, bus, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_AcceptanceFilterBypassCommand_fields[3] = { + PB_FIELD( 1, INT32 , OPTIONAL, STATIC , FIRST, openxc_AcceptanceFilterBypassCommand, bus, bus, 0), + PB_FIELD( 2, BOOL , OPTIONAL, STATIC , OTHER, openxc_AcceptanceFilterBypassCommand, bypass, bus, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_PayloadFormatCommand_fields[2] = { + PB_FIELD( 1, ENUM , OPTIONAL, STATIC , FIRST, openxc_PayloadFormatCommand, format, format, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_PredefinedObd2RequestsCommand_fields[2] = { + PB_FIELD( 1, BOOL , OPTIONAL, STATIC , FIRST, openxc_PredefinedObd2RequestsCommand, enabled, enabled, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_NetworkOperatorSettings_fields[4] = { + PB_FIELD( 1, BOOL , OPTIONAL, STATIC , FIRST, openxc_NetworkOperatorSettings, allowDataRoaming, allowDataRoaming, 0), + PB_FIELD( 2, ENUM , OPTIONAL, STATIC , OTHER, openxc_NetworkOperatorSettings, operatorSelectMode, allowDataRoaming, 0), + PB_FIELD( 3, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_NetworkOperatorSettings, networkDescriptor, operatorSelectMode, &openxc_NetworkOperatorSettings_NetworkDescriptor_fields), + PB_LAST_FIELD +}; + +const pb_field_t openxc_NetworkOperatorSettings_NetworkDescriptor_fields[3] = { + PB_FIELD( 1, UINT32 , OPTIONAL, STATIC , FIRST, openxc_NetworkOperatorSettings_NetworkDescriptor, PLMN, PLMN, 0), + PB_FIELD( 2, ENUM , OPTIONAL, STATIC , OTHER, openxc_NetworkOperatorSettings_NetworkDescriptor, networkType, PLMN, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_NetworkDataSettings_fields[2] = { + PB_FIELD( 1, STRING , OPTIONAL, CALLBACK, FIRST, openxc_NetworkDataSettings, APN, APN, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_ServerConnectSettings_fields[3] = { + PB_FIELD( 1, STRING , OPTIONAL, STATIC , FIRST, openxc_ServerConnectSettings, host, host, 0), + PB_FIELD( 2, UINT32 , OPTIONAL, STATIC , OTHER, openxc_ServerConnectSettings, port, host, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_ModemConfigurationCommand_fields[4] = { + PB_FIELD( 1, MESSAGE , OPTIONAL, STATIC , FIRST, openxc_ModemConfigurationCommand, networkOperatorSettings, networkOperatorSettings, &openxc_NetworkOperatorSettings_fields), + PB_FIELD( 2, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_ModemConfigurationCommand, networkDataSettings, networkOperatorSettings, &openxc_NetworkDataSettings_fields), + PB_FIELD( 3, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_ModemConfigurationCommand, serverConnectSettings, networkDataSettings, &openxc_ServerConnectSettings_fields), + PB_LAST_FIELD +}; + +const pb_field_t openxc_RTCConfigurationCommand_fields[2] = { + PB_FIELD( 1, UINT32 , OPTIONAL, STATIC , FIRST, openxc_RTCConfigurationCommand, unix_time, unix_time, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_CommandResponse_fields[4] = { + PB_FIELD( 1, ENUM , OPTIONAL, STATIC , FIRST, openxc_CommandResponse, type, type, 0), + PB_FIELD( 2, STRING , OPTIONAL, STATIC , OTHER, openxc_CommandResponse, message, type, 0), + PB_FIELD( 3, BOOL , OPTIONAL, STATIC , OTHER, openxc_CommandResponse, status, message, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_DiagnosticRequest_fields[10] = { + PB_FIELD( 1, INT32 , OPTIONAL, STATIC , FIRST, openxc_DiagnosticRequest, bus, bus, 0), + PB_FIELD( 2, UINT32 , OPTIONAL, STATIC , OTHER, openxc_DiagnosticRequest, message_id, bus, 0), + PB_FIELD( 3, UINT32 , OPTIONAL, STATIC , OTHER, openxc_DiagnosticRequest, mode, message_id, 0), + PB_FIELD( 4, UINT32 , OPTIONAL, STATIC , OTHER, openxc_DiagnosticRequest, pid, mode, 0), + PB_FIELD( 5, BYTES , OPTIONAL, STATIC , OTHER, openxc_DiagnosticRequest, payload, pid, 0), + PB_FIELD( 6, BOOL , OPTIONAL, STATIC , OTHER, openxc_DiagnosticRequest, multiple_responses, payload, 0), + PB_FIELD( 7, DOUBLE , OPTIONAL, STATIC , OTHER, openxc_DiagnosticRequest, frequency, multiple_responses, 0), + PB_FIELD( 8, STRING , OPTIONAL, STATIC , OTHER, openxc_DiagnosticRequest, name, frequency, 0), + PB_FIELD( 9, ENUM , OPTIONAL, STATIC , OTHER, openxc_DiagnosticRequest, decoded_type, name, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_DiagnosticResponse_fields[9] = { + PB_FIELD( 1, INT32 , OPTIONAL, STATIC , FIRST, openxc_DiagnosticResponse, bus, bus, 0), + PB_FIELD( 2, UINT32 , OPTIONAL, STATIC , OTHER, openxc_DiagnosticResponse, message_id, bus, 0), + PB_FIELD( 3, UINT32 , OPTIONAL, STATIC , OTHER, openxc_DiagnosticResponse, mode, message_id, 0), + PB_FIELD( 4, UINT32 , OPTIONAL, STATIC , OTHER, openxc_DiagnosticResponse, pid, mode, 0), + PB_FIELD( 5, BOOL , OPTIONAL, STATIC , OTHER, openxc_DiagnosticResponse, success, pid, 0), + PB_FIELD( 6, UINT32 , OPTIONAL, STATIC , OTHER, openxc_DiagnosticResponse, negative_response_code, success, 0), + PB_FIELD( 7, BYTES , OPTIONAL, STATIC , OTHER, openxc_DiagnosticResponse, payload, negative_response_code, 0), + PB_FIELD( 8, DOUBLE , OPTIONAL, STATIC , OTHER, openxc_DiagnosticResponse, value, payload, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_DynamicField_fields[5] = { + PB_FIELD( 1, ENUM , OPTIONAL, STATIC , FIRST, openxc_DynamicField, type, type, 0), + PB_FIELD( 2, STRING , OPTIONAL, STATIC , OTHER, openxc_DynamicField, string_value, type, 0), + PB_FIELD( 3, DOUBLE , OPTIONAL, STATIC , OTHER, openxc_DynamicField, numeric_value, string_value, 0), + PB_FIELD( 4, BOOL , OPTIONAL, STATIC , OTHER, openxc_DynamicField, boolean_value, numeric_value, 0), + PB_LAST_FIELD +}; + +const pb_field_t openxc_SimpleMessage_fields[4] = { + PB_FIELD( 1, STRING , OPTIONAL, STATIC , FIRST, openxc_SimpleMessage, name, name, 0), + PB_FIELD( 2, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_SimpleMessage, value, name, &openxc_DynamicField_fields), + PB_FIELD( 3, MESSAGE , OPTIONAL, STATIC , OTHER, openxc_SimpleMessage, event, value, &openxc_DynamicField_fields), + PB_LAST_FIELD +}; + + +/* Check that field information fits in pb_field_t */ +#if !defined(PB_FIELD_32BIT) +/* If you get an error here, it means that you need to define PB_FIELD_32BIT + * compile-time option. You can do that in pb.h or on compiler command line. + * + * The reason you need to do this is that some of your messages contain tag + * numbers or field sizes that are larger than what can fit in 8 or 16 bit + * field descriptors. + */ +PB_STATIC_ASSERT((pb_membersize(openxc_VehicleMessage, can_message) < 65536 && pb_membersize(openxc_VehicleMessage, simple_message) < 65536 && pb_membersize(openxc_VehicleMessage, diagnostic_response) < 65536 && pb_membersize(openxc_VehicleMessage, control_command) < 65536 && pb_membersize(openxc_VehicleMessage, command_response) < 65536 && pb_membersize(openxc_ControlCommand, diagnostic_request) < 65536 && pb_membersize(openxc_ControlCommand, passthrough_mode_request) < 65536 && pb_membersize(openxc_ControlCommand, acceptance_filter_bypass_command) < 65536 && pb_membersize(openxc_ControlCommand, payload_format_command) < 65536 && pb_membersize(openxc_ControlCommand, predefined_obd2_requests_command) < 65536 && pb_membersize(openxc_ControlCommand, modem_configuration_command) < 65536 && pb_membersize(openxc_ControlCommand, rtc_configuration_command) < 65536 && pb_membersize(openxc_DiagnosticControlCommand, request) < 65536 && pb_membersize(openxc_NetworkOperatorSettings, networkDescriptor) < 65536 && pb_membersize(openxc_ModemConfigurationCommand, networkOperatorSettings) < 65536 && pb_membersize(openxc_ModemConfigurationCommand, networkDataSettings) < 65536 && pb_membersize(openxc_ModemConfigurationCommand, serverConnectSettings) < 65536 && pb_membersize(openxc_SimpleMessage, value) < 65536 && pb_membersize(openxc_SimpleMessage, event) < 65536), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_openxc_VehicleMessage_openxc_CanMessage_openxc_ControlCommand_openxc_DiagnosticControlCommand_openxc_PassthroughModeControlCommand_openxc_AcceptanceFilterBypassCommand_openxc_PayloadFormatCommand_openxc_PredefinedObd2RequestsCommand_openxc_NetworkOperatorSettings_openxc_NetworkOperatorSettings_NetworkDescriptor_openxc_NetworkDataSettings_openxc_ServerConnectSettings_openxc_ModemConfigurationCommand_openxc_RTCConfigurationCommand_openxc_CommandResponse_openxc_DiagnosticRequest_openxc_DiagnosticResponse_openxc_DynamicField_openxc_SimpleMessage) +#endif + +#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT) +/* If you get an error here, it means that you need to define PB_FIELD_16BIT + * compile-time option. You can do that in pb.h or on compiler command line. + * + * The reason you need to do this is that some of your messages contain tag + * numbers or field sizes that are larger than what can fit in the default + * 8 bit descriptors. + */ +PB_STATIC_ASSERT((pb_membersize(openxc_VehicleMessage, can_message) < 256 && pb_membersize(openxc_VehicleMessage, simple_message) < 256 && pb_membersize(openxc_VehicleMessage, diagnostic_response) < 256 && pb_membersize(openxc_VehicleMessage, control_command) < 256 && pb_membersize(openxc_VehicleMessage, command_response) < 256 && pb_membersize(openxc_ControlCommand, diagnostic_request) < 256 && pb_membersize(openxc_ControlCommand, passthrough_mode_request) < 256 && pb_membersize(openxc_ControlCommand, acceptance_filter_bypass_command) < 256 && pb_membersize(openxc_ControlCommand, payload_format_command) < 256 && pb_membersize(openxc_ControlCommand, predefined_obd2_requests_command) < 256 && pb_membersize(openxc_ControlCommand, modem_configuration_command) < 256 && pb_membersize(openxc_ControlCommand, rtc_configuration_command) < 256 && pb_membersize(openxc_DiagnosticControlCommand, request) < 256 && pb_membersize(openxc_NetworkOperatorSettings, networkDescriptor) < 256 && pb_membersize(openxc_ModemConfigurationCommand, networkOperatorSettings) < 256 && pb_membersize(openxc_ModemConfigurationCommand, networkDataSettings) < 256 && pb_membersize(openxc_ModemConfigurationCommand, serverConnectSettings) < 256 && pb_membersize(openxc_SimpleMessage, value) < 256 && pb_membersize(openxc_SimpleMessage, event) < 256), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_openxc_VehicleMessage_openxc_CanMessage_openxc_ControlCommand_openxc_DiagnosticControlCommand_openxc_PassthroughModeControlCommand_openxc_AcceptanceFilterBypassCommand_openxc_PayloadFormatCommand_openxc_PredefinedObd2RequestsCommand_openxc_NetworkOperatorSettings_openxc_NetworkOperatorSettings_NetworkDescriptor_openxc_NetworkDataSettings_openxc_ServerConnectSettings_openxc_ModemConfigurationCommand_openxc_RTCConfigurationCommand_openxc_CommandResponse_openxc_DiagnosticRequest_openxc_DiagnosticResponse_openxc_DynamicField_openxc_SimpleMessage) +#endif + + +/* On some platforms (such as AVR), double is really float. + * These are not directly supported by nanopb, but see example_avr_double. + * To get rid of this error, remove any double fields from your .proto. + */ +PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES) + diff --git a/libs/openxc-message-format/gen/cpp/openxc.pb.h b/libs/openxc-message-format/gen/cpp/openxc.pb.h new file mode 100644 index 00000000..09735ee7 --- /dev/null +++ b/libs/openxc-message-format/gen/cpp/openxc.pb.h @@ -0,0 +1,426 @@ +/* Automatically generated nanopb header */ +/* Generated by nanopb-0.3.1 at Wed Sep 14 16:47:53 2016. */ + +#ifndef PB_OPENXC_PB_H_INCLUDED +#define PB_OPENXC_PB_H_INCLUDED +#include + +#if PB_PROTO_HEADER_VERSION != 30 +#error Regenerate this file with the current version of nanopb generator. +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Enum definitions */ +typedef enum _openxc_VehicleMessage_Type { + openxc_VehicleMessage_Type_CAN = 1, + openxc_VehicleMessage_Type_SIMPLE = 2, + openxc_VehicleMessage_Type_DIAGNOSTIC = 3, + openxc_VehicleMessage_Type_CONTROL_COMMAND = 4, + openxc_VehicleMessage_Type_COMMAND_RESPONSE = 5 +} openxc_VehicleMessage_Type; + +typedef enum _openxc_CanMessage_FrameFormat { + openxc_CanMessage_FrameFormat_STANDARD = 1, + openxc_CanMessage_FrameFormat_EXTENDED = 2 +} openxc_CanMessage_FrameFormat; + +typedef enum _openxc_ControlCommand_Type { + openxc_ControlCommand_Type_VERSION = 1, + openxc_ControlCommand_Type_DEVICE_ID = 2, + openxc_ControlCommand_Type_DIAGNOSTIC = 3, + openxc_ControlCommand_Type_PASSTHROUGH = 4, + openxc_ControlCommand_Type_ACCEPTANCE_FILTER_BYPASS = 5, + openxc_ControlCommand_Type_PAYLOAD_FORMAT = 6, + openxc_ControlCommand_Type_PREDEFINED_OBD2_REQUESTS = 7, + openxc_ControlCommand_Type_MODEM_CONFIGURATION = 8, + openxc_ControlCommand_Type_RTC_CONFIGURATION = 9, + openxc_ControlCommand_Type_SD_MOUNT_STATUS = 10, + openxc_ControlCommand_Type_PLATFORM = 11 +} openxc_ControlCommand_Type; + +typedef enum _openxc_DiagnosticControlCommand_Action { + openxc_DiagnosticControlCommand_Action_ADD = 1, + openxc_DiagnosticControlCommand_Action_CANCEL = 2 +} openxc_DiagnosticControlCommand_Action; + +typedef enum _openxc_PayloadFormatCommand_PayloadFormat { + openxc_PayloadFormatCommand_PayloadFormat_JSON = 1, + openxc_PayloadFormatCommand_PayloadFormat_PROTOBUF = 2, + openxc_PayloadFormatCommand_PayloadFormat_MESSAGEPACK = 3 +} openxc_PayloadFormatCommand_PayloadFormat; + +typedef enum _openxc_NetworkOperatorSettings_OperatorSelectMode { + openxc_NetworkOperatorSettings_OperatorSelectMode_AUTOMATIC = 0, + openxc_NetworkOperatorSettings_OperatorSelectMode_MANUAL = 1, + openxc_NetworkOperatorSettings_OperatorSelectMode_DEREGISTER = 2, + openxc_NetworkOperatorSettings_OperatorSelectMode_SET_ONLY = 3, + openxc_NetworkOperatorSettings_OperatorSelectMode_MANUAL_AUTOMATIC = 4 +} openxc_NetworkOperatorSettings_OperatorSelectMode; + +typedef enum _openxc_NetworkOperatorSettings_NetworkDescriptor_NetworkType { + openxc_NetworkOperatorSettings_NetworkDescriptor_NetworkType_GSM = 0, + openxc_NetworkOperatorSettings_NetworkDescriptor_NetworkType_UTRAN = 2 +} openxc_NetworkOperatorSettings_NetworkDescriptor_NetworkType; + +typedef enum _openxc_DiagnosticRequest_DecodedType { + openxc_DiagnosticRequest_DecodedType_NONE = 1, + openxc_DiagnosticRequest_DecodedType_OBD2 = 2 +} openxc_DiagnosticRequest_DecodedType; + +typedef enum _openxc_DynamicField_Type { + openxc_DynamicField_Type_STRING = 1, + openxc_DynamicField_Type_NUM = 2, + openxc_DynamicField_Type_BOOL = 3 +} openxc_DynamicField_Type; + +/* Struct definitions */ +typedef struct _openxc_NetworkDataSettings { + pb_callback_t APN; +} openxc_NetworkDataSettings; + +typedef struct _openxc_AcceptanceFilterBypassCommand { + bool has_bus; + int32_t bus; + bool has_bypass; + bool bypass; +} openxc_AcceptanceFilterBypassCommand; + +typedef PB_BYTES_ARRAY_T(8) openxc_CanMessage_data_t; + +typedef struct _openxc_CanMessage { + bool has_bus; + int32_t bus; + bool has_id; + uint32_t id; + bool has_data; + openxc_CanMessage_data_t data; + bool has_frame_format; + openxc_CanMessage_FrameFormat frame_format; +} openxc_CanMessage; + +typedef struct _openxc_CommandResponse { + bool has_type; + openxc_ControlCommand_Type type; + bool has_message; + char message[128]; + bool has_status; + bool status; +} openxc_CommandResponse; + +typedef PB_BYTES_ARRAY_T(8) openxc_DiagnosticRequest_payload_t; + +typedef struct _openxc_DiagnosticRequest { + bool has_bus; + int32_t bus; + bool has_message_id; + uint32_t message_id; + bool has_mode; + uint32_t mode; + bool has_pid; + uint32_t pid; + bool has_payload; + openxc_DiagnosticRequest_payload_t payload; + bool has_multiple_responses; + bool multiple_responses; + bool has_frequency; + double frequency; + bool has_name; + char name[10]; + bool has_decoded_type; + openxc_DiagnosticRequest_DecodedType decoded_type; +} openxc_DiagnosticRequest; + +typedef PB_BYTES_ARRAY_T(255) openxc_DiagnosticResponse_payload_t; + +typedef struct _openxc_DiagnosticResponse { + bool has_bus; + int32_t bus; + bool has_message_id; + uint32_t message_id; + bool has_mode; + uint32_t mode; + bool has_pid; + uint32_t pid; + bool has_success; + bool success; + bool has_negative_response_code; + uint32_t negative_response_code; + bool has_payload; + openxc_DiagnosticResponse_payload_t payload; + bool has_value; + double value; +} openxc_DiagnosticResponse; + +typedef struct _openxc_DynamicField { + bool has_type; + openxc_DynamicField_Type type; + bool has_string_value; + char string_value[100]; + bool has_numeric_value; + double numeric_value; + bool has_boolean_value; + bool boolean_value; +} openxc_DynamicField; + +typedef struct _openxc_NetworkOperatorSettings_NetworkDescriptor { + bool has_PLMN; + uint32_t PLMN; + bool has_networkType; + openxc_NetworkOperatorSettings_NetworkDescriptor_NetworkType networkType; +} openxc_NetworkOperatorSettings_NetworkDescriptor; + +typedef struct _openxc_PassthroughModeControlCommand { + bool has_bus; + int32_t bus; + bool has_enabled; + bool enabled; +} openxc_PassthroughModeControlCommand; + +typedef struct _openxc_PayloadFormatCommand { + bool has_format; + openxc_PayloadFormatCommand_PayloadFormat format; +} openxc_PayloadFormatCommand; + +typedef struct _openxc_PredefinedObd2RequestsCommand { + bool has_enabled; + bool enabled; +} openxc_PredefinedObd2RequestsCommand; + +typedef struct _openxc_RTCConfigurationCommand { + bool has_unix_time; + uint32_t unix_time; +} openxc_RTCConfigurationCommand; + +typedef struct _openxc_ServerConnectSettings { + bool has_host; + char host[128]; + bool has_port; + uint32_t port; +} openxc_ServerConnectSettings; + +typedef struct _openxc_DiagnosticControlCommand { + bool has_request; + openxc_DiagnosticRequest request; + bool has_action; + openxc_DiagnosticControlCommand_Action action; +} openxc_DiagnosticControlCommand; + +typedef struct _openxc_NetworkOperatorSettings { + bool has_allowDataRoaming; + bool allowDataRoaming; + bool has_operatorSelectMode; + openxc_NetworkOperatorSettings_OperatorSelectMode operatorSelectMode; + bool has_networkDescriptor; + openxc_NetworkOperatorSettings_NetworkDescriptor networkDescriptor; +} openxc_NetworkOperatorSettings; + +typedef struct _openxc_SimpleMessage { + bool has_name; + char name[100]; + bool has_value; + openxc_DynamicField value; + bool has_event; + openxc_DynamicField event; +} openxc_SimpleMessage; + +typedef struct _openxc_ModemConfigurationCommand { + bool has_networkOperatorSettings; + openxc_NetworkOperatorSettings networkOperatorSettings; + bool has_networkDataSettings; + openxc_NetworkDataSettings networkDataSettings; + bool has_serverConnectSettings; + openxc_ServerConnectSettings serverConnectSettings; +} openxc_ModemConfigurationCommand; + +typedef struct _openxc_ControlCommand { + bool has_type; + openxc_ControlCommand_Type type; + bool has_diagnostic_request; + openxc_DiagnosticControlCommand diagnostic_request; + bool has_passthrough_mode_request; + openxc_PassthroughModeControlCommand passthrough_mode_request; + bool has_acceptance_filter_bypass_command; + openxc_AcceptanceFilterBypassCommand acceptance_filter_bypass_command; + bool has_payload_format_command; + openxc_PayloadFormatCommand payload_format_command; + bool has_predefined_obd2_requests_command; + openxc_PredefinedObd2RequestsCommand predefined_obd2_requests_command; + bool has_modem_configuration_command; + openxc_ModemConfigurationCommand modem_configuration_command; + bool has_rtc_configuration_command; + openxc_RTCConfigurationCommand rtc_configuration_command; +} openxc_ControlCommand; + +typedef struct _openxc_VehicleMessage { + bool has_type; + openxc_VehicleMessage_Type type; + bool has_can_message; + openxc_CanMessage can_message; + bool has_simple_message; + openxc_SimpleMessage simple_message; + bool has_diagnostic_response; + openxc_DiagnosticResponse diagnostic_response; + bool has_control_command; + openxc_ControlCommand control_command; + bool has_command_response; + openxc_CommandResponse command_response; + bool has_timestamp; + uint64_t timestamp; +} openxc_VehicleMessage; + +/* Default values for struct fields */ + +/* Initializer values for message structs */ +#define openxc_VehicleMessage_init_default {false, (openxc_VehicleMessage_Type)0, false, openxc_CanMessage_init_default, false, openxc_SimpleMessage_init_default, false, openxc_DiagnosticResponse_init_default, false, openxc_ControlCommand_init_default, false, openxc_CommandResponse_init_default, false, 0} +#define openxc_CanMessage_init_default {false, 0, false, 0, false, {0, {0}}, false, (openxc_CanMessage_FrameFormat)0} +#define openxc_ControlCommand_init_default {false, (openxc_ControlCommand_Type)0, false, openxc_DiagnosticControlCommand_init_default, false, openxc_PassthroughModeControlCommand_init_default, false, openxc_AcceptanceFilterBypassCommand_init_default, false, openxc_PayloadFormatCommand_init_default, false, openxc_PredefinedObd2RequestsCommand_init_default, false, openxc_ModemConfigurationCommand_init_default, false, openxc_RTCConfigurationCommand_init_default} +#define openxc_DiagnosticControlCommand_init_default {false, openxc_DiagnosticRequest_init_default, false, (openxc_DiagnosticControlCommand_Action)0} +#define openxc_PassthroughModeControlCommand_init_default {false, 0, false, 0} +#define openxc_AcceptanceFilterBypassCommand_init_default {false, 0, false, 0} +#define openxc_PayloadFormatCommand_init_default {false, (openxc_PayloadFormatCommand_PayloadFormat)0} +#define openxc_PredefinedObd2RequestsCommand_init_default {false, 0} +#define openxc_NetworkOperatorSettings_init_default {false, 0, false, (openxc_NetworkOperatorSettings_OperatorSelectMode)0, false, openxc_NetworkOperatorSettings_NetworkDescriptor_init_default} +#define openxc_NetworkOperatorSettings_NetworkDescriptor_init_default {false, 0, false, (openxc_NetworkOperatorSettings_NetworkDescriptor_NetworkType)0} +#define openxc_NetworkDataSettings_init_default {{{NULL}, NULL}} +#define openxc_ServerConnectSettings_init_default {false, "", false, 0} +#define openxc_ModemConfigurationCommand_init_default {false, openxc_NetworkOperatorSettings_init_default, false, openxc_NetworkDataSettings_init_default, false, openxc_ServerConnectSettings_init_default} +#define openxc_RTCConfigurationCommand_init_default {false, 0} +#define openxc_CommandResponse_init_default {false, (openxc_ControlCommand_Type)0, false, "", false, 0} +#define openxc_DiagnosticRequest_init_default {false, 0, false, 0, false, 0, false, 0, false, {0, {0}}, false, 0, false, 0, false, "", false, (openxc_DiagnosticRequest_DecodedType)0} +#define openxc_DiagnosticResponse_init_default {false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, {0, {0}}, false, 0} +#define openxc_DynamicField_init_default {false, (openxc_DynamicField_Type)0, false, "", false, 0, false, 0} +#define openxc_SimpleMessage_init_default {false, "", false, openxc_DynamicField_init_default, false, openxc_DynamicField_init_default} +#define openxc_VehicleMessage_init_zero {false, (openxc_VehicleMessage_Type)0, false, openxc_CanMessage_init_zero, false, openxc_SimpleMessage_init_zero, false, openxc_DiagnosticResponse_init_zero, false, openxc_ControlCommand_init_zero, false, openxc_CommandResponse_init_zero, false, 0} +#define openxc_CanMessage_init_zero {false, 0, false, 0, false, {0, {0}}, false, (openxc_CanMessage_FrameFormat)0} +#define openxc_ControlCommand_init_zero {false, (openxc_ControlCommand_Type)0, false, openxc_DiagnosticControlCommand_init_zero, false, openxc_PassthroughModeControlCommand_init_zero, false, openxc_AcceptanceFilterBypassCommand_init_zero, false, openxc_PayloadFormatCommand_init_zero, false, openxc_PredefinedObd2RequestsCommand_init_zero, false, openxc_ModemConfigurationCommand_init_zero, false, openxc_RTCConfigurationCommand_init_zero} +#define openxc_DiagnosticControlCommand_init_zero {false, openxc_DiagnosticRequest_init_zero, false, (openxc_DiagnosticControlCommand_Action)0} +#define openxc_PassthroughModeControlCommand_init_zero {false, 0, false, 0} +#define openxc_AcceptanceFilterBypassCommand_init_zero {false, 0, false, 0} +#define openxc_PayloadFormatCommand_init_zero {false, (openxc_PayloadFormatCommand_PayloadFormat)0} +#define openxc_PredefinedObd2RequestsCommand_init_zero {false, 0} +#define openxc_NetworkOperatorSettings_init_zero {false, 0, false, (openxc_NetworkOperatorSettings_OperatorSelectMode)0, false, openxc_NetworkOperatorSettings_NetworkDescriptor_init_zero} +#define openxc_NetworkOperatorSettings_NetworkDescriptor_init_zero {false, 0, false, (openxc_NetworkOperatorSettings_NetworkDescriptor_NetworkType)0} +#define openxc_NetworkDataSettings_init_zero {{{NULL}, NULL}} +#define openxc_ServerConnectSettings_init_zero {false, "", false, 0} +#define openxc_ModemConfigurationCommand_init_zero {false, openxc_NetworkOperatorSettings_init_zero, false, openxc_NetworkDataSettings_init_zero, false, openxc_ServerConnectSettings_init_zero} +#define openxc_RTCConfigurationCommand_init_zero {false, 0} +#define openxc_CommandResponse_init_zero {false, (openxc_ControlCommand_Type)0, false, "", false, 0} +#define openxc_DiagnosticRequest_init_zero {false, 0, false, 0, false, 0, false, 0, false, {0, {0}}, false, 0, false, 0, false, "", false, (openxc_DiagnosticRequest_DecodedType)0} +#define openxc_DiagnosticResponse_init_zero {false, 0, false, 0, false, 0, false, 0, false, 0, false, 0, false, {0, {0}}, false, 0} +#define openxc_DynamicField_init_zero {false, (openxc_DynamicField_Type)0, false, "", false, 0, false, 0} +#define openxc_SimpleMessage_init_zero {false, "", false, openxc_DynamicField_init_zero, false, openxc_DynamicField_init_zero} + +/* Field tags (for use in manual encoding/decoding) */ +#define openxc_NetworkDataSettings_APN_tag 1 +#define openxc_AcceptanceFilterBypassCommand_bus_tag 1 +#define openxc_AcceptanceFilterBypassCommand_bypass_tag 2 +#define openxc_CanMessage_bus_tag 1 +#define openxc_CanMessage_id_tag 2 +#define openxc_CanMessage_data_tag 3 +#define openxc_CanMessage_frame_format_tag 4 +#define openxc_CommandResponse_type_tag 1 +#define openxc_CommandResponse_message_tag 2 +#define openxc_CommandResponse_status_tag 3 +#define openxc_DiagnosticRequest_bus_tag 1 +#define openxc_DiagnosticRequest_message_id_tag 2 +#define openxc_DiagnosticRequest_mode_tag 3 +#define openxc_DiagnosticRequest_pid_tag 4 +#define openxc_DiagnosticRequest_payload_tag 5 +#define openxc_DiagnosticRequest_multiple_responses_tag 6 +#define openxc_DiagnosticRequest_frequency_tag 7 +#define openxc_DiagnosticRequest_name_tag 8 +#define openxc_DiagnosticRequest_decoded_type_tag 9 +#define openxc_DiagnosticResponse_bus_tag 1 +#define openxc_DiagnosticResponse_message_id_tag 2 +#define openxc_DiagnosticResponse_mode_tag 3 +#define openxc_DiagnosticResponse_pid_tag 4 +#define openxc_DiagnosticResponse_success_tag 5 +#define openxc_DiagnosticResponse_negative_response_code_tag 6 +#define openxc_DiagnosticResponse_payload_tag 7 +#define openxc_DiagnosticResponse_value_tag 8 +#define openxc_DynamicField_type_tag 1 +#define openxc_DynamicField_string_value_tag 2 +#define openxc_DynamicField_numeric_value_tag 3 +#define openxc_DynamicField_boolean_value_tag 4 +#define openxc_NetworkOperatorSettings_NetworkDescriptor_PLMN_tag 1 +#define openxc_NetworkOperatorSettings_NetworkDescriptor_networkType_tag 2 +#define openxc_PassthroughModeControlCommand_bus_tag 1 +#define openxc_PassthroughModeControlCommand_enabled_tag 2 +#define openxc_PayloadFormatCommand_format_tag 1 +#define openxc_PredefinedObd2RequestsCommand_enabled_tag 1 +#define openxc_RTCConfigurationCommand_unix_time_tag 1 +#define openxc_ServerConnectSettings_host_tag 1 +#define openxc_ServerConnectSettings_port_tag 2 +#define openxc_DiagnosticControlCommand_request_tag 1 +#define openxc_DiagnosticControlCommand_action_tag 2 +#define openxc_NetworkOperatorSettings_allowDataRoaming_tag 1 +#define openxc_NetworkOperatorSettings_operatorSelectMode_tag 2 +#define openxc_NetworkOperatorSettings_networkDescriptor_tag 3 +#define openxc_SimpleMessage_name_tag 1 +#define openxc_SimpleMessage_value_tag 2 +#define openxc_SimpleMessage_event_tag 3 +#define openxc_ModemConfigurationCommand_networkOperatorSettings_tag 1 +#define openxc_ModemConfigurationCommand_networkDataSettings_tag 2 +#define openxc_ModemConfigurationCommand_serverConnectSettings_tag 3 +#define openxc_ControlCommand_type_tag 1 +#define openxc_ControlCommand_diagnostic_request_tag 2 +#define openxc_ControlCommand_passthrough_mode_request_tag 3 +#define openxc_ControlCommand_acceptance_filter_bypass_command_tag 4 +#define openxc_ControlCommand_payload_format_command_tag 5 +#define openxc_ControlCommand_predefined_obd2_requests_command_tag 6 +#define openxc_ControlCommand_modem_configuration_command_tag 7 +#define openxc_ControlCommand_rtc_configuration_command_tag 8 +#define openxc_VehicleMessage_type_tag 1 +#define openxc_VehicleMessage_can_message_tag 2 +#define openxc_VehicleMessage_simple_message_tag 3 +#define openxc_VehicleMessage_diagnostic_response_tag 4 +#define openxc_VehicleMessage_control_command_tag 5 +#define openxc_VehicleMessage_command_response_tag 6 +#define openxc_VehicleMessage_timestamp_tag 7 + +/* Struct field encoding specification for nanopb */ +extern const pb_field_t openxc_VehicleMessage_fields[8]; +extern const pb_field_t openxc_CanMessage_fields[5]; +extern const pb_field_t openxc_ControlCommand_fields[9]; +extern const pb_field_t openxc_DiagnosticControlCommand_fields[3]; +extern const pb_field_t openxc_PassthroughModeControlCommand_fields[3]; +extern const pb_field_t openxc_AcceptanceFilterBypassCommand_fields[3]; +extern const pb_field_t openxc_PayloadFormatCommand_fields[2]; +extern const pb_field_t openxc_PredefinedObd2RequestsCommand_fields[2]; +extern const pb_field_t openxc_NetworkOperatorSettings_fields[4]; +extern const pb_field_t openxc_NetworkOperatorSettings_NetworkDescriptor_fields[3]; +extern const pb_field_t openxc_NetworkDataSettings_fields[2]; +extern const pb_field_t openxc_ServerConnectSettings_fields[3]; +extern const pb_field_t openxc_ModemConfigurationCommand_fields[4]; +extern const pb_field_t openxc_RTCConfigurationCommand_fields[2]; +extern const pb_field_t openxc_CommandResponse_fields[4]; +extern const pb_field_t openxc_DiagnosticRequest_fields[10]; +extern const pb_field_t openxc_DiagnosticResponse_fields[9]; +extern const pb_field_t openxc_DynamicField_fields[5]; +extern const pb_field_t openxc_SimpleMessage_fields[4]; + +/* Maximum encoded size of messages (where known) */ +#define openxc_CanMessage_size 33 +#define openxc_DiagnosticControlCommand_size 76 +#define openxc_PassthroughModeControlCommand_size 13 +#define openxc_AcceptanceFilterBypassCommand_size 13 +#define openxc_PayloadFormatCommand_size 6 +#define openxc_PredefinedObd2RequestsCommand_size 2 +#define openxc_NetworkOperatorSettings_size 22 +#define openxc_NetworkOperatorSettings_NetworkDescriptor_size 12 +#define openxc_ServerConnectSettings_size 137 +#define openxc_RTCConfigurationCommand_size 6 +#define openxc_CommandResponse_size 139 +#define openxc_DiagnosticRequest_size 68 +#define openxc_DiagnosticResponse_size 304 +#define openxc_DynamicField_size 119 +#define openxc_SimpleMessage_size 344 + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/libs/openxc-message-format/gen/java/com/openxc/BinaryMessages.java b/libs/openxc-message-format/gen/java/com/openxc/BinaryMessages.java new file mode 100644 index 00000000..4fad1d6a --- /dev/null +++ b/libs/openxc-message-format/gen/java/com/openxc/BinaryMessages.java @@ -0,0 +1,12099 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: openxc.proto + +package com.openxc; + +public final class BinaryMessages { + private BinaryMessages() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + } + public interface VehicleMessageOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional .openxc.VehicleMessage.Type type = 1; + boolean hasType(); + com.openxc.BinaryMessages.VehicleMessage.Type getType(); + + // optional .openxc.CanMessage can_message = 2; + boolean hasCanMessage(); + com.openxc.BinaryMessages.CanMessage getCanMessage(); + com.openxc.BinaryMessages.CanMessageOrBuilder getCanMessageOrBuilder(); + + // optional .openxc.SimpleMessage simple_message = 3; + boolean hasSimpleMessage(); + com.openxc.BinaryMessages.SimpleMessage getSimpleMessage(); + com.openxc.BinaryMessages.SimpleMessageOrBuilder getSimpleMessageOrBuilder(); + + // optional .openxc.DiagnosticResponse diagnostic_response = 4; + boolean hasDiagnosticResponse(); + com.openxc.BinaryMessages.DiagnosticResponse getDiagnosticResponse(); + com.openxc.BinaryMessages.DiagnosticResponseOrBuilder getDiagnosticResponseOrBuilder(); + + // optional .openxc.ControlCommand control_command = 5; + boolean hasControlCommand(); + com.openxc.BinaryMessages.ControlCommand getControlCommand(); + com.openxc.BinaryMessages.ControlCommandOrBuilder getControlCommandOrBuilder(); + + // optional .openxc.CommandResponse command_response = 6; + boolean hasCommandResponse(); + com.openxc.BinaryMessages.CommandResponse getCommandResponse(); + com.openxc.BinaryMessages.CommandResponseOrBuilder getCommandResponseOrBuilder(); + + // optional uint64 timestamp = 7; + boolean hasTimestamp(); + long getTimestamp(); + } + public static final class VehicleMessage extends + com.google.protobuf.GeneratedMessage + implements VehicleMessageOrBuilder { + // Use VehicleMessage.newBuilder() to construct. + private VehicleMessage(Builder builder) { + super(builder); + } + private VehicleMessage(boolean noInit) {} + + private static final VehicleMessage defaultInstance; + public static VehicleMessage getDefaultInstance() { + return defaultInstance; + } + + public VehicleMessage getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_VehicleMessage_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_VehicleMessage_fieldAccessorTable; + } + + public enum Type + implements com.google.protobuf.ProtocolMessageEnum { + CAN(0, 1), + SIMPLE(1, 2), + DIAGNOSTIC(2, 3), + CONTROL_COMMAND(3, 4), + COMMAND_RESPONSE(4, 5), + ; + + public static final int CAN_VALUE = 1; + public static final int SIMPLE_VALUE = 2; + public static final int DIAGNOSTIC_VALUE = 3; + public static final int CONTROL_COMMAND_VALUE = 4; + public static final int COMMAND_RESPONSE_VALUE = 5; + + + public final int getNumber() { return value; } + + public static Type valueOf(int value) { + switch (value) { + case 1: return CAN; + case 2: return SIMPLE; + case 3: return DIAGNOSTIC; + case 4: return CONTROL_COMMAND; + case 5: return COMMAND_RESPONSE; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public Type findValueByNumber(int number) { + return Type.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return com.openxc.BinaryMessages.VehicleMessage.getDescriptor().getEnumTypes().get(0); + } + + private static final Type[] VALUES = { + CAN, SIMPLE, DIAGNOSTIC, CONTROL_COMMAND, COMMAND_RESPONSE, + }; + + public static Type valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private Type(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:openxc.VehicleMessage.Type) + } + + private int bitField0_; + // optional .openxc.VehicleMessage.Type type = 1; + public static final int TYPE_FIELD_NUMBER = 1; + private com.openxc.BinaryMessages.VehicleMessage.Type type_; + public boolean hasType() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.VehicleMessage.Type getType() { + return type_; + } + + // optional .openxc.CanMessage can_message = 2; + public static final int CAN_MESSAGE_FIELD_NUMBER = 2; + private com.openxc.BinaryMessages.CanMessage canMessage_; + public boolean hasCanMessage() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.CanMessage getCanMessage() { + return canMessage_; + } + public com.openxc.BinaryMessages.CanMessageOrBuilder getCanMessageOrBuilder() { + return canMessage_; + } + + // optional .openxc.SimpleMessage simple_message = 3; + public static final int SIMPLE_MESSAGE_FIELD_NUMBER = 3; + private com.openxc.BinaryMessages.SimpleMessage simpleMessage_; + public boolean hasSimpleMessage() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.openxc.BinaryMessages.SimpleMessage getSimpleMessage() { + return simpleMessage_; + } + public com.openxc.BinaryMessages.SimpleMessageOrBuilder getSimpleMessageOrBuilder() { + return simpleMessage_; + } + + // optional .openxc.DiagnosticResponse diagnostic_response = 4; + public static final int DIAGNOSTIC_RESPONSE_FIELD_NUMBER = 4; + private com.openxc.BinaryMessages.DiagnosticResponse diagnosticResponse_; + public boolean hasDiagnosticResponse() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public com.openxc.BinaryMessages.DiagnosticResponse getDiagnosticResponse() { + return diagnosticResponse_; + } + public com.openxc.BinaryMessages.DiagnosticResponseOrBuilder getDiagnosticResponseOrBuilder() { + return diagnosticResponse_; + } + + // optional .openxc.ControlCommand control_command = 5; + public static final int CONTROL_COMMAND_FIELD_NUMBER = 5; + private com.openxc.BinaryMessages.ControlCommand controlCommand_; + public boolean hasControlCommand() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + public com.openxc.BinaryMessages.ControlCommand getControlCommand() { + return controlCommand_; + } + public com.openxc.BinaryMessages.ControlCommandOrBuilder getControlCommandOrBuilder() { + return controlCommand_; + } + + // optional .openxc.CommandResponse command_response = 6; + public static final int COMMAND_RESPONSE_FIELD_NUMBER = 6; + private com.openxc.BinaryMessages.CommandResponse commandResponse_; + public boolean hasCommandResponse() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + public com.openxc.BinaryMessages.CommandResponse getCommandResponse() { + return commandResponse_; + } + public com.openxc.BinaryMessages.CommandResponseOrBuilder getCommandResponseOrBuilder() { + return commandResponse_; + } + + // optional uint64 timestamp = 7; + public static final int TIMESTAMP_FIELD_NUMBER = 7; + private long timestamp_; + public boolean hasTimestamp() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + public long getTimestamp() { + return timestamp_; + } + + private void initFields() { + type_ = com.openxc.BinaryMessages.VehicleMessage.Type.CAN; + canMessage_ = com.openxc.BinaryMessages.CanMessage.getDefaultInstance(); + simpleMessage_ = com.openxc.BinaryMessages.SimpleMessage.getDefaultInstance(); + diagnosticResponse_ = com.openxc.BinaryMessages.DiagnosticResponse.getDefaultInstance(); + controlCommand_ = com.openxc.BinaryMessages.ControlCommand.getDefaultInstance(); + commandResponse_ = com.openxc.BinaryMessages.CommandResponse.getDefaultInstance(); + timestamp_ = 0L; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeEnum(1, type_.getNumber()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeMessage(2, canMessage_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, simpleMessage_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeMessage(4, diagnosticResponse_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeMessage(5, controlCommand_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + output.writeMessage(6, commandResponse_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeUInt64(7, timestamp_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(1, type_.getNumber()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, canMessage_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, simpleMessage_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, diagnosticResponse_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, controlCommand_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, commandResponse_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt64Size(7, timestamp_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.VehicleMessage parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.VehicleMessage parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.VehicleMessage parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.VehicleMessage parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.VehicleMessage parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.VehicleMessage parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.VehicleMessage parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.VehicleMessage parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.VehicleMessage parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.VehicleMessage parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.VehicleMessage prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.VehicleMessageOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_VehicleMessage_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_VehicleMessage_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.VehicleMessage.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getCanMessageFieldBuilder(); + getSimpleMessageFieldBuilder(); + getDiagnosticResponseFieldBuilder(); + getControlCommandFieldBuilder(); + getCommandResponseFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + type_ = com.openxc.BinaryMessages.VehicleMessage.Type.CAN; + bitField0_ = (bitField0_ & ~0x00000001); + if (canMessageBuilder_ == null) { + canMessage_ = com.openxc.BinaryMessages.CanMessage.getDefaultInstance(); + } else { + canMessageBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + if (simpleMessageBuilder_ == null) { + simpleMessage_ = com.openxc.BinaryMessages.SimpleMessage.getDefaultInstance(); + } else { + simpleMessageBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + if (diagnosticResponseBuilder_ == null) { + diagnosticResponse_ = com.openxc.BinaryMessages.DiagnosticResponse.getDefaultInstance(); + } else { + diagnosticResponseBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000008); + if (controlCommandBuilder_ == null) { + controlCommand_ = com.openxc.BinaryMessages.ControlCommand.getDefaultInstance(); + } else { + controlCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000010); + if (commandResponseBuilder_ == null) { + commandResponse_ = com.openxc.BinaryMessages.CommandResponse.getDefaultInstance(); + } else { + commandResponseBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000020); + timestamp_ = 0L; + bitField0_ = (bitField0_ & ~0x00000040); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.VehicleMessage.getDescriptor(); + } + + public com.openxc.BinaryMessages.VehicleMessage getDefaultInstanceForType() { + return com.openxc.BinaryMessages.VehicleMessage.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.VehicleMessage build() { + com.openxc.BinaryMessages.VehicleMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.VehicleMessage buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.VehicleMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.VehicleMessage buildPartial() { + com.openxc.BinaryMessages.VehicleMessage result = new com.openxc.BinaryMessages.VehicleMessage(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.type_ = type_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + if (canMessageBuilder_ == null) { + result.canMessage_ = canMessage_; + } else { + result.canMessage_ = canMessageBuilder_.build(); + } + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + if (simpleMessageBuilder_ == null) { + result.simpleMessage_ = simpleMessage_; + } else { + result.simpleMessage_ = simpleMessageBuilder_.build(); + } + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + if (diagnosticResponseBuilder_ == null) { + result.diagnosticResponse_ = diagnosticResponse_; + } else { + result.diagnosticResponse_ = diagnosticResponseBuilder_.build(); + } + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000010; + } + if (controlCommandBuilder_ == null) { + result.controlCommand_ = controlCommand_; + } else { + result.controlCommand_ = controlCommandBuilder_.build(); + } + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000020; + } + if (commandResponseBuilder_ == null) { + result.commandResponse_ = commandResponse_; + } else { + result.commandResponse_ = commandResponseBuilder_.build(); + } + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000040; + } + result.timestamp_ = timestamp_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.VehicleMessage) { + return mergeFrom((com.openxc.BinaryMessages.VehicleMessage)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.VehicleMessage other) { + if (other == com.openxc.BinaryMessages.VehicleMessage.getDefaultInstance()) return this; + if (other.hasType()) { + setType(other.getType()); + } + if (other.hasCanMessage()) { + mergeCanMessage(other.getCanMessage()); + } + if (other.hasSimpleMessage()) { + mergeSimpleMessage(other.getSimpleMessage()); + } + if (other.hasDiagnosticResponse()) { + mergeDiagnosticResponse(other.getDiagnosticResponse()); + } + if (other.hasControlCommand()) { + mergeControlCommand(other.getControlCommand()); + } + if (other.hasCommandResponse()) { + mergeCommandResponse(other.getCommandResponse()); + } + if (other.hasTimestamp()) { + setTimestamp(other.getTimestamp()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + int rawValue = input.readEnum(); + com.openxc.BinaryMessages.VehicleMessage.Type value = com.openxc.BinaryMessages.VehicleMessage.Type.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(1, rawValue); + } else { + bitField0_ |= 0x00000001; + type_ = value; + } + break; + } + case 18: { + com.openxc.BinaryMessages.CanMessage.Builder subBuilder = com.openxc.BinaryMessages.CanMessage.newBuilder(); + if (hasCanMessage()) { + subBuilder.mergeFrom(getCanMessage()); + } + input.readMessage(subBuilder, extensionRegistry); + setCanMessage(subBuilder.buildPartial()); + break; + } + case 26: { + com.openxc.BinaryMessages.SimpleMessage.Builder subBuilder = com.openxc.BinaryMessages.SimpleMessage.newBuilder(); + if (hasSimpleMessage()) { + subBuilder.mergeFrom(getSimpleMessage()); + } + input.readMessage(subBuilder, extensionRegistry); + setSimpleMessage(subBuilder.buildPartial()); + break; + } + case 34: { + com.openxc.BinaryMessages.DiagnosticResponse.Builder subBuilder = com.openxc.BinaryMessages.DiagnosticResponse.newBuilder(); + if (hasDiagnosticResponse()) { + subBuilder.mergeFrom(getDiagnosticResponse()); + } + input.readMessage(subBuilder, extensionRegistry); + setDiagnosticResponse(subBuilder.buildPartial()); + break; + } + case 42: { + com.openxc.BinaryMessages.ControlCommand.Builder subBuilder = com.openxc.BinaryMessages.ControlCommand.newBuilder(); + if (hasControlCommand()) { + subBuilder.mergeFrom(getControlCommand()); + } + input.readMessage(subBuilder, extensionRegistry); + setControlCommand(subBuilder.buildPartial()); + break; + } + case 50: { + com.openxc.BinaryMessages.CommandResponse.Builder subBuilder = com.openxc.BinaryMessages.CommandResponse.newBuilder(); + if (hasCommandResponse()) { + subBuilder.mergeFrom(getCommandResponse()); + } + input.readMessage(subBuilder, extensionRegistry); + setCommandResponse(subBuilder.buildPartial()); + break; + } + case 56: { + bitField0_ |= 0x00000040; + timestamp_ = input.readUInt64(); + break; + } + } + } + } + + private int bitField0_; + + // optional .openxc.VehicleMessage.Type type = 1; + private com.openxc.BinaryMessages.VehicleMessage.Type type_ = com.openxc.BinaryMessages.VehicleMessage.Type.CAN; + public boolean hasType() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.VehicleMessage.Type getType() { + return type_; + } + public Builder setType(com.openxc.BinaryMessages.VehicleMessage.Type value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + type_ = value; + onChanged(); + return this; + } + public Builder clearType() { + bitField0_ = (bitField0_ & ~0x00000001); + type_ = com.openxc.BinaryMessages.VehicleMessage.Type.CAN; + onChanged(); + return this; + } + + // optional .openxc.CanMessage can_message = 2; + private com.openxc.BinaryMessages.CanMessage canMessage_ = com.openxc.BinaryMessages.CanMessage.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.CanMessage, com.openxc.BinaryMessages.CanMessage.Builder, com.openxc.BinaryMessages.CanMessageOrBuilder> canMessageBuilder_; + public boolean hasCanMessage() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.CanMessage getCanMessage() { + if (canMessageBuilder_ == null) { + return canMessage_; + } else { + return canMessageBuilder_.getMessage(); + } + } + public Builder setCanMessage(com.openxc.BinaryMessages.CanMessage value) { + if (canMessageBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + canMessage_ = value; + onChanged(); + } else { + canMessageBuilder_.setMessage(value); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder setCanMessage( + com.openxc.BinaryMessages.CanMessage.Builder builderForValue) { + if (canMessageBuilder_ == null) { + canMessage_ = builderForValue.build(); + onChanged(); + } else { + canMessageBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder mergeCanMessage(com.openxc.BinaryMessages.CanMessage value) { + if (canMessageBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002) && + canMessage_ != com.openxc.BinaryMessages.CanMessage.getDefaultInstance()) { + canMessage_ = + com.openxc.BinaryMessages.CanMessage.newBuilder(canMessage_).mergeFrom(value).buildPartial(); + } else { + canMessage_ = value; + } + onChanged(); + } else { + canMessageBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder clearCanMessage() { + if (canMessageBuilder_ == null) { + canMessage_ = com.openxc.BinaryMessages.CanMessage.getDefaultInstance(); + onChanged(); + } else { + canMessageBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + public com.openxc.BinaryMessages.CanMessage.Builder getCanMessageBuilder() { + bitField0_ |= 0x00000002; + onChanged(); + return getCanMessageFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.CanMessageOrBuilder getCanMessageOrBuilder() { + if (canMessageBuilder_ != null) { + return canMessageBuilder_.getMessageOrBuilder(); + } else { + return canMessage_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.CanMessage, com.openxc.BinaryMessages.CanMessage.Builder, com.openxc.BinaryMessages.CanMessageOrBuilder> + getCanMessageFieldBuilder() { + if (canMessageBuilder_ == null) { + canMessageBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.CanMessage, com.openxc.BinaryMessages.CanMessage.Builder, com.openxc.BinaryMessages.CanMessageOrBuilder>( + canMessage_, + getParentForChildren(), + isClean()); + canMessage_ = null; + } + return canMessageBuilder_; + } + + // optional .openxc.SimpleMessage simple_message = 3; + private com.openxc.BinaryMessages.SimpleMessage simpleMessage_ = com.openxc.BinaryMessages.SimpleMessage.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.SimpleMessage, com.openxc.BinaryMessages.SimpleMessage.Builder, com.openxc.BinaryMessages.SimpleMessageOrBuilder> simpleMessageBuilder_; + public boolean hasSimpleMessage() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.openxc.BinaryMessages.SimpleMessage getSimpleMessage() { + if (simpleMessageBuilder_ == null) { + return simpleMessage_; + } else { + return simpleMessageBuilder_.getMessage(); + } + } + public Builder setSimpleMessage(com.openxc.BinaryMessages.SimpleMessage value) { + if (simpleMessageBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + simpleMessage_ = value; + onChanged(); + } else { + simpleMessageBuilder_.setMessage(value); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder setSimpleMessage( + com.openxc.BinaryMessages.SimpleMessage.Builder builderForValue) { + if (simpleMessageBuilder_ == null) { + simpleMessage_ = builderForValue.build(); + onChanged(); + } else { + simpleMessageBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder mergeSimpleMessage(com.openxc.BinaryMessages.SimpleMessage value) { + if (simpleMessageBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + simpleMessage_ != com.openxc.BinaryMessages.SimpleMessage.getDefaultInstance()) { + simpleMessage_ = + com.openxc.BinaryMessages.SimpleMessage.newBuilder(simpleMessage_).mergeFrom(value).buildPartial(); + } else { + simpleMessage_ = value; + } + onChanged(); + } else { + simpleMessageBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder clearSimpleMessage() { + if (simpleMessageBuilder_ == null) { + simpleMessage_ = com.openxc.BinaryMessages.SimpleMessage.getDefaultInstance(); + onChanged(); + } else { + simpleMessageBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + public com.openxc.BinaryMessages.SimpleMessage.Builder getSimpleMessageBuilder() { + bitField0_ |= 0x00000004; + onChanged(); + return getSimpleMessageFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.SimpleMessageOrBuilder getSimpleMessageOrBuilder() { + if (simpleMessageBuilder_ != null) { + return simpleMessageBuilder_.getMessageOrBuilder(); + } else { + return simpleMessage_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.SimpleMessage, com.openxc.BinaryMessages.SimpleMessage.Builder, com.openxc.BinaryMessages.SimpleMessageOrBuilder> + getSimpleMessageFieldBuilder() { + if (simpleMessageBuilder_ == null) { + simpleMessageBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.SimpleMessage, com.openxc.BinaryMessages.SimpleMessage.Builder, com.openxc.BinaryMessages.SimpleMessageOrBuilder>( + simpleMessage_, + getParentForChildren(), + isClean()); + simpleMessage_ = null; + } + return simpleMessageBuilder_; + } + + // optional .openxc.DiagnosticResponse diagnostic_response = 4; + private com.openxc.BinaryMessages.DiagnosticResponse diagnosticResponse_ = com.openxc.BinaryMessages.DiagnosticResponse.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DiagnosticResponse, com.openxc.BinaryMessages.DiagnosticResponse.Builder, com.openxc.BinaryMessages.DiagnosticResponseOrBuilder> diagnosticResponseBuilder_; + public boolean hasDiagnosticResponse() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public com.openxc.BinaryMessages.DiagnosticResponse getDiagnosticResponse() { + if (diagnosticResponseBuilder_ == null) { + return diagnosticResponse_; + } else { + return diagnosticResponseBuilder_.getMessage(); + } + } + public Builder setDiagnosticResponse(com.openxc.BinaryMessages.DiagnosticResponse value) { + if (diagnosticResponseBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + diagnosticResponse_ = value; + onChanged(); + } else { + diagnosticResponseBuilder_.setMessage(value); + } + bitField0_ |= 0x00000008; + return this; + } + public Builder setDiagnosticResponse( + com.openxc.BinaryMessages.DiagnosticResponse.Builder builderForValue) { + if (diagnosticResponseBuilder_ == null) { + diagnosticResponse_ = builderForValue.build(); + onChanged(); + } else { + diagnosticResponseBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000008; + return this; + } + public Builder mergeDiagnosticResponse(com.openxc.BinaryMessages.DiagnosticResponse value) { + if (diagnosticResponseBuilder_ == null) { + if (((bitField0_ & 0x00000008) == 0x00000008) && + diagnosticResponse_ != com.openxc.BinaryMessages.DiagnosticResponse.getDefaultInstance()) { + diagnosticResponse_ = + com.openxc.BinaryMessages.DiagnosticResponse.newBuilder(diagnosticResponse_).mergeFrom(value).buildPartial(); + } else { + diagnosticResponse_ = value; + } + onChanged(); + } else { + diagnosticResponseBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000008; + return this; + } + public Builder clearDiagnosticResponse() { + if (diagnosticResponseBuilder_ == null) { + diagnosticResponse_ = com.openxc.BinaryMessages.DiagnosticResponse.getDefaultInstance(); + onChanged(); + } else { + diagnosticResponseBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000008); + return this; + } + public com.openxc.BinaryMessages.DiagnosticResponse.Builder getDiagnosticResponseBuilder() { + bitField0_ |= 0x00000008; + onChanged(); + return getDiagnosticResponseFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.DiagnosticResponseOrBuilder getDiagnosticResponseOrBuilder() { + if (diagnosticResponseBuilder_ != null) { + return diagnosticResponseBuilder_.getMessageOrBuilder(); + } else { + return diagnosticResponse_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DiagnosticResponse, com.openxc.BinaryMessages.DiagnosticResponse.Builder, com.openxc.BinaryMessages.DiagnosticResponseOrBuilder> + getDiagnosticResponseFieldBuilder() { + if (diagnosticResponseBuilder_ == null) { + diagnosticResponseBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DiagnosticResponse, com.openxc.BinaryMessages.DiagnosticResponse.Builder, com.openxc.BinaryMessages.DiagnosticResponseOrBuilder>( + diagnosticResponse_, + getParentForChildren(), + isClean()); + diagnosticResponse_ = null; + } + return diagnosticResponseBuilder_; + } + + // optional .openxc.ControlCommand control_command = 5; + private com.openxc.BinaryMessages.ControlCommand controlCommand_ = com.openxc.BinaryMessages.ControlCommand.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.ControlCommand, com.openxc.BinaryMessages.ControlCommand.Builder, com.openxc.BinaryMessages.ControlCommandOrBuilder> controlCommandBuilder_; + public boolean hasControlCommand() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + public com.openxc.BinaryMessages.ControlCommand getControlCommand() { + if (controlCommandBuilder_ == null) { + return controlCommand_; + } else { + return controlCommandBuilder_.getMessage(); + } + } + public Builder setControlCommand(com.openxc.BinaryMessages.ControlCommand value) { + if (controlCommandBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + controlCommand_ = value; + onChanged(); + } else { + controlCommandBuilder_.setMessage(value); + } + bitField0_ |= 0x00000010; + return this; + } + public Builder setControlCommand( + com.openxc.BinaryMessages.ControlCommand.Builder builderForValue) { + if (controlCommandBuilder_ == null) { + controlCommand_ = builderForValue.build(); + onChanged(); + } else { + controlCommandBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000010; + return this; + } + public Builder mergeControlCommand(com.openxc.BinaryMessages.ControlCommand value) { + if (controlCommandBuilder_ == null) { + if (((bitField0_ & 0x00000010) == 0x00000010) && + controlCommand_ != com.openxc.BinaryMessages.ControlCommand.getDefaultInstance()) { + controlCommand_ = + com.openxc.BinaryMessages.ControlCommand.newBuilder(controlCommand_).mergeFrom(value).buildPartial(); + } else { + controlCommand_ = value; + } + onChanged(); + } else { + controlCommandBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000010; + return this; + } + public Builder clearControlCommand() { + if (controlCommandBuilder_ == null) { + controlCommand_ = com.openxc.BinaryMessages.ControlCommand.getDefaultInstance(); + onChanged(); + } else { + controlCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000010); + return this; + } + public com.openxc.BinaryMessages.ControlCommand.Builder getControlCommandBuilder() { + bitField0_ |= 0x00000010; + onChanged(); + return getControlCommandFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.ControlCommandOrBuilder getControlCommandOrBuilder() { + if (controlCommandBuilder_ != null) { + return controlCommandBuilder_.getMessageOrBuilder(); + } else { + return controlCommand_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.ControlCommand, com.openxc.BinaryMessages.ControlCommand.Builder, com.openxc.BinaryMessages.ControlCommandOrBuilder> + getControlCommandFieldBuilder() { + if (controlCommandBuilder_ == null) { + controlCommandBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.ControlCommand, com.openxc.BinaryMessages.ControlCommand.Builder, com.openxc.BinaryMessages.ControlCommandOrBuilder>( + controlCommand_, + getParentForChildren(), + isClean()); + controlCommand_ = null; + } + return controlCommandBuilder_; + } + + // optional .openxc.CommandResponse command_response = 6; + private com.openxc.BinaryMessages.CommandResponse commandResponse_ = com.openxc.BinaryMessages.CommandResponse.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.CommandResponse, com.openxc.BinaryMessages.CommandResponse.Builder, com.openxc.BinaryMessages.CommandResponseOrBuilder> commandResponseBuilder_; + public boolean hasCommandResponse() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + public com.openxc.BinaryMessages.CommandResponse getCommandResponse() { + if (commandResponseBuilder_ == null) { + return commandResponse_; + } else { + return commandResponseBuilder_.getMessage(); + } + } + public Builder setCommandResponse(com.openxc.BinaryMessages.CommandResponse value) { + if (commandResponseBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + commandResponse_ = value; + onChanged(); + } else { + commandResponseBuilder_.setMessage(value); + } + bitField0_ |= 0x00000020; + return this; + } + public Builder setCommandResponse( + com.openxc.BinaryMessages.CommandResponse.Builder builderForValue) { + if (commandResponseBuilder_ == null) { + commandResponse_ = builderForValue.build(); + onChanged(); + } else { + commandResponseBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000020; + return this; + } + public Builder mergeCommandResponse(com.openxc.BinaryMessages.CommandResponse value) { + if (commandResponseBuilder_ == null) { + if (((bitField0_ & 0x00000020) == 0x00000020) && + commandResponse_ != com.openxc.BinaryMessages.CommandResponse.getDefaultInstance()) { + commandResponse_ = + com.openxc.BinaryMessages.CommandResponse.newBuilder(commandResponse_).mergeFrom(value).buildPartial(); + } else { + commandResponse_ = value; + } + onChanged(); + } else { + commandResponseBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000020; + return this; + } + public Builder clearCommandResponse() { + if (commandResponseBuilder_ == null) { + commandResponse_ = com.openxc.BinaryMessages.CommandResponse.getDefaultInstance(); + onChanged(); + } else { + commandResponseBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000020); + return this; + } + public com.openxc.BinaryMessages.CommandResponse.Builder getCommandResponseBuilder() { + bitField0_ |= 0x00000020; + onChanged(); + return getCommandResponseFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.CommandResponseOrBuilder getCommandResponseOrBuilder() { + if (commandResponseBuilder_ != null) { + return commandResponseBuilder_.getMessageOrBuilder(); + } else { + return commandResponse_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.CommandResponse, com.openxc.BinaryMessages.CommandResponse.Builder, com.openxc.BinaryMessages.CommandResponseOrBuilder> + getCommandResponseFieldBuilder() { + if (commandResponseBuilder_ == null) { + commandResponseBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.CommandResponse, com.openxc.BinaryMessages.CommandResponse.Builder, com.openxc.BinaryMessages.CommandResponseOrBuilder>( + commandResponse_, + getParentForChildren(), + isClean()); + commandResponse_ = null; + } + return commandResponseBuilder_; + } + + // optional uint64 timestamp = 7; + private long timestamp_ ; + public boolean hasTimestamp() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + public long getTimestamp() { + return timestamp_; + } + public Builder setTimestamp(long value) { + bitField0_ |= 0x00000040; + timestamp_ = value; + onChanged(); + return this; + } + public Builder clearTimestamp() { + bitField0_ = (bitField0_ & ~0x00000040); + timestamp_ = 0L; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.VehicleMessage) + } + + static { + defaultInstance = new VehicleMessage(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.VehicleMessage) + } + + public interface CanMessageOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional int32 bus = 1; + boolean hasBus(); + int getBus(); + + // optional uint32 id = 2; + boolean hasId(); + int getId(); + + // optional bytes data = 3; + boolean hasData(); + com.google.protobuf.ByteString getData(); + + // optional .openxc.CanMessage.FrameFormat frame_format = 4; + boolean hasFrameFormat(); + com.openxc.BinaryMessages.CanMessage.FrameFormat getFrameFormat(); + } + public static final class CanMessage extends + com.google.protobuf.GeneratedMessage + implements CanMessageOrBuilder { + // Use CanMessage.newBuilder() to construct. + private CanMessage(Builder builder) { + super(builder); + } + private CanMessage(boolean noInit) {} + + private static final CanMessage defaultInstance; + public static CanMessage getDefaultInstance() { + return defaultInstance; + } + + public CanMessage getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_CanMessage_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_CanMessage_fieldAccessorTable; + } + + public enum FrameFormat + implements com.google.protobuf.ProtocolMessageEnum { + STANDARD(0, 1), + EXTENDED(1, 2), + ; + + public static final int STANDARD_VALUE = 1; + public static final int EXTENDED_VALUE = 2; + + + public final int getNumber() { return value; } + + public static FrameFormat valueOf(int value) { + switch (value) { + case 1: return STANDARD; + case 2: return EXTENDED; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public FrameFormat findValueByNumber(int number) { + return FrameFormat.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return com.openxc.BinaryMessages.CanMessage.getDescriptor().getEnumTypes().get(0); + } + + private static final FrameFormat[] VALUES = { + STANDARD, EXTENDED, + }; + + public static FrameFormat valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private FrameFormat(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:openxc.CanMessage.FrameFormat) + } + + private int bitField0_; + // optional int32 bus = 1; + public static final int BUS_FIELD_NUMBER = 1; + private int bus_; + public boolean hasBus() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getBus() { + return bus_; + } + + // optional uint32 id = 2; + public static final int ID_FIELD_NUMBER = 2; + private int id_; + public boolean hasId() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public int getId() { + return id_; + } + + // optional bytes data = 3; + public static final int DATA_FIELD_NUMBER = 3; + private com.google.protobuf.ByteString data_; + public boolean hasData() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.google.protobuf.ByteString getData() { + return data_; + } + + // optional .openxc.CanMessage.FrameFormat frame_format = 4; + public static final int FRAME_FORMAT_FIELD_NUMBER = 4; + private com.openxc.BinaryMessages.CanMessage.FrameFormat frameFormat_; + public boolean hasFrameFormat() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public com.openxc.BinaryMessages.CanMessage.FrameFormat getFrameFormat() { + return frameFormat_; + } + + private void initFields() { + bus_ = 0; + id_ = 0; + data_ = com.google.protobuf.ByteString.EMPTY; + frameFormat_ = com.openxc.BinaryMessages.CanMessage.FrameFormat.STANDARD; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, bus_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeUInt32(2, id_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeBytes(3, data_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeEnum(4, frameFormat_.getNumber()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, bus_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(2, id_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(3, data_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(4, frameFormat_.getNumber()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.CanMessage parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.CanMessage parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.CanMessage parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.CanMessage parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.CanMessage parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.CanMessage parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.CanMessage parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.CanMessage parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.CanMessage parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.CanMessage parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.CanMessage prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.CanMessageOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_CanMessage_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_CanMessage_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.CanMessage.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + bus_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + id_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); + data_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000004); + frameFormat_ = com.openxc.BinaryMessages.CanMessage.FrameFormat.STANDARD; + bitField0_ = (bitField0_ & ~0x00000008); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.CanMessage.getDescriptor(); + } + + public com.openxc.BinaryMessages.CanMessage getDefaultInstanceForType() { + return com.openxc.BinaryMessages.CanMessage.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.CanMessage build() { + com.openxc.BinaryMessages.CanMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.CanMessage buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.CanMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.CanMessage buildPartial() { + com.openxc.BinaryMessages.CanMessage result = new com.openxc.BinaryMessages.CanMessage(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.bus_ = bus_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.id_ = id_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.data_ = data_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.frameFormat_ = frameFormat_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.CanMessage) { + return mergeFrom((com.openxc.BinaryMessages.CanMessage)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.CanMessage other) { + if (other == com.openxc.BinaryMessages.CanMessage.getDefaultInstance()) return this; + if (other.hasBus()) { + setBus(other.getBus()); + } + if (other.hasId()) { + setId(other.getId()); + } + if (other.hasData()) { + setData(other.getData()); + } + if (other.hasFrameFormat()) { + setFrameFormat(other.getFrameFormat()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + bus_ = input.readInt32(); + break; + } + case 16: { + bitField0_ |= 0x00000002; + id_ = input.readUInt32(); + break; + } + case 26: { + bitField0_ |= 0x00000004; + data_ = input.readBytes(); + break; + } + case 32: { + int rawValue = input.readEnum(); + com.openxc.BinaryMessages.CanMessage.FrameFormat value = com.openxc.BinaryMessages.CanMessage.FrameFormat.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(4, rawValue); + } else { + bitField0_ |= 0x00000008; + frameFormat_ = value; + } + break; + } + } + } + } + + private int bitField0_; + + // optional int32 bus = 1; + private int bus_ ; + public boolean hasBus() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getBus() { + return bus_; + } + public Builder setBus(int value) { + bitField0_ |= 0x00000001; + bus_ = value; + onChanged(); + return this; + } + public Builder clearBus() { + bitField0_ = (bitField0_ & ~0x00000001); + bus_ = 0; + onChanged(); + return this; + } + + // optional uint32 id = 2; + private int id_ ; + public boolean hasId() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public int getId() { + return id_; + } + public Builder setId(int value) { + bitField0_ |= 0x00000002; + id_ = value; + onChanged(); + return this; + } + public Builder clearId() { + bitField0_ = (bitField0_ & ~0x00000002); + id_ = 0; + onChanged(); + return this; + } + + // optional bytes data = 3; + private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; + public boolean hasData() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.google.protobuf.ByteString getData() { + return data_; + } + public Builder setData(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000004; + data_ = value; + onChanged(); + return this; + } + public Builder clearData() { + bitField0_ = (bitField0_ & ~0x00000004); + data_ = getDefaultInstance().getData(); + onChanged(); + return this; + } + + // optional .openxc.CanMessage.FrameFormat frame_format = 4; + private com.openxc.BinaryMessages.CanMessage.FrameFormat frameFormat_ = com.openxc.BinaryMessages.CanMessage.FrameFormat.STANDARD; + public boolean hasFrameFormat() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public com.openxc.BinaryMessages.CanMessage.FrameFormat getFrameFormat() { + return frameFormat_; + } + public Builder setFrameFormat(com.openxc.BinaryMessages.CanMessage.FrameFormat value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000008; + frameFormat_ = value; + onChanged(); + return this; + } + public Builder clearFrameFormat() { + bitField0_ = (bitField0_ & ~0x00000008); + frameFormat_ = com.openxc.BinaryMessages.CanMessage.FrameFormat.STANDARD; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.CanMessage) + } + + static { + defaultInstance = new CanMessage(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.CanMessage) + } + + public interface ControlCommandOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional .openxc.ControlCommand.Type type = 1; + boolean hasType(); + com.openxc.BinaryMessages.ControlCommand.Type getType(); + + // optional .openxc.DiagnosticControlCommand diagnostic_request = 2; + boolean hasDiagnosticRequest(); + com.openxc.BinaryMessages.DiagnosticControlCommand getDiagnosticRequest(); + com.openxc.BinaryMessages.DiagnosticControlCommandOrBuilder getDiagnosticRequestOrBuilder(); + + // optional .openxc.PassthroughModeControlCommand passthrough_mode_request = 3; + boolean hasPassthroughModeRequest(); + com.openxc.BinaryMessages.PassthroughModeControlCommand getPassthroughModeRequest(); + com.openxc.BinaryMessages.PassthroughModeControlCommandOrBuilder getPassthroughModeRequestOrBuilder(); + + // optional .openxc.AcceptanceFilterBypassCommand acceptance_filter_bypass_command = 4; + boolean hasAcceptanceFilterBypassCommand(); + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand getAcceptanceFilterBypassCommand(); + com.openxc.BinaryMessages.AcceptanceFilterBypassCommandOrBuilder getAcceptanceFilterBypassCommandOrBuilder(); + + // optional .openxc.PayloadFormatCommand payload_format_command = 5; + boolean hasPayloadFormatCommand(); + com.openxc.BinaryMessages.PayloadFormatCommand getPayloadFormatCommand(); + com.openxc.BinaryMessages.PayloadFormatCommandOrBuilder getPayloadFormatCommandOrBuilder(); + + // optional .openxc.PredefinedObd2RequestsCommand predefined_obd2_requests_command = 6; + boolean hasPredefinedObd2RequestsCommand(); + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand getPredefinedObd2RequestsCommand(); + com.openxc.BinaryMessages.PredefinedObd2RequestsCommandOrBuilder getPredefinedObd2RequestsCommandOrBuilder(); + + // optional .openxc.ModemConfigurationCommand modem_configuration_command = 7; + boolean hasModemConfigurationCommand(); + com.openxc.BinaryMessages.ModemConfigurationCommand getModemConfigurationCommand(); + com.openxc.BinaryMessages.ModemConfigurationCommandOrBuilder getModemConfigurationCommandOrBuilder(); + + // optional .openxc.RTCConfigurationCommand rtc_configuration_command = 8; + boolean hasRtcConfigurationCommand(); + com.openxc.BinaryMessages.RTCConfigurationCommand getRtcConfigurationCommand(); + com.openxc.BinaryMessages.RTCConfigurationCommandOrBuilder getRtcConfigurationCommandOrBuilder(); + } + public static final class ControlCommand extends + com.google.protobuf.GeneratedMessage + implements ControlCommandOrBuilder { + // Use ControlCommand.newBuilder() to construct. + private ControlCommand(Builder builder) { + super(builder); + } + private ControlCommand(boolean noInit) {} + + private static final ControlCommand defaultInstance; + public static ControlCommand getDefaultInstance() { + return defaultInstance; + } + + public ControlCommand getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_ControlCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_ControlCommand_fieldAccessorTable; + } + + public enum Type + implements com.google.protobuf.ProtocolMessageEnum { + VERSION(0, 1), + DEVICE_ID(1, 2), + DIAGNOSTIC(2, 3), + PASSTHROUGH(3, 4), + ACCEPTANCE_FILTER_BYPASS(4, 5), + PAYLOAD_FORMAT(5, 6), + PREDEFINED_OBD2_REQUESTS(6, 7), + MODEM_CONFIGURATION(7, 8), + RTC_CONFIGURATION(8, 9), + SD_MOUNT_STATUS(9, 10), + PLATFORM(10, 11), + ; + + public static final int VERSION_VALUE = 1; + public static final int DEVICE_ID_VALUE = 2; + public static final int DIAGNOSTIC_VALUE = 3; + public static final int PASSTHROUGH_VALUE = 4; + public static final int ACCEPTANCE_FILTER_BYPASS_VALUE = 5; + public static final int PAYLOAD_FORMAT_VALUE = 6; + public static final int PREDEFINED_OBD2_REQUESTS_VALUE = 7; + public static final int MODEM_CONFIGURATION_VALUE = 8; + public static final int RTC_CONFIGURATION_VALUE = 9; + public static final int SD_MOUNT_STATUS_VALUE = 10; + public static final int PLATFORM_VALUE = 11; + + + public final int getNumber() { return value; } + + public static Type valueOf(int value) { + switch (value) { + case 1: return VERSION; + case 2: return DEVICE_ID; + case 3: return DIAGNOSTIC; + case 4: return PASSTHROUGH; + case 5: return ACCEPTANCE_FILTER_BYPASS; + case 6: return PAYLOAD_FORMAT; + case 7: return PREDEFINED_OBD2_REQUESTS; + case 8: return MODEM_CONFIGURATION; + case 9: return RTC_CONFIGURATION; + case 10: return SD_MOUNT_STATUS; + case 11: return PLATFORM; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public Type findValueByNumber(int number) { + return Type.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return com.openxc.BinaryMessages.ControlCommand.getDescriptor().getEnumTypes().get(0); + } + + private static final Type[] VALUES = { + VERSION, DEVICE_ID, DIAGNOSTIC, PASSTHROUGH, ACCEPTANCE_FILTER_BYPASS, PAYLOAD_FORMAT, PREDEFINED_OBD2_REQUESTS, MODEM_CONFIGURATION, RTC_CONFIGURATION, SD_MOUNT_STATUS, PLATFORM, + }; + + public static Type valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private Type(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:openxc.ControlCommand.Type) + } + + private int bitField0_; + // optional .openxc.ControlCommand.Type type = 1; + public static final int TYPE_FIELD_NUMBER = 1; + private com.openxc.BinaryMessages.ControlCommand.Type type_; + public boolean hasType() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.ControlCommand.Type getType() { + return type_; + } + + // optional .openxc.DiagnosticControlCommand diagnostic_request = 2; + public static final int DIAGNOSTIC_REQUEST_FIELD_NUMBER = 2; + private com.openxc.BinaryMessages.DiagnosticControlCommand diagnosticRequest_; + public boolean hasDiagnosticRequest() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.DiagnosticControlCommand getDiagnosticRequest() { + return diagnosticRequest_; + } + public com.openxc.BinaryMessages.DiagnosticControlCommandOrBuilder getDiagnosticRequestOrBuilder() { + return diagnosticRequest_; + } + + // optional .openxc.PassthroughModeControlCommand passthrough_mode_request = 3; + public static final int PASSTHROUGH_MODE_REQUEST_FIELD_NUMBER = 3; + private com.openxc.BinaryMessages.PassthroughModeControlCommand passthroughModeRequest_; + public boolean hasPassthroughModeRequest() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.openxc.BinaryMessages.PassthroughModeControlCommand getPassthroughModeRequest() { + return passthroughModeRequest_; + } + public com.openxc.BinaryMessages.PassthroughModeControlCommandOrBuilder getPassthroughModeRequestOrBuilder() { + return passthroughModeRequest_; + } + + // optional .openxc.AcceptanceFilterBypassCommand acceptance_filter_bypass_command = 4; + public static final int ACCEPTANCE_FILTER_BYPASS_COMMAND_FIELD_NUMBER = 4; + private com.openxc.BinaryMessages.AcceptanceFilterBypassCommand acceptanceFilterBypassCommand_; + public boolean hasAcceptanceFilterBypassCommand() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public com.openxc.BinaryMessages.AcceptanceFilterBypassCommand getAcceptanceFilterBypassCommand() { + return acceptanceFilterBypassCommand_; + } + public com.openxc.BinaryMessages.AcceptanceFilterBypassCommandOrBuilder getAcceptanceFilterBypassCommandOrBuilder() { + return acceptanceFilterBypassCommand_; + } + + // optional .openxc.PayloadFormatCommand payload_format_command = 5; + public static final int PAYLOAD_FORMAT_COMMAND_FIELD_NUMBER = 5; + private com.openxc.BinaryMessages.PayloadFormatCommand payloadFormatCommand_; + public boolean hasPayloadFormatCommand() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + public com.openxc.BinaryMessages.PayloadFormatCommand getPayloadFormatCommand() { + return payloadFormatCommand_; + } + public com.openxc.BinaryMessages.PayloadFormatCommandOrBuilder getPayloadFormatCommandOrBuilder() { + return payloadFormatCommand_; + } + + // optional .openxc.PredefinedObd2RequestsCommand predefined_obd2_requests_command = 6; + public static final int PREDEFINED_OBD2_REQUESTS_COMMAND_FIELD_NUMBER = 6; + private com.openxc.BinaryMessages.PredefinedObd2RequestsCommand predefinedObd2RequestsCommand_; + public boolean hasPredefinedObd2RequestsCommand() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + public com.openxc.BinaryMessages.PredefinedObd2RequestsCommand getPredefinedObd2RequestsCommand() { + return predefinedObd2RequestsCommand_; + } + public com.openxc.BinaryMessages.PredefinedObd2RequestsCommandOrBuilder getPredefinedObd2RequestsCommandOrBuilder() { + return predefinedObd2RequestsCommand_; + } + + // optional .openxc.ModemConfigurationCommand modem_configuration_command = 7; + public static final int MODEM_CONFIGURATION_COMMAND_FIELD_NUMBER = 7; + private com.openxc.BinaryMessages.ModemConfigurationCommand modemConfigurationCommand_; + public boolean hasModemConfigurationCommand() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + public com.openxc.BinaryMessages.ModemConfigurationCommand getModemConfigurationCommand() { + return modemConfigurationCommand_; + } + public com.openxc.BinaryMessages.ModemConfigurationCommandOrBuilder getModemConfigurationCommandOrBuilder() { + return modemConfigurationCommand_; + } + + // optional .openxc.RTCConfigurationCommand rtc_configuration_command = 8; + public static final int RTC_CONFIGURATION_COMMAND_FIELD_NUMBER = 8; + private com.openxc.BinaryMessages.RTCConfigurationCommand rtcConfigurationCommand_; + public boolean hasRtcConfigurationCommand() { + return ((bitField0_ & 0x00000080) == 0x00000080); + } + public com.openxc.BinaryMessages.RTCConfigurationCommand getRtcConfigurationCommand() { + return rtcConfigurationCommand_; + } + public com.openxc.BinaryMessages.RTCConfigurationCommandOrBuilder getRtcConfigurationCommandOrBuilder() { + return rtcConfigurationCommand_; + } + + private void initFields() { + type_ = com.openxc.BinaryMessages.ControlCommand.Type.VERSION; + diagnosticRequest_ = com.openxc.BinaryMessages.DiagnosticControlCommand.getDefaultInstance(); + passthroughModeRequest_ = com.openxc.BinaryMessages.PassthroughModeControlCommand.getDefaultInstance(); + acceptanceFilterBypassCommand_ = com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.getDefaultInstance(); + payloadFormatCommand_ = com.openxc.BinaryMessages.PayloadFormatCommand.getDefaultInstance(); + predefinedObd2RequestsCommand_ = com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.getDefaultInstance(); + modemConfigurationCommand_ = com.openxc.BinaryMessages.ModemConfigurationCommand.getDefaultInstance(); + rtcConfigurationCommand_ = com.openxc.BinaryMessages.RTCConfigurationCommand.getDefaultInstance(); + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeEnum(1, type_.getNumber()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeMessage(2, diagnosticRequest_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, passthroughModeRequest_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeMessage(4, acceptanceFilterBypassCommand_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeMessage(5, payloadFormatCommand_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + output.writeMessage(6, predefinedObd2RequestsCommand_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeMessage(7, modemConfigurationCommand_); + } + if (((bitField0_ & 0x00000080) == 0x00000080)) { + output.writeMessage(8, rtcConfigurationCommand_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(1, type_.getNumber()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, diagnosticRequest_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, passthroughModeRequest_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, acceptanceFilterBypassCommand_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, payloadFormatCommand_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, predefinedObd2RequestsCommand_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(7, modemConfigurationCommand_); + } + if (((bitField0_ & 0x00000080) == 0x00000080)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(8, rtcConfigurationCommand_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.ControlCommand parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.ControlCommand parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.ControlCommand parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.ControlCommand parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.ControlCommand parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.ControlCommand parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.ControlCommand parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.ControlCommand parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.ControlCommand parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.ControlCommand parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.ControlCommand prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.ControlCommandOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_ControlCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_ControlCommand_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.ControlCommand.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getDiagnosticRequestFieldBuilder(); + getPassthroughModeRequestFieldBuilder(); + getAcceptanceFilterBypassCommandFieldBuilder(); + getPayloadFormatCommandFieldBuilder(); + getPredefinedObd2RequestsCommandFieldBuilder(); + getModemConfigurationCommandFieldBuilder(); + getRtcConfigurationCommandFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + type_ = com.openxc.BinaryMessages.ControlCommand.Type.VERSION; + bitField0_ = (bitField0_ & ~0x00000001); + if (diagnosticRequestBuilder_ == null) { + diagnosticRequest_ = com.openxc.BinaryMessages.DiagnosticControlCommand.getDefaultInstance(); + } else { + diagnosticRequestBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + if (passthroughModeRequestBuilder_ == null) { + passthroughModeRequest_ = com.openxc.BinaryMessages.PassthroughModeControlCommand.getDefaultInstance(); + } else { + passthroughModeRequestBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + if (acceptanceFilterBypassCommandBuilder_ == null) { + acceptanceFilterBypassCommand_ = com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.getDefaultInstance(); + } else { + acceptanceFilterBypassCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000008); + if (payloadFormatCommandBuilder_ == null) { + payloadFormatCommand_ = com.openxc.BinaryMessages.PayloadFormatCommand.getDefaultInstance(); + } else { + payloadFormatCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000010); + if (predefinedObd2RequestsCommandBuilder_ == null) { + predefinedObd2RequestsCommand_ = com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.getDefaultInstance(); + } else { + predefinedObd2RequestsCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000020); + if (modemConfigurationCommandBuilder_ == null) { + modemConfigurationCommand_ = com.openxc.BinaryMessages.ModemConfigurationCommand.getDefaultInstance(); + } else { + modemConfigurationCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000040); + if (rtcConfigurationCommandBuilder_ == null) { + rtcConfigurationCommand_ = com.openxc.BinaryMessages.RTCConfigurationCommand.getDefaultInstance(); + } else { + rtcConfigurationCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000080); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.ControlCommand.getDescriptor(); + } + + public com.openxc.BinaryMessages.ControlCommand getDefaultInstanceForType() { + return com.openxc.BinaryMessages.ControlCommand.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.ControlCommand build() { + com.openxc.BinaryMessages.ControlCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.ControlCommand buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.ControlCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.ControlCommand buildPartial() { + com.openxc.BinaryMessages.ControlCommand result = new com.openxc.BinaryMessages.ControlCommand(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.type_ = type_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + if (diagnosticRequestBuilder_ == null) { + result.diagnosticRequest_ = diagnosticRequest_; + } else { + result.diagnosticRequest_ = diagnosticRequestBuilder_.build(); + } + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + if (passthroughModeRequestBuilder_ == null) { + result.passthroughModeRequest_ = passthroughModeRequest_; + } else { + result.passthroughModeRequest_ = passthroughModeRequestBuilder_.build(); + } + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + if (acceptanceFilterBypassCommandBuilder_ == null) { + result.acceptanceFilterBypassCommand_ = acceptanceFilterBypassCommand_; + } else { + result.acceptanceFilterBypassCommand_ = acceptanceFilterBypassCommandBuilder_.build(); + } + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000010; + } + if (payloadFormatCommandBuilder_ == null) { + result.payloadFormatCommand_ = payloadFormatCommand_; + } else { + result.payloadFormatCommand_ = payloadFormatCommandBuilder_.build(); + } + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000020; + } + if (predefinedObd2RequestsCommandBuilder_ == null) { + result.predefinedObd2RequestsCommand_ = predefinedObd2RequestsCommand_; + } else { + result.predefinedObd2RequestsCommand_ = predefinedObd2RequestsCommandBuilder_.build(); + } + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000040; + } + if (modemConfigurationCommandBuilder_ == null) { + result.modemConfigurationCommand_ = modemConfigurationCommand_; + } else { + result.modemConfigurationCommand_ = modemConfigurationCommandBuilder_.build(); + } + if (((from_bitField0_ & 0x00000080) == 0x00000080)) { + to_bitField0_ |= 0x00000080; + } + if (rtcConfigurationCommandBuilder_ == null) { + result.rtcConfigurationCommand_ = rtcConfigurationCommand_; + } else { + result.rtcConfigurationCommand_ = rtcConfigurationCommandBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.ControlCommand) { + return mergeFrom((com.openxc.BinaryMessages.ControlCommand)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.ControlCommand other) { + if (other == com.openxc.BinaryMessages.ControlCommand.getDefaultInstance()) return this; + if (other.hasType()) { + setType(other.getType()); + } + if (other.hasDiagnosticRequest()) { + mergeDiagnosticRequest(other.getDiagnosticRequest()); + } + if (other.hasPassthroughModeRequest()) { + mergePassthroughModeRequest(other.getPassthroughModeRequest()); + } + if (other.hasAcceptanceFilterBypassCommand()) { + mergeAcceptanceFilterBypassCommand(other.getAcceptanceFilterBypassCommand()); + } + if (other.hasPayloadFormatCommand()) { + mergePayloadFormatCommand(other.getPayloadFormatCommand()); + } + if (other.hasPredefinedObd2RequestsCommand()) { + mergePredefinedObd2RequestsCommand(other.getPredefinedObd2RequestsCommand()); + } + if (other.hasModemConfigurationCommand()) { + mergeModemConfigurationCommand(other.getModemConfigurationCommand()); + } + if (other.hasRtcConfigurationCommand()) { + mergeRtcConfigurationCommand(other.getRtcConfigurationCommand()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + int rawValue = input.readEnum(); + com.openxc.BinaryMessages.ControlCommand.Type value = com.openxc.BinaryMessages.ControlCommand.Type.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(1, rawValue); + } else { + bitField0_ |= 0x00000001; + type_ = value; + } + break; + } + case 18: { + com.openxc.BinaryMessages.DiagnosticControlCommand.Builder subBuilder = com.openxc.BinaryMessages.DiagnosticControlCommand.newBuilder(); + if (hasDiagnosticRequest()) { + subBuilder.mergeFrom(getDiagnosticRequest()); + } + input.readMessage(subBuilder, extensionRegistry); + setDiagnosticRequest(subBuilder.buildPartial()); + break; + } + case 26: { + com.openxc.BinaryMessages.PassthroughModeControlCommand.Builder subBuilder = com.openxc.BinaryMessages.PassthroughModeControlCommand.newBuilder(); + if (hasPassthroughModeRequest()) { + subBuilder.mergeFrom(getPassthroughModeRequest()); + } + input.readMessage(subBuilder, extensionRegistry); + setPassthroughModeRequest(subBuilder.buildPartial()); + break; + } + case 34: { + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.Builder subBuilder = com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.newBuilder(); + if (hasAcceptanceFilterBypassCommand()) { + subBuilder.mergeFrom(getAcceptanceFilterBypassCommand()); + } + input.readMessage(subBuilder, extensionRegistry); + setAcceptanceFilterBypassCommand(subBuilder.buildPartial()); + break; + } + case 42: { + com.openxc.BinaryMessages.PayloadFormatCommand.Builder subBuilder = com.openxc.BinaryMessages.PayloadFormatCommand.newBuilder(); + if (hasPayloadFormatCommand()) { + subBuilder.mergeFrom(getPayloadFormatCommand()); + } + input.readMessage(subBuilder, extensionRegistry); + setPayloadFormatCommand(subBuilder.buildPartial()); + break; + } + case 50: { + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.Builder subBuilder = com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.newBuilder(); + if (hasPredefinedObd2RequestsCommand()) { + subBuilder.mergeFrom(getPredefinedObd2RequestsCommand()); + } + input.readMessage(subBuilder, extensionRegistry); + setPredefinedObd2RequestsCommand(subBuilder.buildPartial()); + break; + } + case 58: { + com.openxc.BinaryMessages.ModemConfigurationCommand.Builder subBuilder = com.openxc.BinaryMessages.ModemConfigurationCommand.newBuilder(); + if (hasModemConfigurationCommand()) { + subBuilder.mergeFrom(getModemConfigurationCommand()); + } + input.readMessage(subBuilder, extensionRegistry); + setModemConfigurationCommand(subBuilder.buildPartial()); + break; + } + case 66: { + com.openxc.BinaryMessages.RTCConfigurationCommand.Builder subBuilder = com.openxc.BinaryMessages.RTCConfigurationCommand.newBuilder(); + if (hasRtcConfigurationCommand()) { + subBuilder.mergeFrom(getRtcConfigurationCommand()); + } + input.readMessage(subBuilder, extensionRegistry); + setRtcConfigurationCommand(subBuilder.buildPartial()); + break; + } + } + } + } + + private int bitField0_; + + // optional .openxc.ControlCommand.Type type = 1; + private com.openxc.BinaryMessages.ControlCommand.Type type_ = com.openxc.BinaryMessages.ControlCommand.Type.VERSION; + public boolean hasType() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.ControlCommand.Type getType() { + return type_; + } + public Builder setType(com.openxc.BinaryMessages.ControlCommand.Type value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + type_ = value; + onChanged(); + return this; + } + public Builder clearType() { + bitField0_ = (bitField0_ & ~0x00000001); + type_ = com.openxc.BinaryMessages.ControlCommand.Type.VERSION; + onChanged(); + return this; + } + + // optional .openxc.DiagnosticControlCommand diagnostic_request = 2; + private com.openxc.BinaryMessages.DiagnosticControlCommand diagnosticRequest_ = com.openxc.BinaryMessages.DiagnosticControlCommand.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DiagnosticControlCommand, com.openxc.BinaryMessages.DiagnosticControlCommand.Builder, com.openxc.BinaryMessages.DiagnosticControlCommandOrBuilder> diagnosticRequestBuilder_; + public boolean hasDiagnosticRequest() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.DiagnosticControlCommand getDiagnosticRequest() { + if (diagnosticRequestBuilder_ == null) { + return diagnosticRequest_; + } else { + return diagnosticRequestBuilder_.getMessage(); + } + } + public Builder setDiagnosticRequest(com.openxc.BinaryMessages.DiagnosticControlCommand value) { + if (diagnosticRequestBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + diagnosticRequest_ = value; + onChanged(); + } else { + diagnosticRequestBuilder_.setMessage(value); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder setDiagnosticRequest( + com.openxc.BinaryMessages.DiagnosticControlCommand.Builder builderForValue) { + if (diagnosticRequestBuilder_ == null) { + diagnosticRequest_ = builderForValue.build(); + onChanged(); + } else { + diagnosticRequestBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder mergeDiagnosticRequest(com.openxc.BinaryMessages.DiagnosticControlCommand value) { + if (diagnosticRequestBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002) && + diagnosticRequest_ != com.openxc.BinaryMessages.DiagnosticControlCommand.getDefaultInstance()) { + diagnosticRequest_ = + com.openxc.BinaryMessages.DiagnosticControlCommand.newBuilder(diagnosticRequest_).mergeFrom(value).buildPartial(); + } else { + diagnosticRequest_ = value; + } + onChanged(); + } else { + diagnosticRequestBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder clearDiagnosticRequest() { + if (diagnosticRequestBuilder_ == null) { + diagnosticRequest_ = com.openxc.BinaryMessages.DiagnosticControlCommand.getDefaultInstance(); + onChanged(); + } else { + diagnosticRequestBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + public com.openxc.BinaryMessages.DiagnosticControlCommand.Builder getDiagnosticRequestBuilder() { + bitField0_ |= 0x00000002; + onChanged(); + return getDiagnosticRequestFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.DiagnosticControlCommandOrBuilder getDiagnosticRequestOrBuilder() { + if (diagnosticRequestBuilder_ != null) { + return diagnosticRequestBuilder_.getMessageOrBuilder(); + } else { + return diagnosticRequest_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DiagnosticControlCommand, com.openxc.BinaryMessages.DiagnosticControlCommand.Builder, com.openxc.BinaryMessages.DiagnosticControlCommandOrBuilder> + getDiagnosticRequestFieldBuilder() { + if (diagnosticRequestBuilder_ == null) { + diagnosticRequestBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DiagnosticControlCommand, com.openxc.BinaryMessages.DiagnosticControlCommand.Builder, com.openxc.BinaryMessages.DiagnosticControlCommandOrBuilder>( + diagnosticRequest_, + getParentForChildren(), + isClean()); + diagnosticRequest_ = null; + } + return diagnosticRequestBuilder_; + } + + // optional .openxc.PassthroughModeControlCommand passthrough_mode_request = 3; + private com.openxc.BinaryMessages.PassthroughModeControlCommand passthroughModeRequest_ = com.openxc.BinaryMessages.PassthroughModeControlCommand.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.PassthroughModeControlCommand, com.openxc.BinaryMessages.PassthroughModeControlCommand.Builder, com.openxc.BinaryMessages.PassthroughModeControlCommandOrBuilder> passthroughModeRequestBuilder_; + public boolean hasPassthroughModeRequest() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.openxc.BinaryMessages.PassthroughModeControlCommand getPassthroughModeRequest() { + if (passthroughModeRequestBuilder_ == null) { + return passthroughModeRequest_; + } else { + return passthroughModeRequestBuilder_.getMessage(); + } + } + public Builder setPassthroughModeRequest(com.openxc.BinaryMessages.PassthroughModeControlCommand value) { + if (passthroughModeRequestBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + passthroughModeRequest_ = value; + onChanged(); + } else { + passthroughModeRequestBuilder_.setMessage(value); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder setPassthroughModeRequest( + com.openxc.BinaryMessages.PassthroughModeControlCommand.Builder builderForValue) { + if (passthroughModeRequestBuilder_ == null) { + passthroughModeRequest_ = builderForValue.build(); + onChanged(); + } else { + passthroughModeRequestBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder mergePassthroughModeRequest(com.openxc.BinaryMessages.PassthroughModeControlCommand value) { + if (passthroughModeRequestBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + passthroughModeRequest_ != com.openxc.BinaryMessages.PassthroughModeControlCommand.getDefaultInstance()) { + passthroughModeRequest_ = + com.openxc.BinaryMessages.PassthroughModeControlCommand.newBuilder(passthroughModeRequest_).mergeFrom(value).buildPartial(); + } else { + passthroughModeRequest_ = value; + } + onChanged(); + } else { + passthroughModeRequestBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder clearPassthroughModeRequest() { + if (passthroughModeRequestBuilder_ == null) { + passthroughModeRequest_ = com.openxc.BinaryMessages.PassthroughModeControlCommand.getDefaultInstance(); + onChanged(); + } else { + passthroughModeRequestBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + public com.openxc.BinaryMessages.PassthroughModeControlCommand.Builder getPassthroughModeRequestBuilder() { + bitField0_ |= 0x00000004; + onChanged(); + return getPassthroughModeRequestFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.PassthroughModeControlCommandOrBuilder getPassthroughModeRequestOrBuilder() { + if (passthroughModeRequestBuilder_ != null) { + return passthroughModeRequestBuilder_.getMessageOrBuilder(); + } else { + return passthroughModeRequest_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.PassthroughModeControlCommand, com.openxc.BinaryMessages.PassthroughModeControlCommand.Builder, com.openxc.BinaryMessages.PassthroughModeControlCommandOrBuilder> + getPassthroughModeRequestFieldBuilder() { + if (passthroughModeRequestBuilder_ == null) { + passthroughModeRequestBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.PassthroughModeControlCommand, com.openxc.BinaryMessages.PassthroughModeControlCommand.Builder, com.openxc.BinaryMessages.PassthroughModeControlCommandOrBuilder>( + passthroughModeRequest_, + getParentForChildren(), + isClean()); + passthroughModeRequest_ = null; + } + return passthroughModeRequestBuilder_; + } + + // optional .openxc.AcceptanceFilterBypassCommand acceptance_filter_bypass_command = 4; + private com.openxc.BinaryMessages.AcceptanceFilterBypassCommand acceptanceFilterBypassCommand_ = com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand, com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.Builder, com.openxc.BinaryMessages.AcceptanceFilterBypassCommandOrBuilder> acceptanceFilterBypassCommandBuilder_; + public boolean hasAcceptanceFilterBypassCommand() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public com.openxc.BinaryMessages.AcceptanceFilterBypassCommand getAcceptanceFilterBypassCommand() { + if (acceptanceFilterBypassCommandBuilder_ == null) { + return acceptanceFilterBypassCommand_; + } else { + return acceptanceFilterBypassCommandBuilder_.getMessage(); + } + } + public Builder setAcceptanceFilterBypassCommand(com.openxc.BinaryMessages.AcceptanceFilterBypassCommand value) { + if (acceptanceFilterBypassCommandBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + acceptanceFilterBypassCommand_ = value; + onChanged(); + } else { + acceptanceFilterBypassCommandBuilder_.setMessage(value); + } + bitField0_ |= 0x00000008; + return this; + } + public Builder setAcceptanceFilterBypassCommand( + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.Builder builderForValue) { + if (acceptanceFilterBypassCommandBuilder_ == null) { + acceptanceFilterBypassCommand_ = builderForValue.build(); + onChanged(); + } else { + acceptanceFilterBypassCommandBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000008; + return this; + } + public Builder mergeAcceptanceFilterBypassCommand(com.openxc.BinaryMessages.AcceptanceFilterBypassCommand value) { + if (acceptanceFilterBypassCommandBuilder_ == null) { + if (((bitField0_ & 0x00000008) == 0x00000008) && + acceptanceFilterBypassCommand_ != com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.getDefaultInstance()) { + acceptanceFilterBypassCommand_ = + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.newBuilder(acceptanceFilterBypassCommand_).mergeFrom(value).buildPartial(); + } else { + acceptanceFilterBypassCommand_ = value; + } + onChanged(); + } else { + acceptanceFilterBypassCommandBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000008; + return this; + } + public Builder clearAcceptanceFilterBypassCommand() { + if (acceptanceFilterBypassCommandBuilder_ == null) { + acceptanceFilterBypassCommand_ = com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.getDefaultInstance(); + onChanged(); + } else { + acceptanceFilterBypassCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000008); + return this; + } + public com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.Builder getAcceptanceFilterBypassCommandBuilder() { + bitField0_ |= 0x00000008; + onChanged(); + return getAcceptanceFilterBypassCommandFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.AcceptanceFilterBypassCommandOrBuilder getAcceptanceFilterBypassCommandOrBuilder() { + if (acceptanceFilterBypassCommandBuilder_ != null) { + return acceptanceFilterBypassCommandBuilder_.getMessageOrBuilder(); + } else { + return acceptanceFilterBypassCommand_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand, com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.Builder, com.openxc.BinaryMessages.AcceptanceFilterBypassCommandOrBuilder> + getAcceptanceFilterBypassCommandFieldBuilder() { + if (acceptanceFilterBypassCommandBuilder_ == null) { + acceptanceFilterBypassCommandBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand, com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.Builder, com.openxc.BinaryMessages.AcceptanceFilterBypassCommandOrBuilder>( + acceptanceFilterBypassCommand_, + getParentForChildren(), + isClean()); + acceptanceFilterBypassCommand_ = null; + } + return acceptanceFilterBypassCommandBuilder_; + } + + // optional .openxc.PayloadFormatCommand payload_format_command = 5; + private com.openxc.BinaryMessages.PayloadFormatCommand payloadFormatCommand_ = com.openxc.BinaryMessages.PayloadFormatCommand.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.PayloadFormatCommand, com.openxc.BinaryMessages.PayloadFormatCommand.Builder, com.openxc.BinaryMessages.PayloadFormatCommandOrBuilder> payloadFormatCommandBuilder_; + public boolean hasPayloadFormatCommand() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + public com.openxc.BinaryMessages.PayloadFormatCommand getPayloadFormatCommand() { + if (payloadFormatCommandBuilder_ == null) { + return payloadFormatCommand_; + } else { + return payloadFormatCommandBuilder_.getMessage(); + } + } + public Builder setPayloadFormatCommand(com.openxc.BinaryMessages.PayloadFormatCommand value) { + if (payloadFormatCommandBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + payloadFormatCommand_ = value; + onChanged(); + } else { + payloadFormatCommandBuilder_.setMessage(value); + } + bitField0_ |= 0x00000010; + return this; + } + public Builder setPayloadFormatCommand( + com.openxc.BinaryMessages.PayloadFormatCommand.Builder builderForValue) { + if (payloadFormatCommandBuilder_ == null) { + payloadFormatCommand_ = builderForValue.build(); + onChanged(); + } else { + payloadFormatCommandBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000010; + return this; + } + public Builder mergePayloadFormatCommand(com.openxc.BinaryMessages.PayloadFormatCommand value) { + if (payloadFormatCommandBuilder_ == null) { + if (((bitField0_ & 0x00000010) == 0x00000010) && + payloadFormatCommand_ != com.openxc.BinaryMessages.PayloadFormatCommand.getDefaultInstance()) { + payloadFormatCommand_ = + com.openxc.BinaryMessages.PayloadFormatCommand.newBuilder(payloadFormatCommand_).mergeFrom(value).buildPartial(); + } else { + payloadFormatCommand_ = value; + } + onChanged(); + } else { + payloadFormatCommandBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000010; + return this; + } + public Builder clearPayloadFormatCommand() { + if (payloadFormatCommandBuilder_ == null) { + payloadFormatCommand_ = com.openxc.BinaryMessages.PayloadFormatCommand.getDefaultInstance(); + onChanged(); + } else { + payloadFormatCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000010); + return this; + } + public com.openxc.BinaryMessages.PayloadFormatCommand.Builder getPayloadFormatCommandBuilder() { + bitField0_ |= 0x00000010; + onChanged(); + return getPayloadFormatCommandFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.PayloadFormatCommandOrBuilder getPayloadFormatCommandOrBuilder() { + if (payloadFormatCommandBuilder_ != null) { + return payloadFormatCommandBuilder_.getMessageOrBuilder(); + } else { + return payloadFormatCommand_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.PayloadFormatCommand, com.openxc.BinaryMessages.PayloadFormatCommand.Builder, com.openxc.BinaryMessages.PayloadFormatCommandOrBuilder> + getPayloadFormatCommandFieldBuilder() { + if (payloadFormatCommandBuilder_ == null) { + payloadFormatCommandBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.PayloadFormatCommand, com.openxc.BinaryMessages.PayloadFormatCommand.Builder, com.openxc.BinaryMessages.PayloadFormatCommandOrBuilder>( + payloadFormatCommand_, + getParentForChildren(), + isClean()); + payloadFormatCommand_ = null; + } + return payloadFormatCommandBuilder_; + } + + // optional .openxc.PredefinedObd2RequestsCommand predefined_obd2_requests_command = 6; + private com.openxc.BinaryMessages.PredefinedObd2RequestsCommand predefinedObd2RequestsCommand_ = com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand, com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.Builder, com.openxc.BinaryMessages.PredefinedObd2RequestsCommandOrBuilder> predefinedObd2RequestsCommandBuilder_; + public boolean hasPredefinedObd2RequestsCommand() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + public com.openxc.BinaryMessages.PredefinedObd2RequestsCommand getPredefinedObd2RequestsCommand() { + if (predefinedObd2RequestsCommandBuilder_ == null) { + return predefinedObd2RequestsCommand_; + } else { + return predefinedObd2RequestsCommandBuilder_.getMessage(); + } + } + public Builder setPredefinedObd2RequestsCommand(com.openxc.BinaryMessages.PredefinedObd2RequestsCommand value) { + if (predefinedObd2RequestsCommandBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + predefinedObd2RequestsCommand_ = value; + onChanged(); + } else { + predefinedObd2RequestsCommandBuilder_.setMessage(value); + } + bitField0_ |= 0x00000020; + return this; + } + public Builder setPredefinedObd2RequestsCommand( + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.Builder builderForValue) { + if (predefinedObd2RequestsCommandBuilder_ == null) { + predefinedObd2RequestsCommand_ = builderForValue.build(); + onChanged(); + } else { + predefinedObd2RequestsCommandBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000020; + return this; + } + public Builder mergePredefinedObd2RequestsCommand(com.openxc.BinaryMessages.PredefinedObd2RequestsCommand value) { + if (predefinedObd2RequestsCommandBuilder_ == null) { + if (((bitField0_ & 0x00000020) == 0x00000020) && + predefinedObd2RequestsCommand_ != com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.getDefaultInstance()) { + predefinedObd2RequestsCommand_ = + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.newBuilder(predefinedObd2RequestsCommand_).mergeFrom(value).buildPartial(); + } else { + predefinedObd2RequestsCommand_ = value; + } + onChanged(); + } else { + predefinedObd2RequestsCommandBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000020; + return this; + } + public Builder clearPredefinedObd2RequestsCommand() { + if (predefinedObd2RequestsCommandBuilder_ == null) { + predefinedObd2RequestsCommand_ = com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.getDefaultInstance(); + onChanged(); + } else { + predefinedObd2RequestsCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000020); + return this; + } + public com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.Builder getPredefinedObd2RequestsCommandBuilder() { + bitField0_ |= 0x00000020; + onChanged(); + return getPredefinedObd2RequestsCommandFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.PredefinedObd2RequestsCommandOrBuilder getPredefinedObd2RequestsCommandOrBuilder() { + if (predefinedObd2RequestsCommandBuilder_ != null) { + return predefinedObd2RequestsCommandBuilder_.getMessageOrBuilder(); + } else { + return predefinedObd2RequestsCommand_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand, com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.Builder, com.openxc.BinaryMessages.PredefinedObd2RequestsCommandOrBuilder> + getPredefinedObd2RequestsCommandFieldBuilder() { + if (predefinedObd2RequestsCommandBuilder_ == null) { + predefinedObd2RequestsCommandBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand, com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.Builder, com.openxc.BinaryMessages.PredefinedObd2RequestsCommandOrBuilder>( + predefinedObd2RequestsCommand_, + getParentForChildren(), + isClean()); + predefinedObd2RequestsCommand_ = null; + } + return predefinedObd2RequestsCommandBuilder_; + } + + // optional .openxc.ModemConfigurationCommand modem_configuration_command = 7; + private com.openxc.BinaryMessages.ModemConfigurationCommand modemConfigurationCommand_ = com.openxc.BinaryMessages.ModemConfigurationCommand.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.ModemConfigurationCommand, com.openxc.BinaryMessages.ModemConfigurationCommand.Builder, com.openxc.BinaryMessages.ModemConfigurationCommandOrBuilder> modemConfigurationCommandBuilder_; + public boolean hasModemConfigurationCommand() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + public com.openxc.BinaryMessages.ModemConfigurationCommand getModemConfigurationCommand() { + if (modemConfigurationCommandBuilder_ == null) { + return modemConfigurationCommand_; + } else { + return modemConfigurationCommandBuilder_.getMessage(); + } + } + public Builder setModemConfigurationCommand(com.openxc.BinaryMessages.ModemConfigurationCommand value) { + if (modemConfigurationCommandBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + modemConfigurationCommand_ = value; + onChanged(); + } else { + modemConfigurationCommandBuilder_.setMessage(value); + } + bitField0_ |= 0x00000040; + return this; + } + public Builder setModemConfigurationCommand( + com.openxc.BinaryMessages.ModemConfigurationCommand.Builder builderForValue) { + if (modemConfigurationCommandBuilder_ == null) { + modemConfigurationCommand_ = builderForValue.build(); + onChanged(); + } else { + modemConfigurationCommandBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000040; + return this; + } + public Builder mergeModemConfigurationCommand(com.openxc.BinaryMessages.ModemConfigurationCommand value) { + if (modemConfigurationCommandBuilder_ == null) { + if (((bitField0_ & 0x00000040) == 0x00000040) && + modemConfigurationCommand_ != com.openxc.BinaryMessages.ModemConfigurationCommand.getDefaultInstance()) { + modemConfigurationCommand_ = + com.openxc.BinaryMessages.ModemConfigurationCommand.newBuilder(modemConfigurationCommand_).mergeFrom(value).buildPartial(); + } else { + modemConfigurationCommand_ = value; + } + onChanged(); + } else { + modemConfigurationCommandBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000040; + return this; + } + public Builder clearModemConfigurationCommand() { + if (modemConfigurationCommandBuilder_ == null) { + modemConfigurationCommand_ = com.openxc.BinaryMessages.ModemConfigurationCommand.getDefaultInstance(); + onChanged(); + } else { + modemConfigurationCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000040); + return this; + } + public com.openxc.BinaryMessages.ModemConfigurationCommand.Builder getModemConfigurationCommandBuilder() { + bitField0_ |= 0x00000040; + onChanged(); + return getModemConfigurationCommandFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.ModemConfigurationCommandOrBuilder getModemConfigurationCommandOrBuilder() { + if (modemConfigurationCommandBuilder_ != null) { + return modemConfigurationCommandBuilder_.getMessageOrBuilder(); + } else { + return modemConfigurationCommand_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.ModemConfigurationCommand, com.openxc.BinaryMessages.ModemConfigurationCommand.Builder, com.openxc.BinaryMessages.ModemConfigurationCommandOrBuilder> + getModemConfigurationCommandFieldBuilder() { + if (modemConfigurationCommandBuilder_ == null) { + modemConfigurationCommandBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.ModemConfigurationCommand, com.openxc.BinaryMessages.ModemConfigurationCommand.Builder, com.openxc.BinaryMessages.ModemConfigurationCommandOrBuilder>( + modemConfigurationCommand_, + getParentForChildren(), + isClean()); + modemConfigurationCommand_ = null; + } + return modemConfigurationCommandBuilder_; + } + + // optional .openxc.RTCConfigurationCommand rtc_configuration_command = 8; + private com.openxc.BinaryMessages.RTCConfigurationCommand rtcConfigurationCommand_ = com.openxc.BinaryMessages.RTCConfigurationCommand.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.RTCConfigurationCommand, com.openxc.BinaryMessages.RTCConfigurationCommand.Builder, com.openxc.BinaryMessages.RTCConfigurationCommandOrBuilder> rtcConfigurationCommandBuilder_; + public boolean hasRtcConfigurationCommand() { + return ((bitField0_ & 0x00000080) == 0x00000080); + } + public com.openxc.BinaryMessages.RTCConfigurationCommand getRtcConfigurationCommand() { + if (rtcConfigurationCommandBuilder_ == null) { + return rtcConfigurationCommand_; + } else { + return rtcConfigurationCommandBuilder_.getMessage(); + } + } + public Builder setRtcConfigurationCommand(com.openxc.BinaryMessages.RTCConfigurationCommand value) { + if (rtcConfigurationCommandBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + rtcConfigurationCommand_ = value; + onChanged(); + } else { + rtcConfigurationCommandBuilder_.setMessage(value); + } + bitField0_ |= 0x00000080; + return this; + } + public Builder setRtcConfigurationCommand( + com.openxc.BinaryMessages.RTCConfigurationCommand.Builder builderForValue) { + if (rtcConfigurationCommandBuilder_ == null) { + rtcConfigurationCommand_ = builderForValue.build(); + onChanged(); + } else { + rtcConfigurationCommandBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000080; + return this; + } + public Builder mergeRtcConfigurationCommand(com.openxc.BinaryMessages.RTCConfigurationCommand value) { + if (rtcConfigurationCommandBuilder_ == null) { + if (((bitField0_ & 0x00000080) == 0x00000080) && + rtcConfigurationCommand_ != com.openxc.BinaryMessages.RTCConfigurationCommand.getDefaultInstance()) { + rtcConfigurationCommand_ = + com.openxc.BinaryMessages.RTCConfigurationCommand.newBuilder(rtcConfigurationCommand_).mergeFrom(value).buildPartial(); + } else { + rtcConfigurationCommand_ = value; + } + onChanged(); + } else { + rtcConfigurationCommandBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000080; + return this; + } + public Builder clearRtcConfigurationCommand() { + if (rtcConfigurationCommandBuilder_ == null) { + rtcConfigurationCommand_ = com.openxc.BinaryMessages.RTCConfigurationCommand.getDefaultInstance(); + onChanged(); + } else { + rtcConfigurationCommandBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000080); + return this; + } + public com.openxc.BinaryMessages.RTCConfigurationCommand.Builder getRtcConfigurationCommandBuilder() { + bitField0_ |= 0x00000080; + onChanged(); + return getRtcConfigurationCommandFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.RTCConfigurationCommandOrBuilder getRtcConfigurationCommandOrBuilder() { + if (rtcConfigurationCommandBuilder_ != null) { + return rtcConfigurationCommandBuilder_.getMessageOrBuilder(); + } else { + return rtcConfigurationCommand_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.RTCConfigurationCommand, com.openxc.BinaryMessages.RTCConfigurationCommand.Builder, com.openxc.BinaryMessages.RTCConfigurationCommandOrBuilder> + getRtcConfigurationCommandFieldBuilder() { + if (rtcConfigurationCommandBuilder_ == null) { + rtcConfigurationCommandBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.RTCConfigurationCommand, com.openxc.BinaryMessages.RTCConfigurationCommand.Builder, com.openxc.BinaryMessages.RTCConfigurationCommandOrBuilder>( + rtcConfigurationCommand_, + getParentForChildren(), + isClean()); + rtcConfigurationCommand_ = null; + } + return rtcConfigurationCommandBuilder_; + } + + // @@protoc_insertion_point(builder_scope:openxc.ControlCommand) + } + + static { + defaultInstance = new ControlCommand(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.ControlCommand) + } + + public interface DiagnosticControlCommandOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional .openxc.DiagnosticRequest request = 1; + boolean hasRequest(); + com.openxc.BinaryMessages.DiagnosticRequest getRequest(); + com.openxc.BinaryMessages.DiagnosticRequestOrBuilder getRequestOrBuilder(); + + // optional .openxc.DiagnosticControlCommand.Action action = 2; + boolean hasAction(); + com.openxc.BinaryMessages.DiagnosticControlCommand.Action getAction(); + } + public static final class DiagnosticControlCommand extends + com.google.protobuf.GeneratedMessage + implements DiagnosticControlCommandOrBuilder { + // Use DiagnosticControlCommand.newBuilder() to construct. + private DiagnosticControlCommand(Builder builder) { + super(builder); + } + private DiagnosticControlCommand(boolean noInit) {} + + private static final DiagnosticControlCommand defaultInstance; + public static DiagnosticControlCommand getDefaultInstance() { + return defaultInstance; + } + + public DiagnosticControlCommand getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticControlCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticControlCommand_fieldAccessorTable; + } + + public enum Action + implements com.google.protobuf.ProtocolMessageEnum { + ADD(0, 1), + CANCEL(1, 2), + ; + + public static final int ADD_VALUE = 1; + public static final int CANCEL_VALUE = 2; + + + public final int getNumber() { return value; } + + public static Action valueOf(int value) { + switch (value) { + case 1: return ADD; + case 2: return CANCEL; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public Action findValueByNumber(int number) { + return Action.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return com.openxc.BinaryMessages.DiagnosticControlCommand.getDescriptor().getEnumTypes().get(0); + } + + private static final Action[] VALUES = { + ADD, CANCEL, + }; + + public static Action valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private Action(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:openxc.DiagnosticControlCommand.Action) + } + + private int bitField0_; + // optional .openxc.DiagnosticRequest request = 1; + public static final int REQUEST_FIELD_NUMBER = 1; + private com.openxc.BinaryMessages.DiagnosticRequest request_; + public boolean hasRequest() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.DiagnosticRequest getRequest() { + return request_; + } + public com.openxc.BinaryMessages.DiagnosticRequestOrBuilder getRequestOrBuilder() { + return request_; + } + + // optional .openxc.DiagnosticControlCommand.Action action = 2; + public static final int ACTION_FIELD_NUMBER = 2; + private com.openxc.BinaryMessages.DiagnosticControlCommand.Action action_; + public boolean hasAction() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.DiagnosticControlCommand.Action getAction() { + return action_; + } + + private void initFields() { + request_ = com.openxc.BinaryMessages.DiagnosticRequest.getDefaultInstance(); + action_ = com.openxc.BinaryMessages.DiagnosticControlCommand.Action.ADD; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeMessage(1, request_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeEnum(2, action_.getNumber()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(1, request_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(2, action_.getNumber()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.DiagnosticControlCommand parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticControlCommand parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticControlCommand parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticControlCommand parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticControlCommand parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticControlCommand parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticControlCommand parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.DiagnosticControlCommand parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.DiagnosticControlCommand parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticControlCommand parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.DiagnosticControlCommand prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.DiagnosticControlCommandOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticControlCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticControlCommand_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.DiagnosticControlCommand.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getRequestFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + if (requestBuilder_ == null) { + request_ = com.openxc.BinaryMessages.DiagnosticRequest.getDefaultInstance(); + } else { + requestBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); + action_ = com.openxc.BinaryMessages.DiagnosticControlCommand.Action.ADD; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.DiagnosticControlCommand.getDescriptor(); + } + + public com.openxc.BinaryMessages.DiagnosticControlCommand getDefaultInstanceForType() { + return com.openxc.BinaryMessages.DiagnosticControlCommand.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.DiagnosticControlCommand build() { + com.openxc.BinaryMessages.DiagnosticControlCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.DiagnosticControlCommand buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.DiagnosticControlCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.DiagnosticControlCommand buildPartial() { + com.openxc.BinaryMessages.DiagnosticControlCommand result = new com.openxc.BinaryMessages.DiagnosticControlCommand(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + if (requestBuilder_ == null) { + result.request_ = request_; + } else { + result.request_ = requestBuilder_.build(); + } + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.action_ = action_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.DiagnosticControlCommand) { + return mergeFrom((com.openxc.BinaryMessages.DiagnosticControlCommand)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.DiagnosticControlCommand other) { + if (other == com.openxc.BinaryMessages.DiagnosticControlCommand.getDefaultInstance()) return this; + if (other.hasRequest()) { + mergeRequest(other.getRequest()); + } + if (other.hasAction()) { + setAction(other.getAction()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 10: { + com.openxc.BinaryMessages.DiagnosticRequest.Builder subBuilder = com.openxc.BinaryMessages.DiagnosticRequest.newBuilder(); + if (hasRequest()) { + subBuilder.mergeFrom(getRequest()); + } + input.readMessage(subBuilder, extensionRegistry); + setRequest(subBuilder.buildPartial()); + break; + } + case 16: { + int rawValue = input.readEnum(); + com.openxc.BinaryMessages.DiagnosticControlCommand.Action value = com.openxc.BinaryMessages.DiagnosticControlCommand.Action.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(2, rawValue); + } else { + bitField0_ |= 0x00000002; + action_ = value; + } + break; + } + } + } + } + + private int bitField0_; + + // optional .openxc.DiagnosticRequest request = 1; + private com.openxc.BinaryMessages.DiagnosticRequest request_ = com.openxc.BinaryMessages.DiagnosticRequest.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DiagnosticRequest, com.openxc.BinaryMessages.DiagnosticRequest.Builder, com.openxc.BinaryMessages.DiagnosticRequestOrBuilder> requestBuilder_; + public boolean hasRequest() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.DiagnosticRequest getRequest() { + if (requestBuilder_ == null) { + return request_; + } else { + return requestBuilder_.getMessage(); + } + } + public Builder setRequest(com.openxc.BinaryMessages.DiagnosticRequest value) { + if (requestBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + request_ = value; + onChanged(); + } else { + requestBuilder_.setMessage(value); + } + bitField0_ |= 0x00000001; + return this; + } + public Builder setRequest( + com.openxc.BinaryMessages.DiagnosticRequest.Builder builderForValue) { + if (requestBuilder_ == null) { + request_ = builderForValue.build(); + onChanged(); + } else { + requestBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000001; + return this; + } + public Builder mergeRequest(com.openxc.BinaryMessages.DiagnosticRequest value) { + if (requestBuilder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001) && + request_ != com.openxc.BinaryMessages.DiagnosticRequest.getDefaultInstance()) { + request_ = + com.openxc.BinaryMessages.DiagnosticRequest.newBuilder(request_).mergeFrom(value).buildPartial(); + } else { + request_ = value; + } + onChanged(); + } else { + requestBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000001; + return this; + } + public Builder clearRequest() { + if (requestBuilder_ == null) { + request_ = com.openxc.BinaryMessages.DiagnosticRequest.getDefaultInstance(); + onChanged(); + } else { + requestBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); + return this; + } + public com.openxc.BinaryMessages.DiagnosticRequest.Builder getRequestBuilder() { + bitField0_ |= 0x00000001; + onChanged(); + return getRequestFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.DiagnosticRequestOrBuilder getRequestOrBuilder() { + if (requestBuilder_ != null) { + return requestBuilder_.getMessageOrBuilder(); + } else { + return request_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DiagnosticRequest, com.openxc.BinaryMessages.DiagnosticRequest.Builder, com.openxc.BinaryMessages.DiagnosticRequestOrBuilder> + getRequestFieldBuilder() { + if (requestBuilder_ == null) { + requestBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DiagnosticRequest, com.openxc.BinaryMessages.DiagnosticRequest.Builder, com.openxc.BinaryMessages.DiagnosticRequestOrBuilder>( + request_, + getParentForChildren(), + isClean()); + request_ = null; + } + return requestBuilder_; + } + + // optional .openxc.DiagnosticControlCommand.Action action = 2; + private com.openxc.BinaryMessages.DiagnosticControlCommand.Action action_ = com.openxc.BinaryMessages.DiagnosticControlCommand.Action.ADD; + public boolean hasAction() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.DiagnosticControlCommand.Action getAction() { + return action_; + } + public Builder setAction(com.openxc.BinaryMessages.DiagnosticControlCommand.Action value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + action_ = value; + onChanged(); + return this; + } + public Builder clearAction() { + bitField0_ = (bitField0_ & ~0x00000002); + action_ = com.openxc.BinaryMessages.DiagnosticControlCommand.Action.ADD; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.DiagnosticControlCommand) + } + + static { + defaultInstance = new DiagnosticControlCommand(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.DiagnosticControlCommand) + } + + public interface PassthroughModeControlCommandOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional int32 bus = 1; + boolean hasBus(); + int getBus(); + + // optional bool enabled = 2; + boolean hasEnabled(); + boolean getEnabled(); + } + public static final class PassthroughModeControlCommand extends + com.google.protobuf.GeneratedMessage + implements PassthroughModeControlCommandOrBuilder { + // Use PassthroughModeControlCommand.newBuilder() to construct. + private PassthroughModeControlCommand(Builder builder) { + super(builder); + } + private PassthroughModeControlCommand(boolean noInit) {} + + private static final PassthroughModeControlCommand defaultInstance; + public static PassthroughModeControlCommand getDefaultInstance() { + return defaultInstance; + } + + public PassthroughModeControlCommand getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_PassthroughModeControlCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_PassthroughModeControlCommand_fieldAccessorTable; + } + + private int bitField0_; + // optional int32 bus = 1; + public static final int BUS_FIELD_NUMBER = 1; + private int bus_; + public boolean hasBus() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getBus() { + return bus_; + } + + // optional bool enabled = 2; + public static final int ENABLED_FIELD_NUMBER = 2; + private boolean enabled_; + public boolean hasEnabled() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public boolean getEnabled() { + return enabled_; + } + + private void initFields() { + bus_ = 0; + enabled_ = false; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, bus_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBool(2, enabled_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, bus_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(2, enabled_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.PassthroughModeControlCommand parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.PassthroughModeControlCommand parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.PassthroughModeControlCommand parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.PassthroughModeControlCommand parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.PassthroughModeControlCommand parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.PassthroughModeControlCommand parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.PassthroughModeControlCommand parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.PassthroughModeControlCommand parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.PassthroughModeControlCommand parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.PassthroughModeControlCommand parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.PassthroughModeControlCommand prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.PassthroughModeControlCommandOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_PassthroughModeControlCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_PassthroughModeControlCommand_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.PassthroughModeControlCommand.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + bus_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + enabled_ = false; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.PassthroughModeControlCommand.getDescriptor(); + } + + public com.openxc.BinaryMessages.PassthroughModeControlCommand getDefaultInstanceForType() { + return com.openxc.BinaryMessages.PassthroughModeControlCommand.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.PassthroughModeControlCommand build() { + com.openxc.BinaryMessages.PassthroughModeControlCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.PassthroughModeControlCommand buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.PassthroughModeControlCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.PassthroughModeControlCommand buildPartial() { + com.openxc.BinaryMessages.PassthroughModeControlCommand result = new com.openxc.BinaryMessages.PassthroughModeControlCommand(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.bus_ = bus_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.enabled_ = enabled_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.PassthroughModeControlCommand) { + return mergeFrom((com.openxc.BinaryMessages.PassthroughModeControlCommand)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.PassthroughModeControlCommand other) { + if (other == com.openxc.BinaryMessages.PassthroughModeControlCommand.getDefaultInstance()) return this; + if (other.hasBus()) { + setBus(other.getBus()); + } + if (other.hasEnabled()) { + setEnabled(other.getEnabled()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + bus_ = input.readInt32(); + break; + } + case 16: { + bitField0_ |= 0x00000002; + enabled_ = input.readBool(); + break; + } + } + } + } + + private int bitField0_; + + // optional int32 bus = 1; + private int bus_ ; + public boolean hasBus() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getBus() { + return bus_; + } + public Builder setBus(int value) { + bitField0_ |= 0x00000001; + bus_ = value; + onChanged(); + return this; + } + public Builder clearBus() { + bitField0_ = (bitField0_ & ~0x00000001); + bus_ = 0; + onChanged(); + return this; + } + + // optional bool enabled = 2; + private boolean enabled_ ; + public boolean hasEnabled() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public boolean getEnabled() { + return enabled_; + } + public Builder setEnabled(boolean value) { + bitField0_ |= 0x00000002; + enabled_ = value; + onChanged(); + return this; + } + public Builder clearEnabled() { + bitField0_ = (bitField0_ & ~0x00000002); + enabled_ = false; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.PassthroughModeControlCommand) + } + + static { + defaultInstance = new PassthroughModeControlCommand(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.PassthroughModeControlCommand) + } + + public interface AcceptanceFilterBypassCommandOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional int32 bus = 1; + boolean hasBus(); + int getBus(); + + // optional bool bypass = 2; + boolean hasBypass(); + boolean getBypass(); + } + public static final class AcceptanceFilterBypassCommand extends + com.google.protobuf.GeneratedMessage + implements AcceptanceFilterBypassCommandOrBuilder { + // Use AcceptanceFilterBypassCommand.newBuilder() to construct. + private AcceptanceFilterBypassCommand(Builder builder) { + super(builder); + } + private AcceptanceFilterBypassCommand(boolean noInit) {} + + private static final AcceptanceFilterBypassCommand defaultInstance; + public static AcceptanceFilterBypassCommand getDefaultInstance() { + return defaultInstance; + } + + public AcceptanceFilterBypassCommand getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_AcceptanceFilterBypassCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_AcceptanceFilterBypassCommand_fieldAccessorTable; + } + + private int bitField0_; + // optional int32 bus = 1; + public static final int BUS_FIELD_NUMBER = 1; + private int bus_; + public boolean hasBus() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getBus() { + return bus_; + } + + // optional bool bypass = 2; + public static final int BYPASS_FIELD_NUMBER = 2; + private boolean bypass_; + public boolean hasBypass() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public boolean getBypass() { + return bypass_; + } + + private void initFields() { + bus_ = 0; + bypass_ = false; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, bus_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBool(2, bypass_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, bus_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(2, bypass_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.AcceptanceFilterBypassCommand parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.AcceptanceFilterBypassCommand parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.AcceptanceFilterBypassCommand parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.AcceptanceFilterBypassCommand parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.AcceptanceFilterBypassCommand parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.AcceptanceFilterBypassCommand parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.AcceptanceFilterBypassCommand parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.AcceptanceFilterBypassCommand parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.AcceptanceFilterBypassCommand parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.AcceptanceFilterBypassCommand parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.AcceptanceFilterBypassCommand prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.AcceptanceFilterBypassCommandOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_AcceptanceFilterBypassCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_AcceptanceFilterBypassCommand_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + bus_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + bypass_ = false; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.getDescriptor(); + } + + public com.openxc.BinaryMessages.AcceptanceFilterBypassCommand getDefaultInstanceForType() { + return com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.AcceptanceFilterBypassCommand build() { + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.AcceptanceFilterBypassCommand buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.AcceptanceFilterBypassCommand buildPartial() { + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand result = new com.openxc.BinaryMessages.AcceptanceFilterBypassCommand(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.bus_ = bus_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.bypass_ = bypass_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.AcceptanceFilterBypassCommand) { + return mergeFrom((com.openxc.BinaryMessages.AcceptanceFilterBypassCommand)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.AcceptanceFilterBypassCommand other) { + if (other == com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.getDefaultInstance()) return this; + if (other.hasBus()) { + setBus(other.getBus()); + } + if (other.hasBypass()) { + setBypass(other.getBypass()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + bus_ = input.readInt32(); + break; + } + case 16: { + bitField0_ |= 0x00000002; + bypass_ = input.readBool(); + break; + } + } + } + } + + private int bitField0_; + + // optional int32 bus = 1; + private int bus_ ; + public boolean hasBus() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getBus() { + return bus_; + } + public Builder setBus(int value) { + bitField0_ |= 0x00000001; + bus_ = value; + onChanged(); + return this; + } + public Builder clearBus() { + bitField0_ = (bitField0_ & ~0x00000001); + bus_ = 0; + onChanged(); + return this; + } + + // optional bool bypass = 2; + private boolean bypass_ ; + public boolean hasBypass() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public boolean getBypass() { + return bypass_; + } + public Builder setBypass(boolean value) { + bitField0_ |= 0x00000002; + bypass_ = value; + onChanged(); + return this; + } + public Builder clearBypass() { + bitField0_ = (bitField0_ & ~0x00000002); + bypass_ = false; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.AcceptanceFilterBypassCommand) + } + + static { + defaultInstance = new AcceptanceFilterBypassCommand(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.AcceptanceFilterBypassCommand) + } + + public interface PayloadFormatCommandOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional .openxc.PayloadFormatCommand.PayloadFormat format = 1; + boolean hasFormat(); + com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat getFormat(); + } + public static final class PayloadFormatCommand extends + com.google.protobuf.GeneratedMessage + implements PayloadFormatCommandOrBuilder { + // Use PayloadFormatCommand.newBuilder() to construct. + private PayloadFormatCommand(Builder builder) { + super(builder); + } + private PayloadFormatCommand(boolean noInit) {} + + private static final PayloadFormatCommand defaultInstance; + public static PayloadFormatCommand getDefaultInstance() { + return defaultInstance; + } + + public PayloadFormatCommand getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_PayloadFormatCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_PayloadFormatCommand_fieldAccessorTable; + } + + public enum PayloadFormat + implements com.google.protobuf.ProtocolMessageEnum { + JSON(0, 1), + PROTOBUF(1, 2), + MESSAGEPACK(2, 3), + ; + + public static final int JSON_VALUE = 1; + public static final int PROTOBUF_VALUE = 2; + public static final int MESSAGEPACK_VALUE = 3; + + + public final int getNumber() { return value; } + + public static PayloadFormat valueOf(int value) { + switch (value) { + case 1: return JSON; + case 2: return PROTOBUF; + case 3: return MESSAGEPACK; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public PayloadFormat findValueByNumber(int number) { + return PayloadFormat.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return com.openxc.BinaryMessages.PayloadFormatCommand.getDescriptor().getEnumTypes().get(0); + } + + private static final PayloadFormat[] VALUES = { + JSON, PROTOBUF, MESSAGEPACK, + }; + + public static PayloadFormat valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private PayloadFormat(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:openxc.PayloadFormatCommand.PayloadFormat) + } + + private int bitField0_; + // optional .openxc.PayloadFormatCommand.PayloadFormat format = 1; + public static final int FORMAT_FIELD_NUMBER = 1; + private com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat format_; + public boolean hasFormat() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat getFormat() { + return format_; + } + + private void initFields() { + format_ = com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat.JSON; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeEnum(1, format_.getNumber()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(1, format_.getNumber()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.PayloadFormatCommand parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.PayloadFormatCommand parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.PayloadFormatCommand parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.PayloadFormatCommand parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.PayloadFormatCommand parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.PayloadFormatCommand parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.PayloadFormatCommand parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.PayloadFormatCommand parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.PayloadFormatCommand parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.PayloadFormatCommand parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.PayloadFormatCommand prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.PayloadFormatCommandOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_PayloadFormatCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_PayloadFormatCommand_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.PayloadFormatCommand.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + format_ = com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat.JSON; + bitField0_ = (bitField0_ & ~0x00000001); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.PayloadFormatCommand.getDescriptor(); + } + + public com.openxc.BinaryMessages.PayloadFormatCommand getDefaultInstanceForType() { + return com.openxc.BinaryMessages.PayloadFormatCommand.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.PayloadFormatCommand build() { + com.openxc.BinaryMessages.PayloadFormatCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.PayloadFormatCommand buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.PayloadFormatCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.PayloadFormatCommand buildPartial() { + com.openxc.BinaryMessages.PayloadFormatCommand result = new com.openxc.BinaryMessages.PayloadFormatCommand(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.format_ = format_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.PayloadFormatCommand) { + return mergeFrom((com.openxc.BinaryMessages.PayloadFormatCommand)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.PayloadFormatCommand other) { + if (other == com.openxc.BinaryMessages.PayloadFormatCommand.getDefaultInstance()) return this; + if (other.hasFormat()) { + setFormat(other.getFormat()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + int rawValue = input.readEnum(); + com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat value = com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(1, rawValue); + } else { + bitField0_ |= 0x00000001; + format_ = value; + } + break; + } + } + } + } + + private int bitField0_; + + // optional .openxc.PayloadFormatCommand.PayloadFormat format = 1; + private com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat format_ = com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat.JSON; + public boolean hasFormat() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat getFormat() { + return format_; + } + public Builder setFormat(com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + format_ = value; + onChanged(); + return this; + } + public Builder clearFormat() { + bitField0_ = (bitField0_ & ~0x00000001); + format_ = com.openxc.BinaryMessages.PayloadFormatCommand.PayloadFormat.JSON; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.PayloadFormatCommand) + } + + static { + defaultInstance = new PayloadFormatCommand(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.PayloadFormatCommand) + } + + public interface PredefinedObd2RequestsCommandOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional bool enabled = 1; + boolean hasEnabled(); + boolean getEnabled(); + } + public static final class PredefinedObd2RequestsCommand extends + com.google.protobuf.GeneratedMessage + implements PredefinedObd2RequestsCommandOrBuilder { + // Use PredefinedObd2RequestsCommand.newBuilder() to construct. + private PredefinedObd2RequestsCommand(Builder builder) { + super(builder); + } + private PredefinedObd2RequestsCommand(boolean noInit) {} + + private static final PredefinedObd2RequestsCommand defaultInstance; + public static PredefinedObd2RequestsCommand getDefaultInstance() { + return defaultInstance; + } + + public PredefinedObd2RequestsCommand getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_PredefinedObd2RequestsCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_PredefinedObd2RequestsCommand_fieldAccessorTable; + } + + private int bitField0_; + // optional bool enabled = 1; + public static final int ENABLED_FIELD_NUMBER = 1; + private boolean enabled_; + public boolean hasEnabled() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public boolean getEnabled() { + return enabled_; + } + + private void initFields() { + enabled_ = false; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBool(1, enabled_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(1, enabled_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.PredefinedObd2RequestsCommand parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.PredefinedObd2RequestsCommand parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.PredefinedObd2RequestsCommand parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.PredefinedObd2RequestsCommand parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.PredefinedObd2RequestsCommand parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.PredefinedObd2RequestsCommand parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.PredefinedObd2RequestsCommand parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.PredefinedObd2RequestsCommand parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.PredefinedObd2RequestsCommand parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.PredefinedObd2RequestsCommand parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.PredefinedObd2RequestsCommand prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.PredefinedObd2RequestsCommandOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_PredefinedObd2RequestsCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_PredefinedObd2RequestsCommand_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + enabled_ = false; + bitField0_ = (bitField0_ & ~0x00000001); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.getDescriptor(); + } + + public com.openxc.BinaryMessages.PredefinedObd2RequestsCommand getDefaultInstanceForType() { + return com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.PredefinedObd2RequestsCommand build() { + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.PredefinedObd2RequestsCommand buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.PredefinedObd2RequestsCommand buildPartial() { + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand result = new com.openxc.BinaryMessages.PredefinedObd2RequestsCommand(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.enabled_ = enabled_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.PredefinedObd2RequestsCommand) { + return mergeFrom((com.openxc.BinaryMessages.PredefinedObd2RequestsCommand)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.PredefinedObd2RequestsCommand other) { + if (other == com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.getDefaultInstance()) return this; + if (other.hasEnabled()) { + setEnabled(other.getEnabled()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + enabled_ = input.readBool(); + break; + } + } + } + } + + private int bitField0_; + + // optional bool enabled = 1; + private boolean enabled_ ; + public boolean hasEnabled() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public boolean getEnabled() { + return enabled_; + } + public Builder setEnabled(boolean value) { + bitField0_ |= 0x00000001; + enabled_ = value; + onChanged(); + return this; + } + public Builder clearEnabled() { + bitField0_ = (bitField0_ & ~0x00000001); + enabled_ = false; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.PredefinedObd2RequestsCommand) + } + + static { + defaultInstance = new PredefinedObd2RequestsCommand(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.PredefinedObd2RequestsCommand) + } + + public interface NetworkOperatorSettingsOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional bool allowDataRoaming = 1; + boolean hasAllowDataRoaming(); + boolean getAllowDataRoaming(); + + // optional .openxc.NetworkOperatorSettings.OperatorSelectMode operatorSelectMode = 2; + boolean hasOperatorSelectMode(); + com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode getOperatorSelectMode(); + + // optional .openxc.NetworkOperatorSettings.NetworkDescriptor networkDescriptor = 3; + boolean hasNetworkDescriptor(); + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor getNetworkDescriptor(); + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptorOrBuilder getNetworkDescriptorOrBuilder(); + } + public static final class NetworkOperatorSettings extends + com.google.protobuf.GeneratedMessage + implements NetworkOperatorSettingsOrBuilder { + // Use NetworkOperatorSettings.newBuilder() to construct. + private NetworkOperatorSettings(Builder builder) { + super(builder); + } + private NetworkOperatorSettings(boolean noInit) {} + + private static final NetworkOperatorSettings defaultInstance; + public static NetworkOperatorSettings getDefaultInstance() { + return defaultInstance; + } + + public NetworkOperatorSettings getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkOperatorSettings_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkOperatorSettings_fieldAccessorTable; + } + + public enum OperatorSelectMode + implements com.google.protobuf.ProtocolMessageEnum { + AUTOMATIC(0, 0), + MANUAL(1, 1), + DEREGISTER(2, 2), + SET_ONLY(3, 3), + MANUAL_AUTOMATIC(4, 4), + ; + + public static final int AUTOMATIC_VALUE = 0; + public static final int MANUAL_VALUE = 1; + public static final int DEREGISTER_VALUE = 2; + public static final int SET_ONLY_VALUE = 3; + public static final int MANUAL_AUTOMATIC_VALUE = 4; + + + public final int getNumber() { return value; } + + public static OperatorSelectMode valueOf(int value) { + switch (value) { + case 0: return AUTOMATIC; + case 1: return MANUAL; + case 2: return DEREGISTER; + case 3: return SET_ONLY; + case 4: return MANUAL_AUTOMATIC; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public OperatorSelectMode findValueByNumber(int number) { + return OperatorSelectMode.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return com.openxc.BinaryMessages.NetworkOperatorSettings.getDescriptor().getEnumTypes().get(0); + } + + private static final OperatorSelectMode[] VALUES = { + AUTOMATIC, MANUAL, DEREGISTER, SET_ONLY, MANUAL_AUTOMATIC, + }; + + public static OperatorSelectMode valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private OperatorSelectMode(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:openxc.NetworkOperatorSettings.OperatorSelectMode) + } + + public interface NetworkDescriptorOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional uint32 PLMN = 1; + boolean hasPLMN(); + int getPLMN(); + + // optional .openxc.NetworkOperatorSettings.NetworkDescriptor.NetworkType networkType = 2; + boolean hasNetworkType(); + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType getNetworkType(); + } + public static final class NetworkDescriptor extends + com.google.protobuf.GeneratedMessage + implements NetworkDescriptorOrBuilder { + // Use NetworkDescriptor.newBuilder() to construct. + private NetworkDescriptor(Builder builder) { + super(builder); + } + private NetworkDescriptor(boolean noInit) {} + + private static final NetworkDescriptor defaultInstance; + public static NetworkDescriptor getDefaultInstance() { + return defaultInstance; + } + + public NetworkDescriptor getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkOperatorSettings_NetworkDescriptor_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkOperatorSettings_NetworkDescriptor_fieldAccessorTable; + } + + public enum NetworkType + implements com.google.protobuf.ProtocolMessageEnum { + GSM(0, 0), + UTRAN(1, 2), + ; + + public static final int GSM_VALUE = 0; + public static final int UTRAN_VALUE = 2; + + + public final int getNumber() { return value; } + + public static NetworkType valueOf(int value) { + switch (value) { + case 0: return GSM; + case 2: return UTRAN; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public NetworkType findValueByNumber(int number) { + return NetworkType.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.getDescriptor().getEnumTypes().get(0); + } + + private static final NetworkType[] VALUES = { + GSM, UTRAN, + }; + + public static NetworkType valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private NetworkType(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:openxc.NetworkOperatorSettings.NetworkDescriptor.NetworkType) + } + + private int bitField0_; + // optional uint32 PLMN = 1; + public static final int PLMN_FIELD_NUMBER = 1; + private int pLMN_; + public boolean hasPLMN() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getPLMN() { + return pLMN_; + } + + // optional .openxc.NetworkOperatorSettings.NetworkDescriptor.NetworkType networkType = 2; + public static final int NETWORKTYPE_FIELD_NUMBER = 2; + private com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType networkType_; + public boolean hasNetworkType() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType getNetworkType() { + return networkType_; + } + + private void initFields() { + pLMN_ = 0; + networkType_ = com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType.GSM; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeUInt32(1, pLMN_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeEnum(2, networkType_.getNumber()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(1, pLMN_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(2, networkType_.getNumber()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptorOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkOperatorSettings_NetworkDescriptor_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkOperatorSettings_NetworkDescriptor_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + pLMN_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + networkType_ = com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType.GSM; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.getDescriptor(); + } + + public com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor getDefaultInstanceForType() { + return com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor build() { + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor buildPartial() { + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor result = new com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.pLMN_ = pLMN_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.networkType_ = networkType_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor) { + return mergeFrom((com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor other) { + if (other == com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.getDefaultInstance()) return this; + if (other.hasPLMN()) { + setPLMN(other.getPLMN()); + } + if (other.hasNetworkType()) { + setNetworkType(other.getNetworkType()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + pLMN_ = input.readUInt32(); + break; + } + case 16: { + int rawValue = input.readEnum(); + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType value = com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(2, rawValue); + } else { + bitField0_ |= 0x00000002; + networkType_ = value; + } + break; + } + } + } + } + + private int bitField0_; + + // optional uint32 PLMN = 1; + private int pLMN_ ; + public boolean hasPLMN() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getPLMN() { + return pLMN_; + } + public Builder setPLMN(int value) { + bitField0_ |= 0x00000001; + pLMN_ = value; + onChanged(); + return this; + } + public Builder clearPLMN() { + bitField0_ = (bitField0_ & ~0x00000001); + pLMN_ = 0; + onChanged(); + return this; + } + + // optional .openxc.NetworkOperatorSettings.NetworkDescriptor.NetworkType networkType = 2; + private com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType networkType_ = com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType.GSM; + public boolean hasNetworkType() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType getNetworkType() { + return networkType_; + } + public Builder setNetworkType(com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + networkType_ = value; + onChanged(); + return this; + } + public Builder clearNetworkType() { + bitField0_ = (bitField0_ & ~0x00000002); + networkType_ = com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.NetworkType.GSM; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.NetworkOperatorSettings.NetworkDescriptor) + } + + static { + defaultInstance = new NetworkDescriptor(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.NetworkOperatorSettings.NetworkDescriptor) + } + + private int bitField0_; + // optional bool allowDataRoaming = 1; + public static final int ALLOWDATAROAMING_FIELD_NUMBER = 1; + private boolean allowDataRoaming_; + public boolean hasAllowDataRoaming() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public boolean getAllowDataRoaming() { + return allowDataRoaming_; + } + + // optional .openxc.NetworkOperatorSettings.OperatorSelectMode operatorSelectMode = 2; + public static final int OPERATORSELECTMODE_FIELD_NUMBER = 2; + private com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode operatorSelectMode_; + public boolean hasOperatorSelectMode() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode getOperatorSelectMode() { + return operatorSelectMode_; + } + + // optional .openxc.NetworkOperatorSettings.NetworkDescriptor networkDescriptor = 3; + public static final int NETWORKDESCRIPTOR_FIELD_NUMBER = 3; + private com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor networkDescriptor_; + public boolean hasNetworkDescriptor() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor getNetworkDescriptor() { + return networkDescriptor_; + } + public com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptorOrBuilder getNetworkDescriptorOrBuilder() { + return networkDescriptor_; + } + + private void initFields() { + allowDataRoaming_ = false; + operatorSelectMode_ = com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode.AUTOMATIC; + networkDescriptor_ = com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.getDefaultInstance(); + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBool(1, allowDataRoaming_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeEnum(2, operatorSelectMode_.getNumber()); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, networkDescriptor_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(1, allowDataRoaming_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(2, operatorSelectMode_.getNumber()); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, networkDescriptor_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.NetworkOperatorSettings parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkOperatorSettings parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.NetworkOperatorSettings prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.NetworkOperatorSettingsOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkOperatorSettings_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkOperatorSettings_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.NetworkOperatorSettings.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getNetworkDescriptorFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + allowDataRoaming_ = false; + bitField0_ = (bitField0_ & ~0x00000001); + operatorSelectMode_ = com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode.AUTOMATIC; + bitField0_ = (bitField0_ & ~0x00000002); + if (networkDescriptorBuilder_ == null) { + networkDescriptor_ = com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.getDefaultInstance(); + } else { + networkDescriptorBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.NetworkOperatorSettings.getDescriptor(); + } + + public com.openxc.BinaryMessages.NetworkOperatorSettings getDefaultInstanceForType() { + return com.openxc.BinaryMessages.NetworkOperatorSettings.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.NetworkOperatorSettings build() { + com.openxc.BinaryMessages.NetworkOperatorSettings result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.NetworkOperatorSettings buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.NetworkOperatorSettings result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.NetworkOperatorSettings buildPartial() { + com.openxc.BinaryMessages.NetworkOperatorSettings result = new com.openxc.BinaryMessages.NetworkOperatorSettings(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.allowDataRoaming_ = allowDataRoaming_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.operatorSelectMode_ = operatorSelectMode_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + if (networkDescriptorBuilder_ == null) { + result.networkDescriptor_ = networkDescriptor_; + } else { + result.networkDescriptor_ = networkDescriptorBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.NetworkOperatorSettings) { + return mergeFrom((com.openxc.BinaryMessages.NetworkOperatorSettings)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.NetworkOperatorSettings other) { + if (other == com.openxc.BinaryMessages.NetworkOperatorSettings.getDefaultInstance()) return this; + if (other.hasAllowDataRoaming()) { + setAllowDataRoaming(other.getAllowDataRoaming()); + } + if (other.hasOperatorSelectMode()) { + setOperatorSelectMode(other.getOperatorSelectMode()); + } + if (other.hasNetworkDescriptor()) { + mergeNetworkDescriptor(other.getNetworkDescriptor()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + allowDataRoaming_ = input.readBool(); + break; + } + case 16: { + int rawValue = input.readEnum(); + com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode value = com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(2, rawValue); + } else { + bitField0_ |= 0x00000002; + operatorSelectMode_ = value; + } + break; + } + case 26: { + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.Builder subBuilder = com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.newBuilder(); + if (hasNetworkDescriptor()) { + subBuilder.mergeFrom(getNetworkDescriptor()); + } + input.readMessage(subBuilder, extensionRegistry); + setNetworkDescriptor(subBuilder.buildPartial()); + break; + } + } + } + } + + private int bitField0_; + + // optional bool allowDataRoaming = 1; + private boolean allowDataRoaming_ ; + public boolean hasAllowDataRoaming() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public boolean getAllowDataRoaming() { + return allowDataRoaming_; + } + public Builder setAllowDataRoaming(boolean value) { + bitField0_ |= 0x00000001; + allowDataRoaming_ = value; + onChanged(); + return this; + } + public Builder clearAllowDataRoaming() { + bitField0_ = (bitField0_ & ~0x00000001); + allowDataRoaming_ = false; + onChanged(); + return this; + } + + // optional .openxc.NetworkOperatorSettings.OperatorSelectMode operatorSelectMode = 2; + private com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode operatorSelectMode_ = com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode.AUTOMATIC; + public boolean hasOperatorSelectMode() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode getOperatorSelectMode() { + return operatorSelectMode_; + } + public Builder setOperatorSelectMode(com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + operatorSelectMode_ = value; + onChanged(); + return this; + } + public Builder clearOperatorSelectMode() { + bitField0_ = (bitField0_ & ~0x00000002); + operatorSelectMode_ = com.openxc.BinaryMessages.NetworkOperatorSettings.OperatorSelectMode.AUTOMATIC; + onChanged(); + return this; + } + + // optional .openxc.NetworkOperatorSettings.NetworkDescriptor networkDescriptor = 3; + private com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor networkDescriptor_ = com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor, com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.Builder, com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptorOrBuilder> networkDescriptorBuilder_; + public boolean hasNetworkDescriptor() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor getNetworkDescriptor() { + if (networkDescriptorBuilder_ == null) { + return networkDescriptor_; + } else { + return networkDescriptorBuilder_.getMessage(); + } + } + public Builder setNetworkDescriptor(com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor value) { + if (networkDescriptorBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + networkDescriptor_ = value; + onChanged(); + } else { + networkDescriptorBuilder_.setMessage(value); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder setNetworkDescriptor( + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.Builder builderForValue) { + if (networkDescriptorBuilder_ == null) { + networkDescriptor_ = builderForValue.build(); + onChanged(); + } else { + networkDescriptorBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder mergeNetworkDescriptor(com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor value) { + if (networkDescriptorBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + networkDescriptor_ != com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.getDefaultInstance()) { + networkDescriptor_ = + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.newBuilder(networkDescriptor_).mergeFrom(value).buildPartial(); + } else { + networkDescriptor_ = value; + } + onChanged(); + } else { + networkDescriptorBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder clearNetworkDescriptor() { + if (networkDescriptorBuilder_ == null) { + networkDescriptor_ = com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.getDefaultInstance(); + onChanged(); + } else { + networkDescriptorBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + public com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.Builder getNetworkDescriptorBuilder() { + bitField0_ |= 0x00000004; + onChanged(); + return getNetworkDescriptorFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptorOrBuilder getNetworkDescriptorOrBuilder() { + if (networkDescriptorBuilder_ != null) { + return networkDescriptorBuilder_.getMessageOrBuilder(); + } else { + return networkDescriptor_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor, com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.Builder, com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptorOrBuilder> + getNetworkDescriptorFieldBuilder() { + if (networkDescriptorBuilder_ == null) { + networkDescriptorBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor, com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.Builder, com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptorOrBuilder>( + networkDescriptor_, + getParentForChildren(), + isClean()); + networkDescriptor_ = null; + } + return networkDescriptorBuilder_; + } + + // @@protoc_insertion_point(builder_scope:openxc.NetworkOperatorSettings) + } + + static { + defaultInstance = new NetworkOperatorSettings(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.NetworkOperatorSettings) + } + + public interface NetworkDataSettingsOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional string APN = 1; + boolean hasAPN(); + String getAPN(); + } + public static final class NetworkDataSettings extends + com.google.protobuf.GeneratedMessage + implements NetworkDataSettingsOrBuilder { + // Use NetworkDataSettings.newBuilder() to construct. + private NetworkDataSettings(Builder builder) { + super(builder); + } + private NetworkDataSettings(boolean noInit) {} + + private static final NetworkDataSettings defaultInstance; + public static NetworkDataSettings getDefaultInstance() { + return defaultInstance; + } + + public NetworkDataSettings getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkDataSettings_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkDataSettings_fieldAccessorTable; + } + + private int bitField0_; + // optional string APN = 1; + public static final int APN_FIELD_NUMBER = 1; + private java.lang.Object aPN_; + public boolean hasAPN() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getAPN() { + java.lang.Object ref = aPN_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + aPN_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getAPNBytes() { + java.lang.Object ref = aPN_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + aPN_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private void initFields() { + aPN_ = ""; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, getAPNBytes()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(1, getAPNBytes()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.NetworkDataSettings parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkDataSettings parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkDataSettings parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkDataSettings parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkDataSettings parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkDataSettings parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkDataSettings parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.NetworkDataSettings parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.NetworkDataSettings parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.NetworkDataSettings parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.NetworkDataSettings prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.NetworkDataSettingsOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkDataSettings_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_NetworkDataSettings_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.NetworkDataSettings.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + aPN_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.NetworkDataSettings.getDescriptor(); + } + + public com.openxc.BinaryMessages.NetworkDataSettings getDefaultInstanceForType() { + return com.openxc.BinaryMessages.NetworkDataSettings.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.NetworkDataSettings build() { + com.openxc.BinaryMessages.NetworkDataSettings result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.NetworkDataSettings buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.NetworkDataSettings result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.NetworkDataSettings buildPartial() { + com.openxc.BinaryMessages.NetworkDataSettings result = new com.openxc.BinaryMessages.NetworkDataSettings(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.aPN_ = aPN_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.NetworkDataSettings) { + return mergeFrom((com.openxc.BinaryMessages.NetworkDataSettings)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.NetworkDataSettings other) { + if (other == com.openxc.BinaryMessages.NetworkDataSettings.getDefaultInstance()) return this; + if (other.hasAPN()) { + setAPN(other.getAPN()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 10: { + bitField0_ |= 0x00000001; + aPN_ = input.readBytes(); + break; + } + } + } + } + + private int bitField0_; + + // optional string APN = 1; + private java.lang.Object aPN_ = ""; + public boolean hasAPN() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getAPN() { + java.lang.Object ref = aPN_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + aPN_ = s; + return s; + } else { + return (String) ref; + } + } + public Builder setAPN(String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + aPN_ = value; + onChanged(); + return this; + } + public Builder clearAPN() { + bitField0_ = (bitField0_ & ~0x00000001); + aPN_ = getDefaultInstance().getAPN(); + onChanged(); + return this; + } + void setAPN(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000001; + aPN_ = value; + onChanged(); + } + + // @@protoc_insertion_point(builder_scope:openxc.NetworkDataSettings) + } + + static { + defaultInstance = new NetworkDataSettings(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.NetworkDataSettings) + } + + public interface ServerConnectSettingsOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional string host = 1; + boolean hasHost(); + String getHost(); + + // optional uint32 port = 2; + boolean hasPort(); + int getPort(); + } + public static final class ServerConnectSettings extends + com.google.protobuf.GeneratedMessage + implements ServerConnectSettingsOrBuilder { + // Use ServerConnectSettings.newBuilder() to construct. + private ServerConnectSettings(Builder builder) { + super(builder); + } + private ServerConnectSettings(boolean noInit) {} + + private static final ServerConnectSettings defaultInstance; + public static ServerConnectSettings getDefaultInstance() { + return defaultInstance; + } + + public ServerConnectSettings getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_ServerConnectSettings_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_ServerConnectSettings_fieldAccessorTable; + } + + private int bitField0_; + // optional string host = 1; + public static final int HOST_FIELD_NUMBER = 1; + private java.lang.Object host_; + public boolean hasHost() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getHost() { + java.lang.Object ref = host_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + host_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getHostBytes() { + java.lang.Object ref = host_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + host_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + // optional uint32 port = 2; + public static final int PORT_FIELD_NUMBER = 2; + private int port_; + public boolean hasPort() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public int getPort() { + return port_; + } + + private void initFields() { + host_ = ""; + port_ = 0; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, getHostBytes()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeUInt32(2, port_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(1, getHostBytes()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(2, port_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.ServerConnectSettings parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.ServerConnectSettings parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.ServerConnectSettings parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.ServerConnectSettings parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.ServerConnectSettings parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.ServerConnectSettings parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.ServerConnectSettings parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.ServerConnectSettings parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.ServerConnectSettings parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.ServerConnectSettings parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.ServerConnectSettings prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.ServerConnectSettingsOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_ServerConnectSettings_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_ServerConnectSettings_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.ServerConnectSettings.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + host_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + port_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.ServerConnectSettings.getDescriptor(); + } + + public com.openxc.BinaryMessages.ServerConnectSettings getDefaultInstanceForType() { + return com.openxc.BinaryMessages.ServerConnectSettings.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.ServerConnectSettings build() { + com.openxc.BinaryMessages.ServerConnectSettings result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.ServerConnectSettings buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.ServerConnectSettings result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.ServerConnectSettings buildPartial() { + com.openxc.BinaryMessages.ServerConnectSettings result = new com.openxc.BinaryMessages.ServerConnectSettings(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.host_ = host_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.port_ = port_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.ServerConnectSettings) { + return mergeFrom((com.openxc.BinaryMessages.ServerConnectSettings)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.ServerConnectSettings other) { + if (other == com.openxc.BinaryMessages.ServerConnectSettings.getDefaultInstance()) return this; + if (other.hasHost()) { + setHost(other.getHost()); + } + if (other.hasPort()) { + setPort(other.getPort()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 10: { + bitField0_ |= 0x00000001; + host_ = input.readBytes(); + break; + } + case 16: { + bitField0_ |= 0x00000002; + port_ = input.readUInt32(); + break; + } + } + } + } + + private int bitField0_; + + // optional string host = 1; + private java.lang.Object host_ = ""; + public boolean hasHost() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getHost() { + java.lang.Object ref = host_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + host_ = s; + return s; + } else { + return (String) ref; + } + } + public Builder setHost(String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + host_ = value; + onChanged(); + return this; + } + public Builder clearHost() { + bitField0_ = (bitField0_ & ~0x00000001); + host_ = getDefaultInstance().getHost(); + onChanged(); + return this; + } + void setHost(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000001; + host_ = value; + onChanged(); + } + + // optional uint32 port = 2; + private int port_ ; + public boolean hasPort() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public int getPort() { + return port_; + } + public Builder setPort(int value) { + bitField0_ |= 0x00000002; + port_ = value; + onChanged(); + return this; + } + public Builder clearPort() { + bitField0_ = (bitField0_ & ~0x00000002); + port_ = 0; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.ServerConnectSettings) + } + + static { + defaultInstance = new ServerConnectSettings(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.ServerConnectSettings) + } + + public interface ModemConfigurationCommandOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional .openxc.NetworkOperatorSettings networkOperatorSettings = 1; + boolean hasNetworkOperatorSettings(); + com.openxc.BinaryMessages.NetworkOperatorSettings getNetworkOperatorSettings(); + com.openxc.BinaryMessages.NetworkOperatorSettingsOrBuilder getNetworkOperatorSettingsOrBuilder(); + + // optional .openxc.NetworkDataSettings networkDataSettings = 2; + boolean hasNetworkDataSettings(); + com.openxc.BinaryMessages.NetworkDataSettings getNetworkDataSettings(); + com.openxc.BinaryMessages.NetworkDataSettingsOrBuilder getNetworkDataSettingsOrBuilder(); + + // optional .openxc.ServerConnectSettings serverConnectSettings = 3; + boolean hasServerConnectSettings(); + com.openxc.BinaryMessages.ServerConnectSettings getServerConnectSettings(); + com.openxc.BinaryMessages.ServerConnectSettingsOrBuilder getServerConnectSettingsOrBuilder(); + } + public static final class ModemConfigurationCommand extends + com.google.protobuf.GeneratedMessage + implements ModemConfigurationCommandOrBuilder { + // Use ModemConfigurationCommand.newBuilder() to construct. + private ModemConfigurationCommand(Builder builder) { + super(builder); + } + private ModemConfigurationCommand(boolean noInit) {} + + private static final ModemConfigurationCommand defaultInstance; + public static ModemConfigurationCommand getDefaultInstance() { + return defaultInstance; + } + + public ModemConfigurationCommand getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_ModemConfigurationCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_ModemConfigurationCommand_fieldAccessorTable; + } + + private int bitField0_; + // optional .openxc.NetworkOperatorSettings networkOperatorSettings = 1; + public static final int NETWORKOPERATORSETTINGS_FIELD_NUMBER = 1; + private com.openxc.BinaryMessages.NetworkOperatorSettings networkOperatorSettings_; + public boolean hasNetworkOperatorSettings() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.NetworkOperatorSettings getNetworkOperatorSettings() { + return networkOperatorSettings_; + } + public com.openxc.BinaryMessages.NetworkOperatorSettingsOrBuilder getNetworkOperatorSettingsOrBuilder() { + return networkOperatorSettings_; + } + + // optional .openxc.NetworkDataSettings networkDataSettings = 2; + public static final int NETWORKDATASETTINGS_FIELD_NUMBER = 2; + private com.openxc.BinaryMessages.NetworkDataSettings networkDataSettings_; + public boolean hasNetworkDataSettings() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.NetworkDataSettings getNetworkDataSettings() { + return networkDataSettings_; + } + public com.openxc.BinaryMessages.NetworkDataSettingsOrBuilder getNetworkDataSettingsOrBuilder() { + return networkDataSettings_; + } + + // optional .openxc.ServerConnectSettings serverConnectSettings = 3; + public static final int SERVERCONNECTSETTINGS_FIELD_NUMBER = 3; + private com.openxc.BinaryMessages.ServerConnectSettings serverConnectSettings_; + public boolean hasServerConnectSettings() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.openxc.BinaryMessages.ServerConnectSettings getServerConnectSettings() { + return serverConnectSettings_; + } + public com.openxc.BinaryMessages.ServerConnectSettingsOrBuilder getServerConnectSettingsOrBuilder() { + return serverConnectSettings_; + } + + private void initFields() { + networkOperatorSettings_ = com.openxc.BinaryMessages.NetworkOperatorSettings.getDefaultInstance(); + networkDataSettings_ = com.openxc.BinaryMessages.NetworkDataSettings.getDefaultInstance(); + serverConnectSettings_ = com.openxc.BinaryMessages.ServerConnectSettings.getDefaultInstance(); + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeMessage(1, networkOperatorSettings_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeMessage(2, networkDataSettings_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, serverConnectSettings_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(1, networkOperatorSettings_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, networkDataSettings_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, serverConnectSettings_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.ModemConfigurationCommand parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.ModemConfigurationCommand parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.ModemConfigurationCommand parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.ModemConfigurationCommand parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.ModemConfigurationCommand parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.ModemConfigurationCommand parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.ModemConfigurationCommand parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.ModemConfigurationCommand parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.ModemConfigurationCommand parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.ModemConfigurationCommand parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.ModemConfigurationCommand prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.ModemConfigurationCommandOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_ModemConfigurationCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_ModemConfigurationCommand_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.ModemConfigurationCommand.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getNetworkOperatorSettingsFieldBuilder(); + getNetworkDataSettingsFieldBuilder(); + getServerConnectSettingsFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + if (networkOperatorSettingsBuilder_ == null) { + networkOperatorSettings_ = com.openxc.BinaryMessages.NetworkOperatorSettings.getDefaultInstance(); + } else { + networkOperatorSettingsBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); + if (networkDataSettingsBuilder_ == null) { + networkDataSettings_ = com.openxc.BinaryMessages.NetworkDataSettings.getDefaultInstance(); + } else { + networkDataSettingsBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + if (serverConnectSettingsBuilder_ == null) { + serverConnectSettings_ = com.openxc.BinaryMessages.ServerConnectSettings.getDefaultInstance(); + } else { + serverConnectSettingsBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.ModemConfigurationCommand.getDescriptor(); + } + + public com.openxc.BinaryMessages.ModemConfigurationCommand getDefaultInstanceForType() { + return com.openxc.BinaryMessages.ModemConfigurationCommand.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.ModemConfigurationCommand build() { + com.openxc.BinaryMessages.ModemConfigurationCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.ModemConfigurationCommand buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.ModemConfigurationCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.ModemConfigurationCommand buildPartial() { + com.openxc.BinaryMessages.ModemConfigurationCommand result = new com.openxc.BinaryMessages.ModemConfigurationCommand(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + if (networkOperatorSettingsBuilder_ == null) { + result.networkOperatorSettings_ = networkOperatorSettings_; + } else { + result.networkOperatorSettings_ = networkOperatorSettingsBuilder_.build(); + } + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + if (networkDataSettingsBuilder_ == null) { + result.networkDataSettings_ = networkDataSettings_; + } else { + result.networkDataSettings_ = networkDataSettingsBuilder_.build(); + } + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + if (serverConnectSettingsBuilder_ == null) { + result.serverConnectSettings_ = serverConnectSettings_; + } else { + result.serverConnectSettings_ = serverConnectSettingsBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.ModemConfigurationCommand) { + return mergeFrom((com.openxc.BinaryMessages.ModemConfigurationCommand)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.ModemConfigurationCommand other) { + if (other == com.openxc.BinaryMessages.ModemConfigurationCommand.getDefaultInstance()) return this; + if (other.hasNetworkOperatorSettings()) { + mergeNetworkOperatorSettings(other.getNetworkOperatorSettings()); + } + if (other.hasNetworkDataSettings()) { + mergeNetworkDataSettings(other.getNetworkDataSettings()); + } + if (other.hasServerConnectSettings()) { + mergeServerConnectSettings(other.getServerConnectSettings()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 10: { + com.openxc.BinaryMessages.NetworkOperatorSettings.Builder subBuilder = com.openxc.BinaryMessages.NetworkOperatorSettings.newBuilder(); + if (hasNetworkOperatorSettings()) { + subBuilder.mergeFrom(getNetworkOperatorSettings()); + } + input.readMessage(subBuilder, extensionRegistry); + setNetworkOperatorSettings(subBuilder.buildPartial()); + break; + } + case 18: { + com.openxc.BinaryMessages.NetworkDataSettings.Builder subBuilder = com.openxc.BinaryMessages.NetworkDataSettings.newBuilder(); + if (hasNetworkDataSettings()) { + subBuilder.mergeFrom(getNetworkDataSettings()); + } + input.readMessage(subBuilder, extensionRegistry); + setNetworkDataSettings(subBuilder.buildPartial()); + break; + } + case 26: { + com.openxc.BinaryMessages.ServerConnectSettings.Builder subBuilder = com.openxc.BinaryMessages.ServerConnectSettings.newBuilder(); + if (hasServerConnectSettings()) { + subBuilder.mergeFrom(getServerConnectSettings()); + } + input.readMessage(subBuilder, extensionRegistry); + setServerConnectSettings(subBuilder.buildPartial()); + break; + } + } + } + } + + private int bitField0_; + + // optional .openxc.NetworkOperatorSettings networkOperatorSettings = 1; + private com.openxc.BinaryMessages.NetworkOperatorSettings networkOperatorSettings_ = com.openxc.BinaryMessages.NetworkOperatorSettings.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.NetworkOperatorSettings, com.openxc.BinaryMessages.NetworkOperatorSettings.Builder, com.openxc.BinaryMessages.NetworkOperatorSettingsOrBuilder> networkOperatorSettingsBuilder_; + public boolean hasNetworkOperatorSettings() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.NetworkOperatorSettings getNetworkOperatorSettings() { + if (networkOperatorSettingsBuilder_ == null) { + return networkOperatorSettings_; + } else { + return networkOperatorSettingsBuilder_.getMessage(); + } + } + public Builder setNetworkOperatorSettings(com.openxc.BinaryMessages.NetworkOperatorSettings value) { + if (networkOperatorSettingsBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + networkOperatorSettings_ = value; + onChanged(); + } else { + networkOperatorSettingsBuilder_.setMessage(value); + } + bitField0_ |= 0x00000001; + return this; + } + public Builder setNetworkOperatorSettings( + com.openxc.BinaryMessages.NetworkOperatorSettings.Builder builderForValue) { + if (networkOperatorSettingsBuilder_ == null) { + networkOperatorSettings_ = builderForValue.build(); + onChanged(); + } else { + networkOperatorSettingsBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000001; + return this; + } + public Builder mergeNetworkOperatorSettings(com.openxc.BinaryMessages.NetworkOperatorSettings value) { + if (networkOperatorSettingsBuilder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001) && + networkOperatorSettings_ != com.openxc.BinaryMessages.NetworkOperatorSettings.getDefaultInstance()) { + networkOperatorSettings_ = + com.openxc.BinaryMessages.NetworkOperatorSettings.newBuilder(networkOperatorSettings_).mergeFrom(value).buildPartial(); + } else { + networkOperatorSettings_ = value; + } + onChanged(); + } else { + networkOperatorSettingsBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000001; + return this; + } + public Builder clearNetworkOperatorSettings() { + if (networkOperatorSettingsBuilder_ == null) { + networkOperatorSettings_ = com.openxc.BinaryMessages.NetworkOperatorSettings.getDefaultInstance(); + onChanged(); + } else { + networkOperatorSettingsBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000001); + return this; + } + public com.openxc.BinaryMessages.NetworkOperatorSettings.Builder getNetworkOperatorSettingsBuilder() { + bitField0_ |= 0x00000001; + onChanged(); + return getNetworkOperatorSettingsFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.NetworkOperatorSettingsOrBuilder getNetworkOperatorSettingsOrBuilder() { + if (networkOperatorSettingsBuilder_ != null) { + return networkOperatorSettingsBuilder_.getMessageOrBuilder(); + } else { + return networkOperatorSettings_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.NetworkOperatorSettings, com.openxc.BinaryMessages.NetworkOperatorSettings.Builder, com.openxc.BinaryMessages.NetworkOperatorSettingsOrBuilder> + getNetworkOperatorSettingsFieldBuilder() { + if (networkOperatorSettingsBuilder_ == null) { + networkOperatorSettingsBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.NetworkOperatorSettings, com.openxc.BinaryMessages.NetworkOperatorSettings.Builder, com.openxc.BinaryMessages.NetworkOperatorSettingsOrBuilder>( + networkOperatorSettings_, + getParentForChildren(), + isClean()); + networkOperatorSettings_ = null; + } + return networkOperatorSettingsBuilder_; + } + + // optional .openxc.NetworkDataSettings networkDataSettings = 2; + private com.openxc.BinaryMessages.NetworkDataSettings networkDataSettings_ = com.openxc.BinaryMessages.NetworkDataSettings.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.NetworkDataSettings, com.openxc.BinaryMessages.NetworkDataSettings.Builder, com.openxc.BinaryMessages.NetworkDataSettingsOrBuilder> networkDataSettingsBuilder_; + public boolean hasNetworkDataSettings() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.NetworkDataSettings getNetworkDataSettings() { + if (networkDataSettingsBuilder_ == null) { + return networkDataSettings_; + } else { + return networkDataSettingsBuilder_.getMessage(); + } + } + public Builder setNetworkDataSettings(com.openxc.BinaryMessages.NetworkDataSettings value) { + if (networkDataSettingsBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + networkDataSettings_ = value; + onChanged(); + } else { + networkDataSettingsBuilder_.setMessage(value); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder setNetworkDataSettings( + com.openxc.BinaryMessages.NetworkDataSettings.Builder builderForValue) { + if (networkDataSettingsBuilder_ == null) { + networkDataSettings_ = builderForValue.build(); + onChanged(); + } else { + networkDataSettingsBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder mergeNetworkDataSettings(com.openxc.BinaryMessages.NetworkDataSettings value) { + if (networkDataSettingsBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002) && + networkDataSettings_ != com.openxc.BinaryMessages.NetworkDataSettings.getDefaultInstance()) { + networkDataSettings_ = + com.openxc.BinaryMessages.NetworkDataSettings.newBuilder(networkDataSettings_).mergeFrom(value).buildPartial(); + } else { + networkDataSettings_ = value; + } + onChanged(); + } else { + networkDataSettingsBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder clearNetworkDataSettings() { + if (networkDataSettingsBuilder_ == null) { + networkDataSettings_ = com.openxc.BinaryMessages.NetworkDataSettings.getDefaultInstance(); + onChanged(); + } else { + networkDataSettingsBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + public com.openxc.BinaryMessages.NetworkDataSettings.Builder getNetworkDataSettingsBuilder() { + bitField0_ |= 0x00000002; + onChanged(); + return getNetworkDataSettingsFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.NetworkDataSettingsOrBuilder getNetworkDataSettingsOrBuilder() { + if (networkDataSettingsBuilder_ != null) { + return networkDataSettingsBuilder_.getMessageOrBuilder(); + } else { + return networkDataSettings_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.NetworkDataSettings, com.openxc.BinaryMessages.NetworkDataSettings.Builder, com.openxc.BinaryMessages.NetworkDataSettingsOrBuilder> + getNetworkDataSettingsFieldBuilder() { + if (networkDataSettingsBuilder_ == null) { + networkDataSettingsBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.NetworkDataSettings, com.openxc.BinaryMessages.NetworkDataSettings.Builder, com.openxc.BinaryMessages.NetworkDataSettingsOrBuilder>( + networkDataSettings_, + getParentForChildren(), + isClean()); + networkDataSettings_ = null; + } + return networkDataSettingsBuilder_; + } + + // optional .openxc.ServerConnectSettings serverConnectSettings = 3; + private com.openxc.BinaryMessages.ServerConnectSettings serverConnectSettings_ = com.openxc.BinaryMessages.ServerConnectSettings.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.ServerConnectSettings, com.openxc.BinaryMessages.ServerConnectSettings.Builder, com.openxc.BinaryMessages.ServerConnectSettingsOrBuilder> serverConnectSettingsBuilder_; + public boolean hasServerConnectSettings() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.openxc.BinaryMessages.ServerConnectSettings getServerConnectSettings() { + if (serverConnectSettingsBuilder_ == null) { + return serverConnectSettings_; + } else { + return serverConnectSettingsBuilder_.getMessage(); + } + } + public Builder setServerConnectSettings(com.openxc.BinaryMessages.ServerConnectSettings value) { + if (serverConnectSettingsBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + serverConnectSettings_ = value; + onChanged(); + } else { + serverConnectSettingsBuilder_.setMessage(value); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder setServerConnectSettings( + com.openxc.BinaryMessages.ServerConnectSettings.Builder builderForValue) { + if (serverConnectSettingsBuilder_ == null) { + serverConnectSettings_ = builderForValue.build(); + onChanged(); + } else { + serverConnectSettingsBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder mergeServerConnectSettings(com.openxc.BinaryMessages.ServerConnectSettings value) { + if (serverConnectSettingsBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + serverConnectSettings_ != com.openxc.BinaryMessages.ServerConnectSettings.getDefaultInstance()) { + serverConnectSettings_ = + com.openxc.BinaryMessages.ServerConnectSettings.newBuilder(serverConnectSettings_).mergeFrom(value).buildPartial(); + } else { + serverConnectSettings_ = value; + } + onChanged(); + } else { + serverConnectSettingsBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder clearServerConnectSettings() { + if (serverConnectSettingsBuilder_ == null) { + serverConnectSettings_ = com.openxc.BinaryMessages.ServerConnectSettings.getDefaultInstance(); + onChanged(); + } else { + serverConnectSettingsBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + public com.openxc.BinaryMessages.ServerConnectSettings.Builder getServerConnectSettingsBuilder() { + bitField0_ |= 0x00000004; + onChanged(); + return getServerConnectSettingsFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.ServerConnectSettingsOrBuilder getServerConnectSettingsOrBuilder() { + if (serverConnectSettingsBuilder_ != null) { + return serverConnectSettingsBuilder_.getMessageOrBuilder(); + } else { + return serverConnectSettings_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.ServerConnectSettings, com.openxc.BinaryMessages.ServerConnectSettings.Builder, com.openxc.BinaryMessages.ServerConnectSettingsOrBuilder> + getServerConnectSettingsFieldBuilder() { + if (serverConnectSettingsBuilder_ == null) { + serverConnectSettingsBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.ServerConnectSettings, com.openxc.BinaryMessages.ServerConnectSettings.Builder, com.openxc.BinaryMessages.ServerConnectSettingsOrBuilder>( + serverConnectSettings_, + getParentForChildren(), + isClean()); + serverConnectSettings_ = null; + } + return serverConnectSettingsBuilder_; + } + + // @@protoc_insertion_point(builder_scope:openxc.ModemConfigurationCommand) + } + + static { + defaultInstance = new ModemConfigurationCommand(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.ModemConfigurationCommand) + } + + public interface RTCConfigurationCommandOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional uint32 unix_time = 1; + boolean hasUnixTime(); + int getUnixTime(); + } + public static final class RTCConfigurationCommand extends + com.google.protobuf.GeneratedMessage + implements RTCConfigurationCommandOrBuilder { + // Use RTCConfigurationCommand.newBuilder() to construct. + private RTCConfigurationCommand(Builder builder) { + super(builder); + } + private RTCConfigurationCommand(boolean noInit) {} + + private static final RTCConfigurationCommand defaultInstance; + public static RTCConfigurationCommand getDefaultInstance() { + return defaultInstance; + } + + public RTCConfigurationCommand getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_RTCConfigurationCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_RTCConfigurationCommand_fieldAccessorTable; + } + + private int bitField0_; + // optional uint32 unix_time = 1; + public static final int UNIX_TIME_FIELD_NUMBER = 1; + private int unixTime_; + public boolean hasUnixTime() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getUnixTime() { + return unixTime_; + } + + private void initFields() { + unixTime_ = 0; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeUInt32(1, unixTime_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(1, unixTime_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.RTCConfigurationCommand parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.RTCConfigurationCommand parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.RTCConfigurationCommand parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.RTCConfigurationCommand parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.RTCConfigurationCommand parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.RTCConfigurationCommand parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.RTCConfigurationCommand parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.RTCConfigurationCommand parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.RTCConfigurationCommand parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.RTCConfigurationCommand parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.RTCConfigurationCommand prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.RTCConfigurationCommandOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_RTCConfigurationCommand_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_RTCConfigurationCommand_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.RTCConfigurationCommand.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + unixTime_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.RTCConfigurationCommand.getDescriptor(); + } + + public com.openxc.BinaryMessages.RTCConfigurationCommand getDefaultInstanceForType() { + return com.openxc.BinaryMessages.RTCConfigurationCommand.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.RTCConfigurationCommand build() { + com.openxc.BinaryMessages.RTCConfigurationCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.RTCConfigurationCommand buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.RTCConfigurationCommand result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.RTCConfigurationCommand buildPartial() { + com.openxc.BinaryMessages.RTCConfigurationCommand result = new com.openxc.BinaryMessages.RTCConfigurationCommand(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.unixTime_ = unixTime_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.RTCConfigurationCommand) { + return mergeFrom((com.openxc.BinaryMessages.RTCConfigurationCommand)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.RTCConfigurationCommand other) { + if (other == com.openxc.BinaryMessages.RTCConfigurationCommand.getDefaultInstance()) return this; + if (other.hasUnixTime()) { + setUnixTime(other.getUnixTime()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + unixTime_ = input.readUInt32(); + break; + } + } + } + } + + private int bitField0_; + + // optional uint32 unix_time = 1; + private int unixTime_ ; + public boolean hasUnixTime() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getUnixTime() { + return unixTime_; + } + public Builder setUnixTime(int value) { + bitField0_ |= 0x00000001; + unixTime_ = value; + onChanged(); + return this; + } + public Builder clearUnixTime() { + bitField0_ = (bitField0_ & ~0x00000001); + unixTime_ = 0; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.RTCConfigurationCommand) + } + + static { + defaultInstance = new RTCConfigurationCommand(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.RTCConfigurationCommand) + } + + public interface CommandResponseOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional .openxc.ControlCommand.Type type = 1; + boolean hasType(); + com.openxc.BinaryMessages.ControlCommand.Type getType(); + + // optional string message = 2; + boolean hasMessage(); + String getMessage(); + + // optional bool status = 3; + boolean hasStatus(); + boolean getStatus(); + } + public static final class CommandResponse extends + com.google.protobuf.GeneratedMessage + implements CommandResponseOrBuilder { + // Use CommandResponse.newBuilder() to construct. + private CommandResponse(Builder builder) { + super(builder); + } + private CommandResponse(boolean noInit) {} + + private static final CommandResponse defaultInstance; + public static CommandResponse getDefaultInstance() { + return defaultInstance; + } + + public CommandResponse getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_CommandResponse_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_CommandResponse_fieldAccessorTable; + } + + private int bitField0_; + // optional .openxc.ControlCommand.Type type = 1; + public static final int TYPE_FIELD_NUMBER = 1; + private com.openxc.BinaryMessages.ControlCommand.Type type_; + public boolean hasType() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.ControlCommand.Type getType() { + return type_; + } + + // optional string message = 2; + public static final int MESSAGE_FIELD_NUMBER = 2; + private java.lang.Object message_; + public boolean hasMessage() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getMessage() { + java.lang.Object ref = message_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + message_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + // optional bool status = 3; + public static final int STATUS_FIELD_NUMBER = 3; + private boolean status_; + public boolean hasStatus() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public boolean getStatus() { + return status_; + } + + private void initFields() { + type_ = com.openxc.BinaryMessages.ControlCommand.Type.VERSION; + message_ = ""; + status_ = false; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeEnum(1, type_.getNumber()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getMessageBytes()); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeBool(3, status_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(1, type_.getNumber()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(2, getMessageBytes()); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(3, status_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.CommandResponse parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.CommandResponse parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.CommandResponse parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.CommandResponse parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.CommandResponse parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.CommandResponse parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.CommandResponse parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.CommandResponse parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.CommandResponse parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.CommandResponse parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.CommandResponse prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.CommandResponseOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_CommandResponse_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_CommandResponse_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.CommandResponse.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + type_ = com.openxc.BinaryMessages.ControlCommand.Type.VERSION; + bitField0_ = (bitField0_ & ~0x00000001); + message_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + status_ = false; + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.CommandResponse.getDescriptor(); + } + + public com.openxc.BinaryMessages.CommandResponse getDefaultInstanceForType() { + return com.openxc.BinaryMessages.CommandResponse.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.CommandResponse build() { + com.openxc.BinaryMessages.CommandResponse result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.CommandResponse buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.CommandResponse result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.CommandResponse buildPartial() { + com.openxc.BinaryMessages.CommandResponse result = new com.openxc.BinaryMessages.CommandResponse(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.type_ = type_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.message_ = message_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.status_ = status_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.CommandResponse) { + return mergeFrom((com.openxc.BinaryMessages.CommandResponse)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.CommandResponse other) { + if (other == com.openxc.BinaryMessages.CommandResponse.getDefaultInstance()) return this; + if (other.hasType()) { + setType(other.getType()); + } + if (other.hasMessage()) { + setMessage(other.getMessage()); + } + if (other.hasStatus()) { + setStatus(other.getStatus()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + int rawValue = input.readEnum(); + com.openxc.BinaryMessages.ControlCommand.Type value = com.openxc.BinaryMessages.ControlCommand.Type.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(1, rawValue); + } else { + bitField0_ |= 0x00000001; + type_ = value; + } + break; + } + case 18: { + bitField0_ |= 0x00000002; + message_ = input.readBytes(); + break; + } + case 24: { + bitField0_ |= 0x00000004; + status_ = input.readBool(); + break; + } + } + } + } + + private int bitField0_; + + // optional .openxc.ControlCommand.Type type = 1; + private com.openxc.BinaryMessages.ControlCommand.Type type_ = com.openxc.BinaryMessages.ControlCommand.Type.VERSION; + public boolean hasType() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.ControlCommand.Type getType() { + return type_; + } + public Builder setType(com.openxc.BinaryMessages.ControlCommand.Type value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + type_ = value; + onChanged(); + return this; + } + public Builder clearType() { + bitField0_ = (bitField0_ & ~0x00000001); + type_ = com.openxc.BinaryMessages.ControlCommand.Type.VERSION; + onChanged(); + return this; + } + + // optional string message = 2; + private java.lang.Object message_ = ""; + public boolean hasMessage() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getMessage() { + java.lang.Object ref = message_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + message_ = s; + return s; + } else { + return (String) ref; + } + } + public Builder setMessage(String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + message_ = value; + onChanged(); + return this; + } + public Builder clearMessage() { + bitField0_ = (bitField0_ & ~0x00000002); + message_ = getDefaultInstance().getMessage(); + onChanged(); + return this; + } + void setMessage(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000002; + message_ = value; + onChanged(); + } + + // optional bool status = 3; + private boolean status_ ; + public boolean hasStatus() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public boolean getStatus() { + return status_; + } + public Builder setStatus(boolean value) { + bitField0_ |= 0x00000004; + status_ = value; + onChanged(); + return this; + } + public Builder clearStatus() { + bitField0_ = (bitField0_ & ~0x00000004); + status_ = false; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.CommandResponse) + } + + static { + defaultInstance = new CommandResponse(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.CommandResponse) + } + + public interface DiagnosticRequestOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional int32 bus = 1; + boolean hasBus(); + int getBus(); + + // optional uint32 message_id = 2; + boolean hasMessageId(); + int getMessageId(); + + // optional uint32 mode = 3; + boolean hasMode(); + int getMode(); + + // optional uint32 pid = 4; + boolean hasPid(); + int getPid(); + + // optional bytes payload = 5; + boolean hasPayload(); + com.google.protobuf.ByteString getPayload(); + + // optional bool multiple_responses = 6; + boolean hasMultipleResponses(); + boolean getMultipleResponses(); + + // optional double frequency = 7; + boolean hasFrequency(); + double getFrequency(); + + // optional string name = 8; + boolean hasName(); + String getName(); + + // optional .openxc.DiagnosticRequest.DecodedType decoded_type = 9; + boolean hasDecodedType(); + com.openxc.BinaryMessages.DiagnosticRequest.DecodedType getDecodedType(); + } + public static final class DiagnosticRequest extends + com.google.protobuf.GeneratedMessage + implements DiagnosticRequestOrBuilder { + // Use DiagnosticRequest.newBuilder() to construct. + private DiagnosticRequest(Builder builder) { + super(builder); + } + private DiagnosticRequest(boolean noInit) {} + + private static final DiagnosticRequest defaultInstance; + public static DiagnosticRequest getDefaultInstance() { + return defaultInstance; + } + + public DiagnosticRequest getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticRequest_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticRequest_fieldAccessorTable; + } + + public enum DecodedType + implements com.google.protobuf.ProtocolMessageEnum { + NONE(0, 1), + OBD2(1, 2), + ; + + public static final int NONE_VALUE = 1; + public static final int OBD2_VALUE = 2; + + + public final int getNumber() { return value; } + + public static DecodedType valueOf(int value) { + switch (value) { + case 1: return NONE; + case 2: return OBD2; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public DecodedType findValueByNumber(int number) { + return DecodedType.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return com.openxc.BinaryMessages.DiagnosticRequest.getDescriptor().getEnumTypes().get(0); + } + + private static final DecodedType[] VALUES = { + NONE, OBD2, + }; + + public static DecodedType valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private DecodedType(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:openxc.DiagnosticRequest.DecodedType) + } + + private int bitField0_; + // optional int32 bus = 1; + public static final int BUS_FIELD_NUMBER = 1; + private int bus_; + public boolean hasBus() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getBus() { + return bus_; + } + + // optional uint32 message_id = 2; + public static final int MESSAGE_ID_FIELD_NUMBER = 2; + private int messageId_; + public boolean hasMessageId() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public int getMessageId() { + return messageId_; + } + + // optional uint32 mode = 3; + public static final int MODE_FIELD_NUMBER = 3; + private int mode_; + public boolean hasMode() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public int getMode() { + return mode_; + } + + // optional uint32 pid = 4; + public static final int PID_FIELD_NUMBER = 4; + private int pid_; + public boolean hasPid() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public int getPid() { + return pid_; + } + + // optional bytes payload = 5; + public static final int PAYLOAD_FIELD_NUMBER = 5; + private com.google.protobuf.ByteString payload_; + public boolean hasPayload() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + public com.google.protobuf.ByteString getPayload() { + return payload_; + } + + // optional bool multiple_responses = 6; + public static final int MULTIPLE_RESPONSES_FIELD_NUMBER = 6; + private boolean multipleResponses_; + public boolean hasMultipleResponses() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + public boolean getMultipleResponses() { + return multipleResponses_; + } + + // optional double frequency = 7; + public static final int FREQUENCY_FIELD_NUMBER = 7; + private double frequency_; + public boolean hasFrequency() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + public double getFrequency() { + return frequency_; + } + + // optional string name = 8; + public static final int NAME_FIELD_NUMBER = 8; + private java.lang.Object name_; + public boolean hasName() { + return ((bitField0_ & 0x00000080) == 0x00000080); + } + public String getName() { + java.lang.Object ref = name_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + name_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + // optional .openxc.DiagnosticRequest.DecodedType decoded_type = 9; + public static final int DECODED_TYPE_FIELD_NUMBER = 9; + private com.openxc.BinaryMessages.DiagnosticRequest.DecodedType decodedType_; + public boolean hasDecodedType() { + return ((bitField0_ & 0x00000100) == 0x00000100); + } + public com.openxc.BinaryMessages.DiagnosticRequest.DecodedType getDecodedType() { + return decodedType_; + } + + private void initFields() { + bus_ = 0; + messageId_ = 0; + mode_ = 0; + pid_ = 0; + payload_ = com.google.protobuf.ByteString.EMPTY; + multipleResponses_ = false; + frequency_ = 0D; + name_ = ""; + decodedType_ = com.openxc.BinaryMessages.DiagnosticRequest.DecodedType.NONE; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, bus_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeUInt32(2, messageId_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeUInt32(3, mode_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeUInt32(4, pid_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeBytes(5, payload_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + output.writeBool(6, multipleResponses_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeDouble(7, frequency_); + } + if (((bitField0_ & 0x00000080) == 0x00000080)) { + output.writeBytes(8, getNameBytes()); + } + if (((bitField0_ & 0x00000100) == 0x00000100)) { + output.writeEnum(9, decodedType_.getNumber()); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, bus_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(2, messageId_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(3, mode_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(4, pid_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(5, payload_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(6, multipleResponses_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + size += com.google.protobuf.CodedOutputStream + .computeDoubleSize(7, frequency_); + } + if (((bitField0_ & 0x00000080) == 0x00000080)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(8, getNameBytes()); + } + if (((bitField0_ & 0x00000100) == 0x00000100)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(9, decodedType_.getNumber()); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.DiagnosticRequest parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticRequest parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticRequest parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticRequest parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticRequest parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticRequest parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticRequest parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.DiagnosticRequest parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.DiagnosticRequest parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticRequest parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.DiagnosticRequest prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.DiagnosticRequestOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticRequest_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticRequest_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.DiagnosticRequest.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + bus_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + messageId_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); + mode_ = 0; + bitField0_ = (bitField0_ & ~0x00000004); + pid_ = 0; + bitField0_ = (bitField0_ & ~0x00000008); + payload_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000010); + multipleResponses_ = false; + bitField0_ = (bitField0_ & ~0x00000020); + frequency_ = 0D; + bitField0_ = (bitField0_ & ~0x00000040); + name_ = ""; + bitField0_ = (bitField0_ & ~0x00000080); + decodedType_ = com.openxc.BinaryMessages.DiagnosticRequest.DecodedType.NONE; + bitField0_ = (bitField0_ & ~0x00000100); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.DiagnosticRequest.getDescriptor(); + } + + public com.openxc.BinaryMessages.DiagnosticRequest getDefaultInstanceForType() { + return com.openxc.BinaryMessages.DiagnosticRequest.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.DiagnosticRequest build() { + com.openxc.BinaryMessages.DiagnosticRequest result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.DiagnosticRequest buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.DiagnosticRequest result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.DiagnosticRequest buildPartial() { + com.openxc.BinaryMessages.DiagnosticRequest result = new com.openxc.BinaryMessages.DiagnosticRequest(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.bus_ = bus_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.messageId_ = messageId_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.mode_ = mode_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.pid_ = pid_; + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000010; + } + result.payload_ = payload_; + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000020; + } + result.multipleResponses_ = multipleResponses_; + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000040; + } + result.frequency_ = frequency_; + if (((from_bitField0_ & 0x00000080) == 0x00000080)) { + to_bitField0_ |= 0x00000080; + } + result.name_ = name_; + if (((from_bitField0_ & 0x00000100) == 0x00000100)) { + to_bitField0_ |= 0x00000100; + } + result.decodedType_ = decodedType_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.DiagnosticRequest) { + return mergeFrom((com.openxc.BinaryMessages.DiagnosticRequest)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.DiagnosticRequest other) { + if (other == com.openxc.BinaryMessages.DiagnosticRequest.getDefaultInstance()) return this; + if (other.hasBus()) { + setBus(other.getBus()); + } + if (other.hasMessageId()) { + setMessageId(other.getMessageId()); + } + if (other.hasMode()) { + setMode(other.getMode()); + } + if (other.hasPid()) { + setPid(other.getPid()); + } + if (other.hasPayload()) { + setPayload(other.getPayload()); + } + if (other.hasMultipleResponses()) { + setMultipleResponses(other.getMultipleResponses()); + } + if (other.hasFrequency()) { + setFrequency(other.getFrequency()); + } + if (other.hasName()) { + setName(other.getName()); + } + if (other.hasDecodedType()) { + setDecodedType(other.getDecodedType()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + bus_ = input.readInt32(); + break; + } + case 16: { + bitField0_ |= 0x00000002; + messageId_ = input.readUInt32(); + break; + } + case 24: { + bitField0_ |= 0x00000004; + mode_ = input.readUInt32(); + break; + } + case 32: { + bitField0_ |= 0x00000008; + pid_ = input.readUInt32(); + break; + } + case 42: { + bitField0_ |= 0x00000010; + payload_ = input.readBytes(); + break; + } + case 48: { + bitField0_ |= 0x00000020; + multipleResponses_ = input.readBool(); + break; + } + case 57: { + bitField0_ |= 0x00000040; + frequency_ = input.readDouble(); + break; + } + case 66: { + bitField0_ |= 0x00000080; + name_ = input.readBytes(); + break; + } + case 72: { + int rawValue = input.readEnum(); + com.openxc.BinaryMessages.DiagnosticRequest.DecodedType value = com.openxc.BinaryMessages.DiagnosticRequest.DecodedType.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(9, rawValue); + } else { + bitField0_ |= 0x00000100; + decodedType_ = value; + } + break; + } + } + } + } + + private int bitField0_; + + // optional int32 bus = 1; + private int bus_ ; + public boolean hasBus() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getBus() { + return bus_; + } + public Builder setBus(int value) { + bitField0_ |= 0x00000001; + bus_ = value; + onChanged(); + return this; + } + public Builder clearBus() { + bitField0_ = (bitField0_ & ~0x00000001); + bus_ = 0; + onChanged(); + return this; + } + + // optional uint32 message_id = 2; + private int messageId_ ; + public boolean hasMessageId() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public int getMessageId() { + return messageId_; + } + public Builder setMessageId(int value) { + bitField0_ |= 0x00000002; + messageId_ = value; + onChanged(); + return this; + } + public Builder clearMessageId() { + bitField0_ = (bitField0_ & ~0x00000002); + messageId_ = 0; + onChanged(); + return this; + } + + // optional uint32 mode = 3; + private int mode_ ; + public boolean hasMode() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public int getMode() { + return mode_; + } + public Builder setMode(int value) { + bitField0_ |= 0x00000004; + mode_ = value; + onChanged(); + return this; + } + public Builder clearMode() { + bitField0_ = (bitField0_ & ~0x00000004); + mode_ = 0; + onChanged(); + return this; + } + + // optional uint32 pid = 4; + private int pid_ ; + public boolean hasPid() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public int getPid() { + return pid_; + } + public Builder setPid(int value) { + bitField0_ |= 0x00000008; + pid_ = value; + onChanged(); + return this; + } + public Builder clearPid() { + bitField0_ = (bitField0_ & ~0x00000008); + pid_ = 0; + onChanged(); + return this; + } + + // optional bytes payload = 5; + private com.google.protobuf.ByteString payload_ = com.google.protobuf.ByteString.EMPTY; + public boolean hasPayload() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + public com.google.protobuf.ByteString getPayload() { + return payload_; + } + public Builder setPayload(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000010; + payload_ = value; + onChanged(); + return this; + } + public Builder clearPayload() { + bitField0_ = (bitField0_ & ~0x00000010); + payload_ = getDefaultInstance().getPayload(); + onChanged(); + return this; + } + + // optional bool multiple_responses = 6; + private boolean multipleResponses_ ; + public boolean hasMultipleResponses() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + public boolean getMultipleResponses() { + return multipleResponses_; + } + public Builder setMultipleResponses(boolean value) { + bitField0_ |= 0x00000020; + multipleResponses_ = value; + onChanged(); + return this; + } + public Builder clearMultipleResponses() { + bitField0_ = (bitField0_ & ~0x00000020); + multipleResponses_ = false; + onChanged(); + return this; + } + + // optional double frequency = 7; + private double frequency_ ; + public boolean hasFrequency() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + public double getFrequency() { + return frequency_; + } + public Builder setFrequency(double value) { + bitField0_ |= 0x00000040; + frequency_ = value; + onChanged(); + return this; + } + public Builder clearFrequency() { + bitField0_ = (bitField0_ & ~0x00000040); + frequency_ = 0D; + onChanged(); + return this; + } + + // optional string name = 8; + private java.lang.Object name_ = ""; + public boolean hasName() { + return ((bitField0_ & 0x00000080) == 0x00000080); + } + public String getName() { + java.lang.Object ref = name_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + name_ = s; + return s; + } else { + return (String) ref; + } + } + public Builder setName(String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000080; + name_ = value; + onChanged(); + return this; + } + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000080); + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + void setName(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000080; + name_ = value; + onChanged(); + } + + // optional .openxc.DiagnosticRequest.DecodedType decoded_type = 9; + private com.openxc.BinaryMessages.DiagnosticRequest.DecodedType decodedType_ = com.openxc.BinaryMessages.DiagnosticRequest.DecodedType.NONE; + public boolean hasDecodedType() { + return ((bitField0_ & 0x00000100) == 0x00000100); + } + public com.openxc.BinaryMessages.DiagnosticRequest.DecodedType getDecodedType() { + return decodedType_; + } + public Builder setDecodedType(com.openxc.BinaryMessages.DiagnosticRequest.DecodedType value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000100; + decodedType_ = value; + onChanged(); + return this; + } + public Builder clearDecodedType() { + bitField0_ = (bitField0_ & ~0x00000100); + decodedType_ = com.openxc.BinaryMessages.DiagnosticRequest.DecodedType.NONE; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.DiagnosticRequest) + } + + static { + defaultInstance = new DiagnosticRequest(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.DiagnosticRequest) + } + + public interface DiagnosticResponseOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional int32 bus = 1; + boolean hasBus(); + int getBus(); + + // optional uint32 message_id = 2; + boolean hasMessageId(); + int getMessageId(); + + // optional uint32 mode = 3; + boolean hasMode(); + int getMode(); + + // optional uint32 pid = 4; + boolean hasPid(); + int getPid(); + + // optional bool success = 5; + boolean hasSuccess(); + boolean getSuccess(); + + // optional uint32 negative_response_code = 6; + boolean hasNegativeResponseCode(); + int getNegativeResponseCode(); + + // optional bytes payload = 7; + boolean hasPayload(); + com.google.protobuf.ByteString getPayload(); + + // optional double value = 8; + boolean hasValue(); + double getValue(); + } + public static final class DiagnosticResponse extends + com.google.protobuf.GeneratedMessage + implements DiagnosticResponseOrBuilder { + // Use DiagnosticResponse.newBuilder() to construct. + private DiagnosticResponse(Builder builder) { + super(builder); + } + private DiagnosticResponse(boolean noInit) {} + + private static final DiagnosticResponse defaultInstance; + public static DiagnosticResponse getDefaultInstance() { + return defaultInstance; + } + + public DiagnosticResponse getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticResponse_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticResponse_fieldAccessorTable; + } + + private int bitField0_; + // optional int32 bus = 1; + public static final int BUS_FIELD_NUMBER = 1; + private int bus_; + public boolean hasBus() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getBus() { + return bus_; + } + + // optional uint32 message_id = 2; + public static final int MESSAGE_ID_FIELD_NUMBER = 2; + private int messageId_; + public boolean hasMessageId() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public int getMessageId() { + return messageId_; + } + + // optional uint32 mode = 3; + public static final int MODE_FIELD_NUMBER = 3; + private int mode_; + public boolean hasMode() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public int getMode() { + return mode_; + } + + // optional uint32 pid = 4; + public static final int PID_FIELD_NUMBER = 4; + private int pid_; + public boolean hasPid() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public int getPid() { + return pid_; + } + + // optional bool success = 5; + public static final int SUCCESS_FIELD_NUMBER = 5; + private boolean success_; + public boolean hasSuccess() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + public boolean getSuccess() { + return success_; + } + + // optional uint32 negative_response_code = 6; + public static final int NEGATIVE_RESPONSE_CODE_FIELD_NUMBER = 6; + private int negativeResponseCode_; + public boolean hasNegativeResponseCode() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + public int getNegativeResponseCode() { + return negativeResponseCode_; + } + + // optional bytes payload = 7; + public static final int PAYLOAD_FIELD_NUMBER = 7; + private com.google.protobuf.ByteString payload_; + public boolean hasPayload() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + public com.google.protobuf.ByteString getPayload() { + return payload_; + } + + // optional double value = 8; + public static final int VALUE_FIELD_NUMBER = 8; + private double value_; + public boolean hasValue() { + return ((bitField0_ & 0x00000080) == 0x00000080); + } + public double getValue() { + return value_; + } + + private void initFields() { + bus_ = 0; + messageId_ = 0; + mode_ = 0; + pid_ = 0; + success_ = false; + negativeResponseCode_ = 0; + payload_ = com.google.protobuf.ByteString.EMPTY; + value_ = 0D; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeInt32(1, bus_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeUInt32(2, messageId_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeUInt32(3, mode_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeUInt32(4, pid_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + output.writeBool(5, success_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + output.writeUInt32(6, negativeResponseCode_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + output.writeBytes(7, payload_); + } + if (((bitField0_ & 0x00000080) == 0x00000080)) { + output.writeDouble(8, value_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(1, bus_); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(2, messageId_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(3, mode_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(4, pid_); + } + if (((bitField0_ & 0x00000010) == 0x00000010)) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(5, success_); + } + if (((bitField0_ & 0x00000020) == 0x00000020)) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(6, negativeResponseCode_); + } + if (((bitField0_ & 0x00000040) == 0x00000040)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(7, payload_); + } + if (((bitField0_ & 0x00000080) == 0x00000080)) { + size += com.google.protobuf.CodedOutputStream + .computeDoubleSize(8, value_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.DiagnosticResponse parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticResponse parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticResponse parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticResponse parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticResponse parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticResponse parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticResponse parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.DiagnosticResponse parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.DiagnosticResponse parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.DiagnosticResponse parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.DiagnosticResponse prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.DiagnosticResponseOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticResponse_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_DiagnosticResponse_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.DiagnosticResponse.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + bus_ = 0; + bitField0_ = (bitField0_ & ~0x00000001); + messageId_ = 0; + bitField0_ = (bitField0_ & ~0x00000002); + mode_ = 0; + bitField0_ = (bitField0_ & ~0x00000004); + pid_ = 0; + bitField0_ = (bitField0_ & ~0x00000008); + success_ = false; + bitField0_ = (bitField0_ & ~0x00000010); + negativeResponseCode_ = 0; + bitField0_ = (bitField0_ & ~0x00000020); + payload_ = com.google.protobuf.ByteString.EMPTY; + bitField0_ = (bitField0_ & ~0x00000040); + value_ = 0D; + bitField0_ = (bitField0_ & ~0x00000080); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.DiagnosticResponse.getDescriptor(); + } + + public com.openxc.BinaryMessages.DiagnosticResponse getDefaultInstanceForType() { + return com.openxc.BinaryMessages.DiagnosticResponse.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.DiagnosticResponse build() { + com.openxc.BinaryMessages.DiagnosticResponse result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.DiagnosticResponse buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.DiagnosticResponse result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.DiagnosticResponse buildPartial() { + com.openxc.BinaryMessages.DiagnosticResponse result = new com.openxc.BinaryMessages.DiagnosticResponse(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.bus_ = bus_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.messageId_ = messageId_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.mode_ = mode_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.pid_ = pid_; + if (((from_bitField0_ & 0x00000010) == 0x00000010)) { + to_bitField0_ |= 0x00000010; + } + result.success_ = success_; + if (((from_bitField0_ & 0x00000020) == 0x00000020)) { + to_bitField0_ |= 0x00000020; + } + result.negativeResponseCode_ = negativeResponseCode_; + if (((from_bitField0_ & 0x00000040) == 0x00000040)) { + to_bitField0_ |= 0x00000040; + } + result.payload_ = payload_; + if (((from_bitField0_ & 0x00000080) == 0x00000080)) { + to_bitField0_ |= 0x00000080; + } + result.value_ = value_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.DiagnosticResponse) { + return mergeFrom((com.openxc.BinaryMessages.DiagnosticResponse)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.DiagnosticResponse other) { + if (other == com.openxc.BinaryMessages.DiagnosticResponse.getDefaultInstance()) return this; + if (other.hasBus()) { + setBus(other.getBus()); + } + if (other.hasMessageId()) { + setMessageId(other.getMessageId()); + } + if (other.hasMode()) { + setMode(other.getMode()); + } + if (other.hasPid()) { + setPid(other.getPid()); + } + if (other.hasSuccess()) { + setSuccess(other.getSuccess()); + } + if (other.hasNegativeResponseCode()) { + setNegativeResponseCode(other.getNegativeResponseCode()); + } + if (other.hasPayload()) { + setPayload(other.getPayload()); + } + if (other.hasValue()) { + setValue(other.getValue()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + bitField0_ |= 0x00000001; + bus_ = input.readInt32(); + break; + } + case 16: { + bitField0_ |= 0x00000002; + messageId_ = input.readUInt32(); + break; + } + case 24: { + bitField0_ |= 0x00000004; + mode_ = input.readUInt32(); + break; + } + case 32: { + bitField0_ |= 0x00000008; + pid_ = input.readUInt32(); + break; + } + case 40: { + bitField0_ |= 0x00000010; + success_ = input.readBool(); + break; + } + case 48: { + bitField0_ |= 0x00000020; + negativeResponseCode_ = input.readUInt32(); + break; + } + case 58: { + bitField0_ |= 0x00000040; + payload_ = input.readBytes(); + break; + } + case 65: { + bitField0_ |= 0x00000080; + value_ = input.readDouble(); + break; + } + } + } + } + + private int bitField0_; + + // optional int32 bus = 1; + private int bus_ ; + public boolean hasBus() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public int getBus() { + return bus_; + } + public Builder setBus(int value) { + bitField0_ |= 0x00000001; + bus_ = value; + onChanged(); + return this; + } + public Builder clearBus() { + bitField0_ = (bitField0_ & ~0x00000001); + bus_ = 0; + onChanged(); + return this; + } + + // optional uint32 message_id = 2; + private int messageId_ ; + public boolean hasMessageId() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public int getMessageId() { + return messageId_; + } + public Builder setMessageId(int value) { + bitField0_ |= 0x00000002; + messageId_ = value; + onChanged(); + return this; + } + public Builder clearMessageId() { + bitField0_ = (bitField0_ & ~0x00000002); + messageId_ = 0; + onChanged(); + return this; + } + + // optional uint32 mode = 3; + private int mode_ ; + public boolean hasMode() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public int getMode() { + return mode_; + } + public Builder setMode(int value) { + bitField0_ |= 0x00000004; + mode_ = value; + onChanged(); + return this; + } + public Builder clearMode() { + bitField0_ = (bitField0_ & ~0x00000004); + mode_ = 0; + onChanged(); + return this; + } + + // optional uint32 pid = 4; + private int pid_ ; + public boolean hasPid() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public int getPid() { + return pid_; + } + public Builder setPid(int value) { + bitField0_ |= 0x00000008; + pid_ = value; + onChanged(); + return this; + } + public Builder clearPid() { + bitField0_ = (bitField0_ & ~0x00000008); + pid_ = 0; + onChanged(); + return this; + } + + // optional bool success = 5; + private boolean success_ ; + public boolean hasSuccess() { + return ((bitField0_ & 0x00000010) == 0x00000010); + } + public boolean getSuccess() { + return success_; + } + public Builder setSuccess(boolean value) { + bitField0_ |= 0x00000010; + success_ = value; + onChanged(); + return this; + } + public Builder clearSuccess() { + bitField0_ = (bitField0_ & ~0x00000010); + success_ = false; + onChanged(); + return this; + } + + // optional uint32 negative_response_code = 6; + private int negativeResponseCode_ ; + public boolean hasNegativeResponseCode() { + return ((bitField0_ & 0x00000020) == 0x00000020); + } + public int getNegativeResponseCode() { + return negativeResponseCode_; + } + public Builder setNegativeResponseCode(int value) { + bitField0_ |= 0x00000020; + negativeResponseCode_ = value; + onChanged(); + return this; + } + public Builder clearNegativeResponseCode() { + bitField0_ = (bitField0_ & ~0x00000020); + negativeResponseCode_ = 0; + onChanged(); + return this; + } + + // optional bytes payload = 7; + private com.google.protobuf.ByteString payload_ = com.google.protobuf.ByteString.EMPTY; + public boolean hasPayload() { + return ((bitField0_ & 0x00000040) == 0x00000040); + } + public com.google.protobuf.ByteString getPayload() { + return payload_; + } + public Builder setPayload(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000040; + payload_ = value; + onChanged(); + return this; + } + public Builder clearPayload() { + bitField0_ = (bitField0_ & ~0x00000040); + payload_ = getDefaultInstance().getPayload(); + onChanged(); + return this; + } + + // optional double value = 8; + private double value_ ; + public boolean hasValue() { + return ((bitField0_ & 0x00000080) == 0x00000080); + } + public double getValue() { + return value_; + } + public Builder setValue(double value) { + bitField0_ |= 0x00000080; + value_ = value; + onChanged(); + return this; + } + public Builder clearValue() { + bitField0_ = (bitField0_ & ~0x00000080); + value_ = 0D; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.DiagnosticResponse) + } + + static { + defaultInstance = new DiagnosticResponse(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.DiagnosticResponse) + } + + public interface DynamicFieldOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional .openxc.DynamicField.Type type = 1; + boolean hasType(); + com.openxc.BinaryMessages.DynamicField.Type getType(); + + // optional string string_value = 2; + boolean hasStringValue(); + String getStringValue(); + + // optional double numeric_value = 3; + boolean hasNumericValue(); + double getNumericValue(); + + // optional bool boolean_value = 4; + boolean hasBooleanValue(); + boolean getBooleanValue(); + } + public static final class DynamicField extends + com.google.protobuf.GeneratedMessage + implements DynamicFieldOrBuilder { + // Use DynamicField.newBuilder() to construct. + private DynamicField(Builder builder) { + super(builder); + } + private DynamicField(boolean noInit) {} + + private static final DynamicField defaultInstance; + public static DynamicField getDefaultInstance() { + return defaultInstance; + } + + public DynamicField getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_DynamicField_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_DynamicField_fieldAccessorTable; + } + + public enum Type + implements com.google.protobuf.ProtocolMessageEnum { + STRING(0, 1), + NUM(1, 2), + BOOL(2, 3), + ; + + public static final int STRING_VALUE = 1; + public static final int NUM_VALUE = 2; + public static final int BOOL_VALUE = 3; + + + public final int getNumber() { return value; } + + public static Type valueOf(int value) { + switch (value) { + case 1: return STRING; + case 2: return NUM; + case 3: return BOOL; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static com.google.protobuf.Internal.EnumLiteMap + internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public Type findValueByNumber(int number) { + return Type.valueOf(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(index); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return com.openxc.BinaryMessages.DynamicField.getDescriptor().getEnumTypes().get(0); + } + + private static final Type[] VALUES = { + STRING, NUM, BOOL, + }; + + public static Type valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + return VALUES[desc.getIndex()]; + } + + private final int index; + private final int value; + + private Type(int index, int value) { + this.index = index; + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:openxc.DynamicField.Type) + } + + private int bitField0_; + // optional .openxc.DynamicField.Type type = 1; + public static final int TYPE_FIELD_NUMBER = 1; + private com.openxc.BinaryMessages.DynamicField.Type type_; + public boolean hasType() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.DynamicField.Type getType() { + return type_; + } + + // optional string string_value = 2; + public static final int STRING_VALUE_FIELD_NUMBER = 2; + private java.lang.Object stringValue_; + public boolean hasStringValue() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getStringValue() { + java.lang.Object ref = stringValue_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + stringValue_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getStringValueBytes() { + java.lang.Object ref = stringValue_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + stringValue_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + // optional double numeric_value = 3; + public static final int NUMERIC_VALUE_FIELD_NUMBER = 3; + private double numericValue_; + public boolean hasNumericValue() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public double getNumericValue() { + return numericValue_; + } + + // optional bool boolean_value = 4; + public static final int BOOLEAN_VALUE_FIELD_NUMBER = 4; + private boolean booleanValue_; + public boolean hasBooleanValue() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public boolean getBooleanValue() { + return booleanValue_; + } + + private void initFields() { + type_ = com.openxc.BinaryMessages.DynamicField.Type.STRING; + stringValue_ = ""; + numericValue_ = 0D; + booleanValue_ = false; + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeEnum(1, type_.getNumber()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeBytes(2, getStringValueBytes()); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeDouble(3, numericValue_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + output.writeBool(4, booleanValue_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(1, type_.getNumber()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(2, getStringValueBytes()); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeDoubleSize(3, numericValue_); + } + if (((bitField0_ & 0x00000008) == 0x00000008)) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(4, booleanValue_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.DynamicField parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.DynamicField parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DynamicField parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.DynamicField parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DynamicField parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.DynamicField parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.DynamicField parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.DynamicField parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.DynamicField parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.DynamicField parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.DynamicField prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.DynamicFieldOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_DynamicField_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_DynamicField_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.DynamicField.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + type_ = com.openxc.BinaryMessages.DynamicField.Type.STRING; + bitField0_ = (bitField0_ & ~0x00000001); + stringValue_ = ""; + bitField0_ = (bitField0_ & ~0x00000002); + numericValue_ = 0D; + bitField0_ = (bitField0_ & ~0x00000004); + booleanValue_ = false; + bitField0_ = (bitField0_ & ~0x00000008); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.DynamicField.getDescriptor(); + } + + public com.openxc.BinaryMessages.DynamicField getDefaultInstanceForType() { + return com.openxc.BinaryMessages.DynamicField.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.DynamicField build() { + com.openxc.BinaryMessages.DynamicField result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.DynamicField buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.DynamicField result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.DynamicField buildPartial() { + com.openxc.BinaryMessages.DynamicField result = new com.openxc.BinaryMessages.DynamicField(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.type_ = type_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + result.stringValue_ = stringValue_; + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + result.numericValue_ = numericValue_; + if (((from_bitField0_ & 0x00000008) == 0x00000008)) { + to_bitField0_ |= 0x00000008; + } + result.booleanValue_ = booleanValue_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.DynamicField) { + return mergeFrom((com.openxc.BinaryMessages.DynamicField)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.DynamicField other) { + if (other == com.openxc.BinaryMessages.DynamicField.getDefaultInstance()) return this; + if (other.hasType()) { + setType(other.getType()); + } + if (other.hasStringValue()) { + setStringValue(other.getStringValue()); + } + if (other.hasNumericValue()) { + setNumericValue(other.getNumericValue()); + } + if (other.hasBooleanValue()) { + setBooleanValue(other.getBooleanValue()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 8: { + int rawValue = input.readEnum(); + com.openxc.BinaryMessages.DynamicField.Type value = com.openxc.BinaryMessages.DynamicField.Type.valueOf(rawValue); + if (value == null) { + unknownFields.mergeVarintField(1, rawValue); + } else { + bitField0_ |= 0x00000001; + type_ = value; + } + break; + } + case 18: { + bitField0_ |= 0x00000002; + stringValue_ = input.readBytes(); + break; + } + case 25: { + bitField0_ |= 0x00000004; + numericValue_ = input.readDouble(); + break; + } + case 32: { + bitField0_ |= 0x00000008; + booleanValue_ = input.readBool(); + break; + } + } + } + } + + private int bitField0_; + + // optional .openxc.DynamicField.Type type = 1; + private com.openxc.BinaryMessages.DynamicField.Type type_ = com.openxc.BinaryMessages.DynamicField.Type.STRING; + public boolean hasType() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public com.openxc.BinaryMessages.DynamicField.Type getType() { + return type_; + } + public Builder setType(com.openxc.BinaryMessages.DynamicField.Type value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + type_ = value; + onChanged(); + return this; + } + public Builder clearType() { + bitField0_ = (bitField0_ & ~0x00000001); + type_ = com.openxc.BinaryMessages.DynamicField.Type.STRING; + onChanged(); + return this; + } + + // optional string string_value = 2; + private java.lang.Object stringValue_ = ""; + public boolean hasStringValue() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public String getStringValue() { + java.lang.Object ref = stringValue_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + stringValue_ = s; + return s; + } else { + return (String) ref; + } + } + public Builder setStringValue(String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000002; + stringValue_ = value; + onChanged(); + return this; + } + public Builder clearStringValue() { + bitField0_ = (bitField0_ & ~0x00000002); + stringValue_ = getDefaultInstance().getStringValue(); + onChanged(); + return this; + } + void setStringValue(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000002; + stringValue_ = value; + onChanged(); + } + + // optional double numeric_value = 3; + private double numericValue_ ; + public boolean hasNumericValue() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public double getNumericValue() { + return numericValue_; + } + public Builder setNumericValue(double value) { + bitField0_ |= 0x00000004; + numericValue_ = value; + onChanged(); + return this; + } + public Builder clearNumericValue() { + bitField0_ = (bitField0_ & ~0x00000004); + numericValue_ = 0D; + onChanged(); + return this; + } + + // optional bool boolean_value = 4; + private boolean booleanValue_ ; + public boolean hasBooleanValue() { + return ((bitField0_ & 0x00000008) == 0x00000008); + } + public boolean getBooleanValue() { + return booleanValue_; + } + public Builder setBooleanValue(boolean value) { + bitField0_ |= 0x00000008; + booleanValue_ = value; + onChanged(); + return this; + } + public Builder clearBooleanValue() { + bitField0_ = (bitField0_ & ~0x00000008); + booleanValue_ = false; + onChanged(); + return this; + } + + // @@protoc_insertion_point(builder_scope:openxc.DynamicField) + } + + static { + defaultInstance = new DynamicField(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.DynamicField) + } + + public interface SimpleMessageOrBuilder + extends com.google.protobuf.MessageOrBuilder { + + // optional string name = 1; + boolean hasName(); + String getName(); + + // optional .openxc.DynamicField value = 2; + boolean hasValue(); + com.openxc.BinaryMessages.DynamicField getValue(); + com.openxc.BinaryMessages.DynamicFieldOrBuilder getValueOrBuilder(); + + // optional .openxc.DynamicField event = 3; + boolean hasEvent(); + com.openxc.BinaryMessages.DynamicField getEvent(); + com.openxc.BinaryMessages.DynamicFieldOrBuilder getEventOrBuilder(); + } + public static final class SimpleMessage extends + com.google.protobuf.GeneratedMessage + implements SimpleMessageOrBuilder { + // Use SimpleMessage.newBuilder() to construct. + private SimpleMessage(Builder builder) { + super(builder); + } + private SimpleMessage(boolean noInit) {} + + private static final SimpleMessage defaultInstance; + public static SimpleMessage getDefaultInstance() { + return defaultInstance; + } + + public SimpleMessage getDefaultInstanceForType() { + return defaultInstance; + } + + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_SimpleMessage_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_SimpleMessage_fieldAccessorTable; + } + + private int bitField0_; + // optional string name = 1; + public static final int NAME_FIELD_NUMBER = 1; + private java.lang.Object name_; + public boolean hasName() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getName() { + java.lang.Object ref = name_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + if (com.google.protobuf.Internal.isValidUtf8(bs)) { + name_ = s; + } + return s; + } + } + private com.google.protobuf.ByteString getNameBytes() { + java.lang.Object ref = name_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((String) ref); + name_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + // optional .openxc.DynamicField value = 2; + public static final int VALUE_FIELD_NUMBER = 2; + private com.openxc.BinaryMessages.DynamicField value_; + public boolean hasValue() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.DynamicField getValue() { + return value_; + } + public com.openxc.BinaryMessages.DynamicFieldOrBuilder getValueOrBuilder() { + return value_; + } + + // optional .openxc.DynamicField event = 3; + public static final int EVENT_FIELD_NUMBER = 3; + private com.openxc.BinaryMessages.DynamicField event_; + public boolean hasEvent() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.openxc.BinaryMessages.DynamicField getEvent() { + return event_; + } + public com.openxc.BinaryMessages.DynamicFieldOrBuilder getEventOrBuilder() { + return event_; + } + + private void initFields() { + name_ = ""; + value_ = com.openxc.BinaryMessages.DynamicField.getDefaultInstance(); + event_ = com.openxc.BinaryMessages.DynamicField.getDefaultInstance(); + } + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized != -1) return isInitialized == 1; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + getSerializedSize(); + if (((bitField0_ & 0x00000001) == 0x00000001)) { + output.writeBytes(1, getNameBytes()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + output.writeMessage(2, value_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + output.writeMessage(3, event_); + } + getUnknownFields().writeTo(output); + } + + private int memoizedSerializedSize = -1; + public int getSerializedSize() { + int size = memoizedSerializedSize; + if (size != -1) return size; + + size = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(1, getNameBytes()); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, value_); + } + if (((bitField0_ & 0x00000004) == 0x00000004)) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, event_); + } + size += getUnknownFields().getSerializedSize(); + memoizedSerializedSize = size; + return size; + } + + private static final long serialVersionUID = 0L; + @java.lang.Override + protected java.lang.Object writeReplace() + throws java.io.ObjectStreamException { + return super.writeReplace(); + } + + public static com.openxc.BinaryMessages.SimpleMessage parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.SimpleMessage parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.SimpleMessage parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data).buildParsed(); + } + public static com.openxc.BinaryMessages.SimpleMessage parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return newBuilder().mergeFrom(data, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.SimpleMessage parseFrom(java.io.InputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.SimpleMessage parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + public static com.openxc.BinaryMessages.SimpleMessage parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.SimpleMessage parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + Builder builder = newBuilder(); + if (builder.mergeDelimitedFrom(input, extensionRegistry)) { + return builder.buildParsed(); + } else { + return null; + } + } + public static com.openxc.BinaryMessages.SimpleMessage parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return newBuilder().mergeFrom(input).buildParsed(); + } + public static com.openxc.BinaryMessages.SimpleMessage parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return newBuilder().mergeFrom(input, extensionRegistry) + .buildParsed(); + } + + public static Builder newBuilder() { return Builder.create(); } + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder(com.openxc.BinaryMessages.SimpleMessage prototype) { + return newBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { return newBuilder(this); } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessage.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + public static final class Builder extends + com.google.protobuf.GeneratedMessage.Builder + implements com.openxc.BinaryMessages.SimpleMessageOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return com.openxc.BinaryMessages.internal_static_openxc_SimpleMessage_descriptor; + } + + protected com.google.protobuf.GeneratedMessage.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.openxc.BinaryMessages.internal_static_openxc_SimpleMessage_fieldAccessorTable; + } + + // Construct using com.openxc.BinaryMessages.SimpleMessage.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { + getValueFieldBuilder(); + getEventFieldBuilder(); + } + } + private static Builder create() { + return new Builder(); + } + + public Builder clear() { + super.clear(); + name_ = ""; + bitField0_ = (bitField0_ & ~0x00000001); + if (valueBuilder_ == null) { + value_ = com.openxc.BinaryMessages.DynamicField.getDefaultInstance(); + } else { + valueBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + if (eventBuilder_ == null) { + event_ = com.openxc.BinaryMessages.DynamicField.getDefaultInstance(); + } else { + eventBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + + public Builder clone() { + return create().mergeFrom(buildPartial()); + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return com.openxc.BinaryMessages.SimpleMessage.getDescriptor(); + } + + public com.openxc.BinaryMessages.SimpleMessage getDefaultInstanceForType() { + return com.openxc.BinaryMessages.SimpleMessage.getDefaultInstance(); + } + + public com.openxc.BinaryMessages.SimpleMessage build() { + com.openxc.BinaryMessages.SimpleMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + private com.openxc.BinaryMessages.SimpleMessage buildParsed() + throws com.google.protobuf.InvalidProtocolBufferException { + com.openxc.BinaryMessages.SimpleMessage result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException( + result).asInvalidProtocolBufferException(); + } + return result; + } + + public com.openxc.BinaryMessages.SimpleMessage buildPartial() { + com.openxc.BinaryMessages.SimpleMessage result = new com.openxc.BinaryMessages.SimpleMessage(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((from_bitField0_ & 0x00000001) == 0x00000001)) { + to_bitField0_ |= 0x00000001; + } + result.name_ = name_; + if (((from_bitField0_ & 0x00000002) == 0x00000002)) { + to_bitField0_ |= 0x00000002; + } + if (valueBuilder_ == null) { + result.value_ = value_; + } else { + result.value_ = valueBuilder_.build(); + } + if (((from_bitField0_ & 0x00000004) == 0x00000004)) { + to_bitField0_ |= 0x00000004; + } + if (eventBuilder_ == null) { + result.event_ = event_; + } else { + result.event_ = eventBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.openxc.BinaryMessages.SimpleMessage) { + return mergeFrom((com.openxc.BinaryMessages.SimpleMessage)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.openxc.BinaryMessages.SimpleMessage other) { + if (other == com.openxc.BinaryMessages.SimpleMessage.getDefaultInstance()) return this; + if (other.hasName()) { + setName(other.getName()); + } + if (other.hasValue()) { + mergeValue(other.getValue()); + } + if (other.hasEvent()) { + mergeEvent(other.getEvent()); + } + this.mergeUnknownFields(other.getUnknownFields()); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder( + this.getUnknownFields()); + while (true) { + int tag = input.readTag(); + switch (tag) { + case 0: + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + default: { + if (!parseUnknownField(input, unknownFields, + extensionRegistry, tag)) { + this.setUnknownFields(unknownFields.build()); + onChanged(); + return this; + } + break; + } + case 10: { + bitField0_ |= 0x00000001; + name_ = input.readBytes(); + break; + } + case 18: { + com.openxc.BinaryMessages.DynamicField.Builder subBuilder = com.openxc.BinaryMessages.DynamicField.newBuilder(); + if (hasValue()) { + subBuilder.mergeFrom(getValue()); + } + input.readMessage(subBuilder, extensionRegistry); + setValue(subBuilder.buildPartial()); + break; + } + case 26: { + com.openxc.BinaryMessages.DynamicField.Builder subBuilder = com.openxc.BinaryMessages.DynamicField.newBuilder(); + if (hasEvent()) { + subBuilder.mergeFrom(getEvent()); + } + input.readMessage(subBuilder, extensionRegistry); + setEvent(subBuilder.buildPartial()); + break; + } + } + } + } + + private int bitField0_; + + // optional string name = 1; + private java.lang.Object name_ = ""; + public boolean hasName() { + return ((bitField0_ & 0x00000001) == 0x00000001); + } + public String getName() { + java.lang.Object ref = name_; + if (!(ref instanceof String)) { + String s = ((com.google.protobuf.ByteString) ref).toStringUtf8(); + name_ = s; + return s; + } else { + return (String) ref; + } + } + public Builder setName(String value) { + if (value == null) { + throw new NullPointerException(); + } + bitField0_ |= 0x00000001; + name_ = value; + onChanged(); + return this; + } + public Builder clearName() { + bitField0_ = (bitField0_ & ~0x00000001); + name_ = getDefaultInstance().getName(); + onChanged(); + return this; + } + void setName(com.google.protobuf.ByteString value) { + bitField0_ |= 0x00000001; + name_ = value; + onChanged(); + } + + // optional .openxc.DynamicField value = 2; + private com.openxc.BinaryMessages.DynamicField value_ = com.openxc.BinaryMessages.DynamicField.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DynamicField, com.openxc.BinaryMessages.DynamicField.Builder, com.openxc.BinaryMessages.DynamicFieldOrBuilder> valueBuilder_; + public boolean hasValue() { + return ((bitField0_ & 0x00000002) == 0x00000002); + } + public com.openxc.BinaryMessages.DynamicField getValue() { + if (valueBuilder_ == null) { + return value_; + } else { + return valueBuilder_.getMessage(); + } + } + public Builder setValue(com.openxc.BinaryMessages.DynamicField value) { + if (valueBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + value_ = value; + onChanged(); + } else { + valueBuilder_.setMessage(value); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder setValue( + com.openxc.BinaryMessages.DynamicField.Builder builderForValue) { + if (valueBuilder_ == null) { + value_ = builderForValue.build(); + onChanged(); + } else { + valueBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder mergeValue(com.openxc.BinaryMessages.DynamicField value) { + if (valueBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002) && + value_ != com.openxc.BinaryMessages.DynamicField.getDefaultInstance()) { + value_ = + com.openxc.BinaryMessages.DynamicField.newBuilder(value_).mergeFrom(value).buildPartial(); + } else { + value_ = value; + } + onChanged(); + } else { + valueBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000002; + return this; + } + public Builder clearValue() { + if (valueBuilder_ == null) { + value_ = com.openxc.BinaryMessages.DynamicField.getDefaultInstance(); + onChanged(); + } else { + valueBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000002); + return this; + } + public com.openxc.BinaryMessages.DynamicField.Builder getValueBuilder() { + bitField0_ |= 0x00000002; + onChanged(); + return getValueFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.DynamicFieldOrBuilder getValueOrBuilder() { + if (valueBuilder_ != null) { + return valueBuilder_.getMessageOrBuilder(); + } else { + return value_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DynamicField, com.openxc.BinaryMessages.DynamicField.Builder, com.openxc.BinaryMessages.DynamicFieldOrBuilder> + getValueFieldBuilder() { + if (valueBuilder_ == null) { + valueBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DynamicField, com.openxc.BinaryMessages.DynamicField.Builder, com.openxc.BinaryMessages.DynamicFieldOrBuilder>( + value_, + getParentForChildren(), + isClean()); + value_ = null; + } + return valueBuilder_; + } + + // optional .openxc.DynamicField event = 3; + private com.openxc.BinaryMessages.DynamicField event_ = com.openxc.BinaryMessages.DynamicField.getDefaultInstance(); + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DynamicField, com.openxc.BinaryMessages.DynamicField.Builder, com.openxc.BinaryMessages.DynamicFieldOrBuilder> eventBuilder_; + public boolean hasEvent() { + return ((bitField0_ & 0x00000004) == 0x00000004); + } + public com.openxc.BinaryMessages.DynamicField getEvent() { + if (eventBuilder_ == null) { + return event_; + } else { + return eventBuilder_.getMessage(); + } + } + public Builder setEvent(com.openxc.BinaryMessages.DynamicField value) { + if (eventBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + event_ = value; + onChanged(); + } else { + eventBuilder_.setMessage(value); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder setEvent( + com.openxc.BinaryMessages.DynamicField.Builder builderForValue) { + if (eventBuilder_ == null) { + event_ = builderForValue.build(); + onChanged(); + } else { + eventBuilder_.setMessage(builderForValue.build()); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder mergeEvent(com.openxc.BinaryMessages.DynamicField value) { + if (eventBuilder_ == null) { + if (((bitField0_ & 0x00000004) == 0x00000004) && + event_ != com.openxc.BinaryMessages.DynamicField.getDefaultInstance()) { + event_ = + com.openxc.BinaryMessages.DynamicField.newBuilder(event_).mergeFrom(value).buildPartial(); + } else { + event_ = value; + } + onChanged(); + } else { + eventBuilder_.mergeFrom(value); + } + bitField0_ |= 0x00000004; + return this; + } + public Builder clearEvent() { + if (eventBuilder_ == null) { + event_ = com.openxc.BinaryMessages.DynamicField.getDefaultInstance(); + onChanged(); + } else { + eventBuilder_.clear(); + } + bitField0_ = (bitField0_ & ~0x00000004); + return this; + } + public com.openxc.BinaryMessages.DynamicField.Builder getEventBuilder() { + bitField0_ |= 0x00000004; + onChanged(); + return getEventFieldBuilder().getBuilder(); + } + public com.openxc.BinaryMessages.DynamicFieldOrBuilder getEventOrBuilder() { + if (eventBuilder_ != null) { + return eventBuilder_.getMessageOrBuilder(); + } else { + return event_; + } + } + private com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DynamicField, com.openxc.BinaryMessages.DynamicField.Builder, com.openxc.BinaryMessages.DynamicFieldOrBuilder> + getEventFieldBuilder() { + if (eventBuilder_ == null) { + eventBuilder_ = new com.google.protobuf.SingleFieldBuilder< + com.openxc.BinaryMessages.DynamicField, com.openxc.BinaryMessages.DynamicField.Builder, com.openxc.BinaryMessages.DynamicFieldOrBuilder>( + event_, + getParentForChildren(), + isClean()); + event_ = null; + } + return eventBuilder_; + } + + // @@protoc_insertion_point(builder_scope:openxc.SimpleMessage) + } + + static { + defaultInstance = new SimpleMessage(true); + defaultInstance.initFields(); + } + + // @@protoc_insertion_point(class_scope:openxc.SimpleMessage) + } + + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_VehicleMessage_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_VehicleMessage_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_CanMessage_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_CanMessage_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_ControlCommand_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_ControlCommand_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_DiagnosticControlCommand_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_DiagnosticControlCommand_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_PassthroughModeControlCommand_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_PassthroughModeControlCommand_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_AcceptanceFilterBypassCommand_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_AcceptanceFilterBypassCommand_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_PayloadFormatCommand_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_PayloadFormatCommand_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_PredefinedObd2RequestsCommand_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_PredefinedObd2RequestsCommand_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_NetworkOperatorSettings_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_NetworkOperatorSettings_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_NetworkOperatorSettings_NetworkDescriptor_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_NetworkOperatorSettings_NetworkDescriptor_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_NetworkDataSettings_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_NetworkDataSettings_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_ServerConnectSettings_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_ServerConnectSettings_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_ModemConfigurationCommand_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_ModemConfigurationCommand_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_RTCConfigurationCommand_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_RTCConfigurationCommand_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_CommandResponse_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_CommandResponse_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_DiagnosticRequest_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_DiagnosticRequest_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_DiagnosticResponse_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_DiagnosticResponse_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_DynamicField_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_DynamicField_fieldAccessorTable; + private static com.google.protobuf.Descriptors.Descriptor + internal_static_openxc_SimpleMessage_descriptor; + private static + com.google.protobuf.GeneratedMessage.FieldAccessorTable + internal_static_openxc_SimpleMessage_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + java.lang.String[] descriptorData = { + "\n\014openxc.proto\022\006openxc\"\233\003\n\016VehicleMessag" + + "e\022)\n\004type\030\001 \001(\0162\033.openxc.VehicleMessage." + + "Type\022\'\n\013can_message\030\002 \001(\0132\022.openxc.CanMe" + + "ssage\022-\n\016simple_message\030\003 \001(\0132\025.openxc.S" + + "impleMessage\0227\n\023diagnostic_response\030\004 \001(" + + "\0132\032.openxc.DiagnosticResponse\022/\n\017control" + + "_command\030\005 \001(\0132\026.openxc.ControlCommand\0221" + + "\n\020command_response\030\006 \001(\0132\027.openxc.Comman" + + "dResponse\022\021\n\ttimestamp\030\007 \001(\004\"V\n\004Type\022\007\n\003" + + "CAN\020\001\022\n\n\006SIMPLE\020\002\022\016\n\nDIAGNOSTIC\020\003\022\023\n\017CON", + "TROL_COMMAND\020\004\022\024\n\020COMMAND_RESPONSE\020\005\"\224\001\n" + + "\nCanMessage\022\013\n\003bus\030\001 \001(\005\022\n\n\002id\030\002 \001(\r\022\014\n\004" + + "data\030\003 \001(\014\0224\n\014frame_format\030\004 \001(\0162\036.openx" + + "c.CanMessage.FrameFormat\")\n\013FrameFormat\022" + + "\014\n\010STANDARD\020\001\022\014\n\010EXTENDED\020\002\"\227\006\n\016ControlC" + + "ommand\022)\n\004type\030\001 \001(\0162\033.openxc.ControlCom" + + "mand.Type\022<\n\022diagnostic_request\030\002 \001(\0132 ." + + "openxc.DiagnosticControlCommand\022G\n\030passt" + + "hrough_mode_request\030\003 \001(\0132%.openxc.Passt" + + "hroughModeControlCommand\022O\n acceptance_f", + "ilter_bypass_command\030\004 \001(\0132%.openxc.Acce" + + "ptanceFilterBypassCommand\022<\n\026payload_for" + + "mat_command\030\005 \001(\0132\034.openxc.PayloadFormat" + + "Command\022O\n predefined_obd2_requests_comm" + + "and\030\006 \001(\0132%.openxc.PredefinedObd2Request" + + "sCommand\022F\n\033modem_configuration_command\030" + + "\007 \001(\0132!.openxc.ModemConfigurationCommand" + + "\022B\n\031rtc_configuration_command\030\010 \001(\0132\037.op" + + "enxc.RTCConfigurationCommand\"\346\001\n\004Type\022\013\n" + + "\007VERSION\020\001\022\r\n\tDEVICE_ID\020\002\022\016\n\nDIAGNOSTIC\020", + "\003\022\017\n\013PASSTHROUGH\020\004\022\034\n\030ACCEPTANCE_FILTER_" + + "BYPASS\020\005\022\022\n\016PAYLOAD_FORMAT\020\006\022\034\n\030PREDEFIN" + + "ED_OBD2_REQUESTS\020\007\022\027\n\023MODEM_CONFIGURATIO" + + "N\020\010\022\025\n\021RTC_CONFIGURATION\020\t\022\023\n\017SD_MOUNT_S" + + "TATUS\020\n\022\014\n\010PLATFORM\020\013\"\236\001\n\030DiagnosticCont" + + "rolCommand\022*\n\007request\030\001 \001(\0132\031.openxc.Dia" + + "gnosticRequest\0227\n\006action\030\002 \001(\0162\'.openxc." + + "DiagnosticControlCommand.Action\"\035\n\006Actio" + + "n\022\007\n\003ADD\020\001\022\n\n\006CANCEL\020\002\"=\n\035PassthroughMod" + + "eControlCommand\022\013\n\003bus\030\001 \001(\005\022\017\n\007enabled\030", + "\002 \001(\010\"<\n\035AcceptanceFilterBypassCommand\022\013" + + "\n\003bus\030\001 \001(\005\022\016\n\006bypass\030\002 \001(\010\"\214\001\n\024PayloadF" + + "ormatCommand\022:\n\006format\030\001 \001(\0162*.openxc.Pa" + + "yloadFormatCommand.PayloadFormat\"8\n\rPayl" + + "oadFormat\022\010\n\004JSON\020\001\022\014\n\010PROTOBUF\020\002\022\017\n\013MES" + + "SAGEPACK\020\003\"0\n\035PredefinedObd2RequestsComm" + + "and\022\017\n\007enabled\030\001 \001(\010\"\321\003\n\027NetworkOperator" + + "Settings\022\030\n\020allowDataRoaming\030\001 \001(\010\022N\n\022op" + + "eratorSelectMode\030\002 \001(\01622.openxc.NetworkO" + + "peratorSettings.OperatorSelectMode\022L\n\021ne", + "tworkDescriptor\030\003 \001(\01321.openxc.NetworkOp" + + "eratorSettings.NetworkDescriptor\032\230\001\n\021Net" + + "workDescriptor\022\014\n\004PLMN\030\001 \001(\r\022R\n\013networkT" + + "ype\030\002 \001(\0162=.openxc.NetworkOperatorSettin" + + "gs.NetworkDescriptor.NetworkType\"!\n\013Netw" + + "orkType\022\007\n\003GSM\020\000\022\t\n\005UTRAN\020\002\"c\n\022OperatorS" + + "electMode\022\r\n\tAUTOMATIC\020\000\022\n\n\006MANUAL\020\001\022\016\n\n" + + "DEREGISTER\020\002\022\014\n\010SET_ONLY\020\003\022\024\n\020MANUAL_AUT" + + "OMATIC\020\004\"\"\n\023NetworkDataSettings\022\013\n\003APN\030\001" + + " \001(\t\"3\n\025ServerConnectSettings\022\014\n\004host\030\001 ", + "\001(\t\022\014\n\004port\030\002 \001(\r\"\325\001\n\031ModemConfiguration" + + "Command\022@\n\027networkOperatorSettings\030\001 \001(\013" + + "2\037.openxc.NetworkOperatorSettings\0228\n\023net" + + "workDataSettings\030\002 \001(\0132\033.openxc.NetworkD" + + "ataSettings\022<\n\025serverConnectSettings\030\003 \001" + + "(\0132\035.openxc.ServerConnectSettings\",\n\027RTC" + + "ConfigurationCommand\022\021\n\tunix_time\030\001 \001(\r\"" + + "]\n\017CommandResponse\022)\n\004type\030\001 \001(\0162\033.openx" + + "c.ControlCommand.Type\022\017\n\007message\030\002 \001(\t\022\016" + + "\n\006status\030\003 \001(\010\"\375\001\n\021DiagnosticRequest\022\013\n\003", + "bus\030\001 \001(\005\022\022\n\nmessage_id\030\002 \001(\r\022\014\n\004mode\030\003 " + + "\001(\r\022\013\n\003pid\030\004 \001(\r\022\017\n\007payload\030\005 \001(\014\022\032\n\022mul" + + "tiple_responses\030\006 \001(\010\022\021\n\tfrequency\030\007 \001(\001" + + "\022\014\n\004name\030\010 \001(\t\022;\n\014decoded_type\030\t \001(\0162%.o" + + "penxc.DiagnosticRequest.DecodedType\"!\n\013D" + + "ecodedType\022\010\n\004NONE\020\001\022\010\n\004OBD2\020\002\"\241\001\n\022Diagn" + + "osticResponse\022\013\n\003bus\030\001 \001(\005\022\022\n\nmessage_id" + + "\030\002 \001(\r\022\014\n\004mode\030\003 \001(\r\022\013\n\003pid\030\004 \001(\r\022\017\n\007suc" + + "cess\030\005 \001(\010\022\036\n\026negative_response_code\030\006 \001" + + "(\r\022\017\n\007payload\030\007 \001(\014\022\r\n\005value\030\010 \001(\001\"\242\001\n\014D", + "ynamicField\022\'\n\004type\030\001 \001(\0162\031.openxc.Dynam" + + "icField.Type\022\024\n\014string_value\030\002 \001(\t\022\025\n\rnu" + + "meric_value\030\003 \001(\001\022\025\n\rboolean_value\030\004 \001(\010" + + "\"%\n\004Type\022\n\n\006STRING\020\001\022\007\n\003NUM\020\002\022\010\n\004BOOL\020\003\"" + + "g\n\rSimpleMessage\022\014\n\004name\030\001 \001(\t\022#\n\005value\030" + + "\002 \001(\0132\024.openxc.DynamicField\022#\n\005event\030\003 \001" + + "(\0132\024.openxc.DynamicFieldB\034\n\ncom.openxcB\016" + + "BinaryMessages" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + internal_static_openxc_VehicleMessage_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_openxc_VehicleMessage_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_VehicleMessage_descriptor, + new java.lang.String[] { "Type", "CanMessage", "SimpleMessage", "DiagnosticResponse", "ControlCommand", "CommandResponse", "Timestamp", }, + com.openxc.BinaryMessages.VehicleMessage.class, + com.openxc.BinaryMessages.VehicleMessage.Builder.class); + internal_static_openxc_CanMessage_descriptor = + getDescriptor().getMessageTypes().get(1); + internal_static_openxc_CanMessage_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_CanMessage_descriptor, + new java.lang.String[] { "Bus", "Id", "Data", "FrameFormat", }, + com.openxc.BinaryMessages.CanMessage.class, + com.openxc.BinaryMessages.CanMessage.Builder.class); + internal_static_openxc_ControlCommand_descriptor = + getDescriptor().getMessageTypes().get(2); + internal_static_openxc_ControlCommand_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_ControlCommand_descriptor, + new java.lang.String[] { "Type", "DiagnosticRequest", "PassthroughModeRequest", "AcceptanceFilterBypassCommand", "PayloadFormatCommand", "PredefinedObd2RequestsCommand", "ModemConfigurationCommand", "RtcConfigurationCommand", }, + com.openxc.BinaryMessages.ControlCommand.class, + com.openxc.BinaryMessages.ControlCommand.Builder.class); + internal_static_openxc_DiagnosticControlCommand_descriptor = + getDescriptor().getMessageTypes().get(3); + internal_static_openxc_DiagnosticControlCommand_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_DiagnosticControlCommand_descriptor, + new java.lang.String[] { "Request", "Action", }, + com.openxc.BinaryMessages.DiagnosticControlCommand.class, + com.openxc.BinaryMessages.DiagnosticControlCommand.Builder.class); + internal_static_openxc_PassthroughModeControlCommand_descriptor = + getDescriptor().getMessageTypes().get(4); + internal_static_openxc_PassthroughModeControlCommand_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_PassthroughModeControlCommand_descriptor, + new java.lang.String[] { "Bus", "Enabled", }, + com.openxc.BinaryMessages.PassthroughModeControlCommand.class, + com.openxc.BinaryMessages.PassthroughModeControlCommand.Builder.class); + internal_static_openxc_AcceptanceFilterBypassCommand_descriptor = + getDescriptor().getMessageTypes().get(5); + internal_static_openxc_AcceptanceFilterBypassCommand_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_AcceptanceFilterBypassCommand_descriptor, + new java.lang.String[] { "Bus", "Bypass", }, + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.class, + com.openxc.BinaryMessages.AcceptanceFilterBypassCommand.Builder.class); + internal_static_openxc_PayloadFormatCommand_descriptor = + getDescriptor().getMessageTypes().get(6); + internal_static_openxc_PayloadFormatCommand_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_PayloadFormatCommand_descriptor, + new java.lang.String[] { "Format", }, + com.openxc.BinaryMessages.PayloadFormatCommand.class, + com.openxc.BinaryMessages.PayloadFormatCommand.Builder.class); + internal_static_openxc_PredefinedObd2RequestsCommand_descriptor = + getDescriptor().getMessageTypes().get(7); + internal_static_openxc_PredefinedObd2RequestsCommand_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_PredefinedObd2RequestsCommand_descriptor, + new java.lang.String[] { "Enabled", }, + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.class, + com.openxc.BinaryMessages.PredefinedObd2RequestsCommand.Builder.class); + internal_static_openxc_NetworkOperatorSettings_descriptor = + getDescriptor().getMessageTypes().get(8); + internal_static_openxc_NetworkOperatorSettings_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_NetworkOperatorSettings_descriptor, + new java.lang.String[] { "AllowDataRoaming", "OperatorSelectMode", "NetworkDescriptor", }, + com.openxc.BinaryMessages.NetworkOperatorSettings.class, + com.openxc.BinaryMessages.NetworkOperatorSettings.Builder.class); + internal_static_openxc_NetworkOperatorSettings_NetworkDescriptor_descriptor = + internal_static_openxc_NetworkOperatorSettings_descriptor.getNestedTypes().get(0); + internal_static_openxc_NetworkOperatorSettings_NetworkDescriptor_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_NetworkOperatorSettings_NetworkDescriptor_descriptor, + new java.lang.String[] { "PLMN", "NetworkType", }, + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.class, + com.openxc.BinaryMessages.NetworkOperatorSettings.NetworkDescriptor.Builder.class); + internal_static_openxc_NetworkDataSettings_descriptor = + getDescriptor().getMessageTypes().get(9); + internal_static_openxc_NetworkDataSettings_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_NetworkDataSettings_descriptor, + new java.lang.String[] { "APN", }, + com.openxc.BinaryMessages.NetworkDataSettings.class, + com.openxc.BinaryMessages.NetworkDataSettings.Builder.class); + internal_static_openxc_ServerConnectSettings_descriptor = + getDescriptor().getMessageTypes().get(10); + internal_static_openxc_ServerConnectSettings_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_ServerConnectSettings_descriptor, + new java.lang.String[] { "Host", "Port", }, + com.openxc.BinaryMessages.ServerConnectSettings.class, + com.openxc.BinaryMessages.ServerConnectSettings.Builder.class); + internal_static_openxc_ModemConfigurationCommand_descriptor = + getDescriptor().getMessageTypes().get(11); + internal_static_openxc_ModemConfigurationCommand_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_ModemConfigurationCommand_descriptor, + new java.lang.String[] { "NetworkOperatorSettings", "NetworkDataSettings", "ServerConnectSettings", }, + com.openxc.BinaryMessages.ModemConfigurationCommand.class, + com.openxc.BinaryMessages.ModemConfigurationCommand.Builder.class); + internal_static_openxc_RTCConfigurationCommand_descriptor = + getDescriptor().getMessageTypes().get(12); + internal_static_openxc_RTCConfigurationCommand_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_RTCConfigurationCommand_descriptor, + new java.lang.String[] { "UnixTime", }, + com.openxc.BinaryMessages.RTCConfigurationCommand.class, + com.openxc.BinaryMessages.RTCConfigurationCommand.Builder.class); + internal_static_openxc_CommandResponse_descriptor = + getDescriptor().getMessageTypes().get(13); + internal_static_openxc_CommandResponse_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_CommandResponse_descriptor, + new java.lang.String[] { "Type", "Message", "Status", }, + com.openxc.BinaryMessages.CommandResponse.class, + com.openxc.BinaryMessages.CommandResponse.Builder.class); + internal_static_openxc_DiagnosticRequest_descriptor = + getDescriptor().getMessageTypes().get(14); + internal_static_openxc_DiagnosticRequest_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_DiagnosticRequest_descriptor, + new java.lang.String[] { "Bus", "MessageId", "Mode", "Pid", "Payload", "MultipleResponses", "Frequency", "Name", "DecodedType", }, + com.openxc.BinaryMessages.DiagnosticRequest.class, + com.openxc.BinaryMessages.DiagnosticRequest.Builder.class); + internal_static_openxc_DiagnosticResponse_descriptor = + getDescriptor().getMessageTypes().get(15); + internal_static_openxc_DiagnosticResponse_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_DiagnosticResponse_descriptor, + new java.lang.String[] { "Bus", "MessageId", "Mode", "Pid", "Success", "NegativeResponseCode", "Payload", "Value", }, + com.openxc.BinaryMessages.DiagnosticResponse.class, + com.openxc.BinaryMessages.DiagnosticResponse.Builder.class); + internal_static_openxc_DynamicField_descriptor = + getDescriptor().getMessageTypes().get(16); + internal_static_openxc_DynamicField_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_DynamicField_descriptor, + new java.lang.String[] { "Type", "StringValue", "NumericValue", "BooleanValue", }, + com.openxc.BinaryMessages.DynamicField.class, + com.openxc.BinaryMessages.DynamicField.Builder.class); + internal_static_openxc_SimpleMessage_descriptor = + getDescriptor().getMessageTypes().get(17); + internal_static_openxc_SimpleMessage_fieldAccessorTable = new + com.google.protobuf.GeneratedMessage.FieldAccessorTable( + internal_static_openxc_SimpleMessage_descriptor, + new java.lang.String[] { "Name", "Value", "Event", }, + com.openxc.BinaryMessages.SimpleMessage.class, + com.openxc.BinaryMessages.SimpleMessage.Builder.class); + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + }, assigner); + } + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/libs/openxc-message-format/gen/python/openxc_pb2.py b/libs/openxc-message-format/gen/python/openxc_pb2.py new file mode 100644 index 00000000..cd5ec5f0 --- /dev/null +++ b/libs/openxc-message-format/gen/python/openxc_pb2.py @@ -0,0 +1,1316 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! + +from google.protobuf import descriptor +from google.protobuf import message +from google.protobuf import reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + + +DESCRIPTOR = descriptor.FileDescriptor( + name='openxc.proto', + package='openxc', + serialized_pb='\n\x0copenxc.proto\x12\x06openxc\"\x9b\x03\n\x0eVehicleMessage\x12)\n\x04type\x18\x01 \x01(\x0e\x32\x1b.openxc.VehicleMessage.Type\x12\'\n\x0b\x63\x61n_message\x18\x02 \x01(\x0b\x32\x12.openxc.CanMessage\x12-\n\x0esimple_message\x18\x03 \x01(\x0b\x32\x15.openxc.SimpleMessage\x12\x37\n\x13\x64iagnostic_response\x18\x04 \x01(\x0b\x32\x1a.openxc.DiagnosticResponse\x12/\n\x0f\x63ontrol_command\x18\x05 \x01(\x0b\x32\x16.openxc.ControlCommand\x12\x31\n\x10\x63ommand_response\x18\x06 \x01(\x0b\x32\x17.openxc.CommandResponse\x12\x11\n\ttimestamp\x18\x07 \x01(\x04\"V\n\x04Type\x12\x07\n\x03\x43\x41N\x10\x01\x12\n\n\x06SIMPLE\x10\x02\x12\x0e\n\nDIAGNOSTIC\x10\x03\x12\x13\n\x0f\x43ONTROL_COMMAND\x10\x04\x12\x14\n\x10\x43OMMAND_RESPONSE\x10\x05\"\x94\x01\n\nCanMessage\x12\x0b\n\x03\x62us\x18\x01 \x01(\x05\x12\n\n\x02id\x18\x02 \x01(\r\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\x12\x34\n\x0c\x66rame_format\x18\x04 \x01(\x0e\x32\x1e.openxc.CanMessage.FrameFormat\")\n\x0b\x46rameFormat\x12\x0c\n\x08STANDARD\x10\x01\x12\x0c\n\x08\x45XTENDED\x10\x02\"\x97\x06\n\x0e\x43ontrolCommand\x12)\n\x04type\x18\x01 \x01(\x0e\x32\x1b.openxc.ControlCommand.Type\x12<\n\x12\x64iagnostic_request\x18\x02 \x01(\x0b\x32 .openxc.DiagnosticControlCommand\x12G\n\x18passthrough_mode_request\x18\x03 \x01(\x0b\x32%.openxc.PassthroughModeControlCommand\x12O\n acceptance_filter_bypass_command\x18\x04 \x01(\x0b\x32%.openxc.AcceptanceFilterBypassCommand\x12<\n\x16payload_format_command\x18\x05 \x01(\x0b\x32\x1c.openxc.PayloadFormatCommand\x12O\n predefined_obd2_requests_command\x18\x06 \x01(\x0b\x32%.openxc.PredefinedObd2RequestsCommand\x12\x46\n\x1bmodem_configuration_command\x18\x07 \x01(\x0b\x32!.openxc.ModemConfigurationCommand\x12\x42\n\x19rtc_configuration_command\x18\x08 \x01(\x0b\x32\x1f.openxc.RTCConfigurationCommand\"\xe6\x01\n\x04Type\x12\x0b\n\x07VERSION\x10\x01\x12\r\n\tDEVICE_ID\x10\x02\x12\x0e\n\nDIAGNOSTIC\x10\x03\x12\x0f\n\x0bPASSTHROUGH\x10\x04\x12\x1c\n\x18\x41\x43\x43\x45PTANCE_FILTER_BYPASS\x10\x05\x12\x12\n\x0ePAYLOAD_FORMAT\x10\x06\x12\x1c\n\x18PREDEFINED_OBD2_REQUESTS\x10\x07\x12\x17\n\x13MODEM_CONFIGURATION\x10\x08\x12\x15\n\x11RTC_CONFIGURATION\x10\t\x12\x13\n\x0fSD_MOUNT_STATUS\x10\n\x12\x0c\n\x08PLATFORM\x10\x0b\"\x9e\x01\n\x18\x44iagnosticControlCommand\x12*\n\x07request\x18\x01 \x01(\x0b\x32\x19.openxc.DiagnosticRequest\x12\x37\n\x06\x61\x63tion\x18\x02 \x01(\x0e\x32\'.openxc.DiagnosticControlCommand.Action\"\x1d\n\x06\x41\x63tion\x12\x07\n\x03\x41\x44\x44\x10\x01\x12\n\n\x06\x43\x41NCEL\x10\x02\"=\n\x1dPassthroughModeControlCommand\x12\x0b\n\x03\x62us\x18\x01 \x01(\x05\x12\x0f\n\x07\x65nabled\x18\x02 \x01(\x08\"<\n\x1d\x41\x63\x63\x65ptanceFilterBypassCommand\x12\x0b\n\x03\x62us\x18\x01 \x01(\x05\x12\x0e\n\x06\x62ypass\x18\x02 \x01(\x08\"\x8c\x01\n\x14PayloadFormatCommand\x12:\n\x06\x66ormat\x18\x01 \x01(\x0e\x32*.openxc.PayloadFormatCommand.PayloadFormat\"8\n\rPayloadFormat\x12\x08\n\x04JSON\x10\x01\x12\x0c\n\x08PROTOBUF\x10\x02\x12\x0f\n\x0bMESSAGEPACK\x10\x03\"0\n\x1dPredefinedObd2RequestsCommand\x12\x0f\n\x07\x65nabled\x18\x01 \x01(\x08\"\xd1\x03\n\x17NetworkOperatorSettings\x12\x18\n\x10\x61llowDataRoaming\x18\x01 \x01(\x08\x12N\n\x12operatorSelectMode\x18\x02 \x01(\x0e\x32\x32.openxc.NetworkOperatorSettings.OperatorSelectMode\x12L\n\x11networkDescriptor\x18\x03 \x01(\x0b\x32\x31.openxc.NetworkOperatorSettings.NetworkDescriptor\x1a\x98\x01\n\x11NetworkDescriptor\x12\x0c\n\x04PLMN\x18\x01 \x01(\r\x12R\n\x0bnetworkType\x18\x02 \x01(\x0e\x32=.openxc.NetworkOperatorSettings.NetworkDescriptor.NetworkType\"!\n\x0bNetworkType\x12\x07\n\x03GSM\x10\x00\x12\t\n\x05UTRAN\x10\x02\"c\n\x12OperatorSelectMode\x12\r\n\tAUTOMATIC\x10\x00\x12\n\n\x06MANUAL\x10\x01\x12\x0e\n\nDEREGISTER\x10\x02\x12\x0c\n\x08SET_ONLY\x10\x03\x12\x14\n\x10MANUAL_AUTOMATIC\x10\x04\"\"\n\x13NetworkDataSettings\x12\x0b\n\x03\x41PN\x18\x01 \x01(\t\"3\n\x15ServerConnectSettings\x12\x0c\n\x04host\x18\x01 \x01(\t\x12\x0c\n\x04port\x18\x02 \x01(\r\"\xd5\x01\n\x19ModemConfigurationCommand\x12@\n\x17networkOperatorSettings\x18\x01 \x01(\x0b\x32\x1f.openxc.NetworkOperatorSettings\x12\x38\n\x13networkDataSettings\x18\x02 \x01(\x0b\x32\x1b.openxc.NetworkDataSettings\x12<\n\x15serverConnectSettings\x18\x03 \x01(\x0b\x32\x1d.openxc.ServerConnectSettings\",\n\x17RTCConfigurationCommand\x12\x11\n\tunix_time\x18\x01 \x01(\r\"]\n\x0f\x43ommandResponse\x12)\n\x04type\x18\x01 \x01(\x0e\x32\x1b.openxc.ControlCommand.Type\x12\x0f\n\x07message\x18\x02 \x01(\t\x12\x0e\n\x06status\x18\x03 \x01(\x08\"\xfd\x01\n\x11\x44iagnosticRequest\x12\x0b\n\x03\x62us\x18\x01 \x01(\x05\x12\x12\n\nmessage_id\x18\x02 \x01(\r\x12\x0c\n\x04mode\x18\x03 \x01(\r\x12\x0b\n\x03pid\x18\x04 \x01(\r\x12\x0f\n\x07payload\x18\x05 \x01(\x0c\x12\x1a\n\x12multiple_responses\x18\x06 \x01(\x08\x12\x11\n\tfrequency\x18\x07 \x01(\x01\x12\x0c\n\x04name\x18\x08 \x01(\t\x12;\n\x0c\x64\x65\x63oded_type\x18\t \x01(\x0e\x32%.openxc.DiagnosticRequest.DecodedType\"!\n\x0b\x44\x65\x63odedType\x12\x08\n\x04NONE\x10\x01\x12\x08\n\x04OBD2\x10\x02\"\xa1\x01\n\x12\x44iagnosticResponse\x12\x0b\n\x03\x62us\x18\x01 \x01(\x05\x12\x12\n\nmessage_id\x18\x02 \x01(\r\x12\x0c\n\x04mode\x18\x03 \x01(\r\x12\x0b\n\x03pid\x18\x04 \x01(\r\x12\x0f\n\x07success\x18\x05 \x01(\x08\x12\x1e\n\x16negative_response_code\x18\x06 \x01(\r\x12\x0f\n\x07payload\x18\x07 \x01(\x0c\x12\r\n\x05value\x18\x08 \x01(\x01\"\xa2\x01\n\x0c\x44ynamicField\x12\'\n\x04type\x18\x01 \x01(\x0e\x32\x19.openxc.DynamicField.Type\x12\x14\n\x0cstring_value\x18\x02 \x01(\t\x12\x15\n\rnumeric_value\x18\x03 \x01(\x01\x12\x15\n\rboolean_value\x18\x04 \x01(\x08\"%\n\x04Type\x12\n\n\x06STRING\x10\x01\x12\x07\n\x03NUM\x10\x02\x12\x08\n\x04\x42OOL\x10\x03\"g\n\rSimpleMessage\x12\x0c\n\x04name\x18\x01 \x01(\t\x12#\n\x05value\x18\x02 \x01(\x0b\x32\x14.openxc.DynamicField\x12#\n\x05\x65vent\x18\x03 \x01(\x0b\x32\x14.openxc.DynamicFieldB\x1c\n\ncom.openxcB\x0e\x42inaryMessages') + + + +_VEHICLEMESSAGE_TYPE = descriptor.EnumDescriptor( + name='Type', + full_name='openxc.VehicleMessage.Type', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='CAN', index=0, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='SIMPLE', index=1, number=2, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='DIAGNOSTIC', index=2, number=3, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='CONTROL_COMMAND', index=3, number=4, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='COMMAND_RESPONSE', index=4, number=5, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=350, + serialized_end=436, +) + +_CANMESSAGE_FRAMEFORMAT = descriptor.EnumDescriptor( + name='FrameFormat', + full_name='openxc.CanMessage.FrameFormat', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='STANDARD', index=0, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='EXTENDED', index=1, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=546, + serialized_end=587, +) + +_CONTROLCOMMAND_TYPE = descriptor.EnumDescriptor( + name='Type', + full_name='openxc.ControlCommand.Type', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='VERSION', index=0, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='DEVICE_ID', index=1, number=2, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='DIAGNOSTIC', index=2, number=3, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PASSTHROUGH', index=3, number=4, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='ACCEPTANCE_FILTER_BYPASS', index=4, number=5, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PAYLOAD_FORMAT', index=5, number=6, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PREDEFINED_OBD2_REQUESTS', index=6, number=7, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='MODEM_CONFIGURATION', index=7, number=8, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='RTC_CONFIGURATION', index=8, number=9, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='SD_MOUNT_STATUS', index=9, number=10, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PLATFORM', index=10, number=11, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=1151, + serialized_end=1381, +) + +_DIAGNOSTICCONTROLCOMMAND_ACTION = descriptor.EnumDescriptor( + name='Action', + full_name='openxc.DiagnosticControlCommand.Action', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='ADD', index=0, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='CANCEL', index=1, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=1513, + serialized_end=1542, +) + +_PAYLOADFORMATCOMMAND_PAYLOADFORMAT = descriptor.EnumDescriptor( + name='PayloadFormat', + full_name='openxc.PayloadFormatCommand.PayloadFormat', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='JSON', index=0, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PROTOBUF', index=1, number=2, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='MESSAGEPACK', index=2, number=3, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=1754, + serialized_end=1810, +) + +_NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR_NETWORKTYPE = descriptor.EnumDescriptor( + name='NetworkType', + full_name='openxc.NetworkOperatorSettings.NetworkDescriptor.NetworkType', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='GSM', index=0, number=0, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='UTRAN', index=1, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=2194, + serialized_end=2227, +) + +_NETWORKOPERATORSETTINGS_OPERATORSELECTMODE = descriptor.EnumDescriptor( + name='OperatorSelectMode', + full_name='openxc.NetworkOperatorSettings.OperatorSelectMode', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='AUTOMATIC', index=0, number=0, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='MANUAL', index=1, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='DEREGISTER', index=2, number=2, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='SET_ONLY', index=3, number=3, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='MANUAL_AUTOMATIC', index=4, number=4, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=2229, + serialized_end=2328, +) + +_DIAGNOSTICREQUEST_DECODEDTYPE = descriptor.EnumDescriptor( + name='DecodedType', + full_name='openxc.DiagnosticRequest.DecodedType', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='NONE', index=0, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='OBD2', index=1, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=2997, + serialized_end=3030, +) + +_DYNAMICFIELD_TYPE = descriptor.EnumDescriptor( + name='Type', + full_name='openxc.DynamicField.Type', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='STRING', index=0, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='NUM', index=1, number=2, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='BOOL', index=2, number=3, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=3322, + serialized_end=3359, +) + + +_VEHICLEMESSAGE = descriptor.Descriptor( + name='VehicleMessage', + full_name='openxc.VehicleMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='type', full_name='openxc.VehicleMessage.type', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='can_message', full_name='openxc.VehicleMessage.can_message', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='simple_message', full_name='openxc.VehicleMessage.simple_message', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='diagnostic_response', full_name='openxc.VehicleMessage.diagnostic_response', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='control_command', full_name='openxc.VehicleMessage.control_command', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='command_response', full_name='openxc.VehicleMessage.command_response', index=5, + number=6, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='timestamp', full_name='openxc.VehicleMessage.timestamp', index=6, + number=7, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _VEHICLEMESSAGE_TYPE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=25, + serialized_end=436, +) + + +_CANMESSAGE = descriptor.Descriptor( + name='CanMessage', + full_name='openxc.CanMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='bus', full_name='openxc.CanMessage.bus', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='id', full_name='openxc.CanMessage.id', index=1, + number=2, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='data', full_name='openxc.CanMessage.data', index=2, + number=3, type=12, cpp_type=9, label=1, + has_default_value=False, default_value="", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='frame_format', full_name='openxc.CanMessage.frame_format', index=3, + number=4, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _CANMESSAGE_FRAMEFORMAT, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=439, + serialized_end=587, +) + + +_CONTROLCOMMAND = descriptor.Descriptor( + name='ControlCommand', + full_name='openxc.ControlCommand', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='type', full_name='openxc.ControlCommand.type', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='diagnostic_request', full_name='openxc.ControlCommand.diagnostic_request', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='passthrough_mode_request', full_name='openxc.ControlCommand.passthrough_mode_request', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='acceptance_filter_bypass_command', full_name='openxc.ControlCommand.acceptance_filter_bypass_command', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='payload_format_command', full_name='openxc.ControlCommand.payload_format_command', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='predefined_obd2_requests_command', full_name='openxc.ControlCommand.predefined_obd2_requests_command', index=5, + number=6, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='modem_configuration_command', full_name='openxc.ControlCommand.modem_configuration_command', index=6, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='rtc_configuration_command', full_name='openxc.ControlCommand.rtc_configuration_command', index=7, + number=8, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _CONTROLCOMMAND_TYPE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=590, + serialized_end=1381, +) + + +_DIAGNOSTICCONTROLCOMMAND = descriptor.Descriptor( + name='DiagnosticControlCommand', + full_name='openxc.DiagnosticControlCommand', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='request', full_name='openxc.DiagnosticControlCommand.request', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='action', full_name='openxc.DiagnosticControlCommand.action', index=1, + number=2, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _DIAGNOSTICCONTROLCOMMAND_ACTION, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1384, + serialized_end=1542, +) + + +_PASSTHROUGHMODECONTROLCOMMAND = descriptor.Descriptor( + name='PassthroughModeControlCommand', + full_name='openxc.PassthroughModeControlCommand', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='bus', full_name='openxc.PassthroughModeControlCommand.bus', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='enabled', full_name='openxc.PassthroughModeControlCommand.enabled', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1544, + serialized_end=1605, +) + + +_ACCEPTANCEFILTERBYPASSCOMMAND = descriptor.Descriptor( + name='AcceptanceFilterBypassCommand', + full_name='openxc.AcceptanceFilterBypassCommand', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='bus', full_name='openxc.AcceptanceFilterBypassCommand.bus', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='bypass', full_name='openxc.AcceptanceFilterBypassCommand.bypass', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1607, + serialized_end=1667, +) + + +_PAYLOADFORMATCOMMAND = descriptor.Descriptor( + name='PayloadFormatCommand', + full_name='openxc.PayloadFormatCommand', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='format', full_name='openxc.PayloadFormatCommand.format', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _PAYLOADFORMATCOMMAND_PAYLOADFORMAT, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1670, + serialized_end=1810, +) + + +_PREDEFINEDOBD2REQUESTSCOMMAND = descriptor.Descriptor( + name='PredefinedObd2RequestsCommand', + full_name='openxc.PredefinedObd2RequestsCommand', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='enabled', full_name='openxc.PredefinedObd2RequestsCommand.enabled', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1812, + serialized_end=1860, +) + + +_NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR = descriptor.Descriptor( + name='NetworkDescriptor', + full_name='openxc.NetworkOperatorSettings.NetworkDescriptor', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='PLMN', full_name='openxc.NetworkOperatorSettings.NetworkDescriptor.PLMN', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='networkType', full_name='openxc.NetworkOperatorSettings.NetworkDescriptor.networkType', index=1, + number=2, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR_NETWORKTYPE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2075, + serialized_end=2227, +) + +_NETWORKOPERATORSETTINGS = descriptor.Descriptor( + name='NetworkOperatorSettings', + full_name='openxc.NetworkOperatorSettings', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='allowDataRoaming', full_name='openxc.NetworkOperatorSettings.allowDataRoaming', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='operatorSelectMode', full_name='openxc.NetworkOperatorSettings.operatorSelectMode', index=1, + number=2, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='networkDescriptor', full_name='openxc.NetworkOperatorSettings.networkDescriptor', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR, ], + enum_types=[ + _NETWORKOPERATORSETTINGS_OPERATORSELECTMODE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1863, + serialized_end=2328, +) + + +_NETWORKDATASETTINGS = descriptor.Descriptor( + name='NetworkDataSettings', + full_name='openxc.NetworkDataSettings', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='APN', full_name='openxc.NetworkDataSettings.APN', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2330, + serialized_end=2364, +) + + +_SERVERCONNECTSETTINGS = descriptor.Descriptor( + name='ServerConnectSettings', + full_name='openxc.ServerConnectSettings', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='host', full_name='openxc.ServerConnectSettings.host', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='port', full_name='openxc.ServerConnectSettings.port', index=1, + number=2, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2366, + serialized_end=2417, +) + + +_MODEMCONFIGURATIONCOMMAND = descriptor.Descriptor( + name='ModemConfigurationCommand', + full_name='openxc.ModemConfigurationCommand', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='networkOperatorSettings', full_name='openxc.ModemConfigurationCommand.networkOperatorSettings', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='networkDataSettings', full_name='openxc.ModemConfigurationCommand.networkDataSettings', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='serverConnectSettings', full_name='openxc.ModemConfigurationCommand.serverConnectSettings', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2420, + serialized_end=2633, +) + + +_RTCCONFIGURATIONCOMMAND = descriptor.Descriptor( + name='RTCConfigurationCommand', + full_name='openxc.RTCConfigurationCommand', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='unix_time', full_name='openxc.RTCConfigurationCommand.unix_time', index=0, + number=1, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2635, + serialized_end=2679, +) + + +_COMMANDRESPONSE = descriptor.Descriptor( + name='CommandResponse', + full_name='openxc.CommandResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='type', full_name='openxc.CommandResponse.type', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='message', full_name='openxc.CommandResponse.message', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='status', full_name='openxc.CommandResponse.status', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2681, + serialized_end=2774, +) + + +_DIAGNOSTICREQUEST = descriptor.Descriptor( + name='DiagnosticRequest', + full_name='openxc.DiagnosticRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='bus', full_name='openxc.DiagnosticRequest.bus', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='message_id', full_name='openxc.DiagnosticRequest.message_id', index=1, + number=2, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='mode', full_name='openxc.DiagnosticRequest.mode', index=2, + number=3, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='pid', full_name='openxc.DiagnosticRequest.pid', index=3, + number=4, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='payload', full_name='openxc.DiagnosticRequest.payload', index=4, + number=5, type=12, cpp_type=9, label=1, + has_default_value=False, default_value="", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='multiple_responses', full_name='openxc.DiagnosticRequest.multiple_responses', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='frequency', full_name='openxc.DiagnosticRequest.frequency', index=6, + number=7, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='name', full_name='openxc.DiagnosticRequest.name', index=7, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='decoded_type', full_name='openxc.DiagnosticRequest.decoded_type', index=8, + number=9, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _DIAGNOSTICREQUEST_DECODEDTYPE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2777, + serialized_end=3030, +) + + +_DIAGNOSTICRESPONSE = descriptor.Descriptor( + name='DiagnosticResponse', + full_name='openxc.DiagnosticResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='bus', full_name='openxc.DiagnosticResponse.bus', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='message_id', full_name='openxc.DiagnosticResponse.message_id', index=1, + number=2, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='mode', full_name='openxc.DiagnosticResponse.mode', index=2, + number=3, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='pid', full_name='openxc.DiagnosticResponse.pid', index=3, + number=4, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='success', full_name='openxc.DiagnosticResponse.success', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='negative_response_code', full_name='openxc.DiagnosticResponse.negative_response_code', index=5, + number=6, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='payload', full_name='openxc.DiagnosticResponse.payload', index=6, + number=7, type=12, cpp_type=9, label=1, + has_default_value=False, default_value="", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='value', full_name='openxc.DiagnosticResponse.value', index=7, + number=8, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3033, + serialized_end=3194, +) + + +_DYNAMICFIELD = descriptor.Descriptor( + name='DynamicField', + full_name='openxc.DynamicField', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='type', full_name='openxc.DynamicField.type', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='string_value', full_name='openxc.DynamicField.string_value', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='numeric_value', full_name='openxc.DynamicField.numeric_value', index=2, + number=3, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='boolean_value', full_name='openxc.DynamicField.boolean_value', index=3, + number=4, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _DYNAMICFIELD_TYPE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3197, + serialized_end=3359, +) + + +_SIMPLEMESSAGE = descriptor.Descriptor( + name='SimpleMessage', + full_name='openxc.SimpleMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='name', full_name='openxc.SimpleMessage.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='value', full_name='openxc.SimpleMessage.value', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='event', full_name='openxc.SimpleMessage.event', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3361, + serialized_end=3464, +) + +_VEHICLEMESSAGE.fields_by_name['type'].enum_type = _VEHICLEMESSAGE_TYPE +_VEHICLEMESSAGE.fields_by_name['can_message'].message_type = _CANMESSAGE +_VEHICLEMESSAGE.fields_by_name['simple_message'].message_type = _SIMPLEMESSAGE +_VEHICLEMESSAGE.fields_by_name['diagnostic_response'].message_type = _DIAGNOSTICRESPONSE +_VEHICLEMESSAGE.fields_by_name['control_command'].message_type = _CONTROLCOMMAND +_VEHICLEMESSAGE.fields_by_name['command_response'].message_type = _COMMANDRESPONSE +_VEHICLEMESSAGE_TYPE.containing_type = _VEHICLEMESSAGE; +_CANMESSAGE.fields_by_name['frame_format'].enum_type = _CANMESSAGE_FRAMEFORMAT +_CANMESSAGE_FRAMEFORMAT.containing_type = _CANMESSAGE; +_CONTROLCOMMAND.fields_by_name['type'].enum_type = _CONTROLCOMMAND_TYPE +_CONTROLCOMMAND.fields_by_name['diagnostic_request'].message_type = _DIAGNOSTICCONTROLCOMMAND +_CONTROLCOMMAND.fields_by_name['passthrough_mode_request'].message_type = _PASSTHROUGHMODECONTROLCOMMAND +_CONTROLCOMMAND.fields_by_name['acceptance_filter_bypass_command'].message_type = _ACCEPTANCEFILTERBYPASSCOMMAND +_CONTROLCOMMAND.fields_by_name['payload_format_command'].message_type = _PAYLOADFORMATCOMMAND +_CONTROLCOMMAND.fields_by_name['predefined_obd2_requests_command'].message_type = _PREDEFINEDOBD2REQUESTSCOMMAND +_CONTROLCOMMAND.fields_by_name['modem_configuration_command'].message_type = _MODEMCONFIGURATIONCOMMAND +_CONTROLCOMMAND.fields_by_name['rtc_configuration_command'].message_type = _RTCCONFIGURATIONCOMMAND +_CONTROLCOMMAND_TYPE.containing_type = _CONTROLCOMMAND; +_DIAGNOSTICCONTROLCOMMAND.fields_by_name['request'].message_type = _DIAGNOSTICREQUEST +_DIAGNOSTICCONTROLCOMMAND.fields_by_name['action'].enum_type = _DIAGNOSTICCONTROLCOMMAND_ACTION +_DIAGNOSTICCONTROLCOMMAND_ACTION.containing_type = _DIAGNOSTICCONTROLCOMMAND; +_PAYLOADFORMATCOMMAND.fields_by_name['format'].enum_type = _PAYLOADFORMATCOMMAND_PAYLOADFORMAT +_PAYLOADFORMATCOMMAND_PAYLOADFORMAT.containing_type = _PAYLOADFORMATCOMMAND; +_NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR.fields_by_name['networkType'].enum_type = _NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR_NETWORKTYPE +_NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR.containing_type = _NETWORKOPERATORSETTINGS; +_NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR_NETWORKTYPE.containing_type = _NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR; +_NETWORKOPERATORSETTINGS.fields_by_name['operatorSelectMode'].enum_type = _NETWORKOPERATORSETTINGS_OPERATORSELECTMODE +_NETWORKOPERATORSETTINGS.fields_by_name['networkDescriptor'].message_type = _NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR +_NETWORKOPERATORSETTINGS_OPERATORSELECTMODE.containing_type = _NETWORKOPERATORSETTINGS; +_MODEMCONFIGURATIONCOMMAND.fields_by_name['networkOperatorSettings'].message_type = _NETWORKOPERATORSETTINGS +_MODEMCONFIGURATIONCOMMAND.fields_by_name['networkDataSettings'].message_type = _NETWORKDATASETTINGS +_MODEMCONFIGURATIONCOMMAND.fields_by_name['serverConnectSettings'].message_type = _SERVERCONNECTSETTINGS +_COMMANDRESPONSE.fields_by_name['type'].enum_type = _CONTROLCOMMAND_TYPE +_DIAGNOSTICREQUEST.fields_by_name['decoded_type'].enum_type = _DIAGNOSTICREQUEST_DECODEDTYPE +_DIAGNOSTICREQUEST_DECODEDTYPE.containing_type = _DIAGNOSTICREQUEST; +_DYNAMICFIELD.fields_by_name['type'].enum_type = _DYNAMICFIELD_TYPE +_DYNAMICFIELD_TYPE.containing_type = _DYNAMICFIELD; +_SIMPLEMESSAGE.fields_by_name['value'].message_type = _DYNAMICFIELD +_SIMPLEMESSAGE.fields_by_name['event'].message_type = _DYNAMICFIELD +DESCRIPTOR.message_types_by_name['VehicleMessage'] = _VEHICLEMESSAGE +DESCRIPTOR.message_types_by_name['CanMessage'] = _CANMESSAGE +DESCRIPTOR.message_types_by_name['ControlCommand'] = _CONTROLCOMMAND +DESCRIPTOR.message_types_by_name['DiagnosticControlCommand'] = _DIAGNOSTICCONTROLCOMMAND +DESCRIPTOR.message_types_by_name['PassthroughModeControlCommand'] = _PASSTHROUGHMODECONTROLCOMMAND +DESCRIPTOR.message_types_by_name['AcceptanceFilterBypassCommand'] = _ACCEPTANCEFILTERBYPASSCOMMAND +DESCRIPTOR.message_types_by_name['PayloadFormatCommand'] = _PAYLOADFORMATCOMMAND +DESCRIPTOR.message_types_by_name['PredefinedObd2RequestsCommand'] = _PREDEFINEDOBD2REQUESTSCOMMAND +DESCRIPTOR.message_types_by_name['NetworkOperatorSettings'] = _NETWORKOPERATORSETTINGS +DESCRIPTOR.message_types_by_name['NetworkDataSettings'] = _NETWORKDATASETTINGS +DESCRIPTOR.message_types_by_name['ServerConnectSettings'] = _SERVERCONNECTSETTINGS +DESCRIPTOR.message_types_by_name['ModemConfigurationCommand'] = _MODEMCONFIGURATIONCOMMAND +DESCRIPTOR.message_types_by_name['RTCConfigurationCommand'] = _RTCCONFIGURATIONCOMMAND +DESCRIPTOR.message_types_by_name['CommandResponse'] = _COMMANDRESPONSE +DESCRIPTOR.message_types_by_name['DiagnosticRequest'] = _DIAGNOSTICREQUEST +DESCRIPTOR.message_types_by_name['DiagnosticResponse'] = _DIAGNOSTICRESPONSE +DESCRIPTOR.message_types_by_name['DynamicField'] = _DYNAMICFIELD +DESCRIPTOR.message_types_by_name['SimpleMessage'] = _SIMPLEMESSAGE + +class VehicleMessage(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _VEHICLEMESSAGE + + # @@protoc_insertion_point(class_scope:openxc.VehicleMessage) + +class CanMessage(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CANMESSAGE + + # @@protoc_insertion_point(class_scope:openxc.CanMessage) + +class ControlCommand(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CONTROLCOMMAND + + # @@protoc_insertion_point(class_scope:openxc.ControlCommand) + +class DiagnosticControlCommand(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _DIAGNOSTICCONTROLCOMMAND + + # @@protoc_insertion_point(class_scope:openxc.DiagnosticControlCommand) + +class PassthroughModeControlCommand(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PASSTHROUGHMODECONTROLCOMMAND + + # @@protoc_insertion_point(class_scope:openxc.PassthroughModeControlCommand) + +class AcceptanceFilterBypassCommand(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _ACCEPTANCEFILTERBYPASSCOMMAND + + # @@protoc_insertion_point(class_scope:openxc.AcceptanceFilterBypassCommand) + +class PayloadFormatCommand(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PAYLOADFORMATCOMMAND + + # @@protoc_insertion_point(class_scope:openxc.PayloadFormatCommand) + +class PredefinedObd2RequestsCommand(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PREDEFINEDOBD2REQUESTSCOMMAND + + # @@protoc_insertion_point(class_scope:openxc.PredefinedObd2RequestsCommand) + +class NetworkOperatorSettings(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + + class NetworkDescriptor(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _NETWORKOPERATORSETTINGS_NETWORKDESCRIPTOR + + # @@protoc_insertion_point(class_scope:openxc.NetworkOperatorSettings.NetworkDescriptor) + DESCRIPTOR = _NETWORKOPERATORSETTINGS + + # @@protoc_insertion_point(class_scope:openxc.NetworkOperatorSettings) + +class NetworkDataSettings(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _NETWORKDATASETTINGS + + # @@protoc_insertion_point(class_scope:openxc.NetworkDataSettings) + +class ServerConnectSettings(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _SERVERCONNECTSETTINGS + + # @@protoc_insertion_point(class_scope:openxc.ServerConnectSettings) + +class ModemConfigurationCommand(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _MODEMCONFIGURATIONCOMMAND + + # @@protoc_insertion_point(class_scope:openxc.ModemConfigurationCommand) + +class RTCConfigurationCommand(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _RTCCONFIGURATIONCOMMAND + + # @@protoc_insertion_point(class_scope:openxc.RTCConfigurationCommand) + +class CommandResponse(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _COMMANDRESPONSE + + # @@protoc_insertion_point(class_scope:openxc.CommandResponse) + +class DiagnosticRequest(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _DIAGNOSTICREQUEST + + # @@protoc_insertion_point(class_scope:openxc.DiagnosticRequest) + +class DiagnosticResponse(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _DIAGNOSTICRESPONSE + + # @@protoc_insertion_point(class_scope:openxc.DiagnosticResponse) + +class DynamicField(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _DYNAMICFIELD + + # @@protoc_insertion_point(class_scope:openxc.DynamicField) + +class SimpleMessage(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _SIMPLEMESSAGE + + # @@protoc_insertion_point(class_scope:openxc.SimpleMessage) + +# @@protoc_insertion_point(module_scope) diff --git a/libs/openxc-message-format/openxc.options b/libs/openxc-message-format/openxc.options new file mode 100644 index 00000000..53726fc4 --- /dev/null +++ b/libs/openxc-message-format/openxc.options @@ -0,0 +1,10 @@ +openxc.SimpleMessage.name max_size:100 +openxc.DynamicField.string_value max_size:100 +openxc.CommandResponse.message max_size:128 +openxc.DiagnosticResponse.payload max_size:255 +openxc.DiagnosticRequest.name max_size:10 +openxc.DiagnosticRequest.payload max_size:8 +openxc.CanMessage.data max_size:8 + +openxc.ServerConnectSettings.host max_size:128 +openxc.NetworkDataSettings.apn max_size:64 diff --git a/libs/openxc-message-format/openxc.proto b/libs/openxc-message-format/openxc.proto new file mode 100644 index 00000000..db7164ff --- /dev/null +++ b/libs/openxc-message-format/openxc.proto @@ -0,0 +1,174 @@ +package openxc; + +option java_package = "com.openxc"; +option java_outer_classname = "BinaryMessages"; + +message VehicleMessage { + enum Type { CAN = 1; SIMPLE = 2; DIAGNOSTIC = 3; CONTROL_COMMAND = 4; + COMMAND_RESPONSE = 5; } + + optional Type type = 1; + optional CanMessage can_message = 2; + optional SimpleMessage simple_message = 3; + optional DiagnosticResponse diagnostic_response = 4; + optional ControlCommand control_command = 5; + optional CommandResponse command_response = 6; + optional uint64 timestamp = 7; +} + +message CanMessage { + enum FrameFormat { + STANDARD = 1; + EXTENDED = 2; + } + optional int32 bus = 1; + optional uint32 id = 2; + optional bytes data = 3; + optional FrameFormat frame_format = 4; +} + +message ControlCommand { + enum Type { + VERSION = 1; + DEVICE_ID = 2; + DIAGNOSTIC = 3; + PASSTHROUGH = 4; + ACCEPTANCE_FILTER_BYPASS = 5; + PAYLOAD_FORMAT = 6; + PREDEFINED_OBD2_REQUESTS = 7; + MODEM_CONFIGURATION = 8; + RTC_CONFIGURATION = 9; + SD_MOUNT_STATUS = 10; + PLATFORM = 11; + } + + optional Type type = 1; + optional DiagnosticControlCommand diagnostic_request = 2; + optional PassthroughModeControlCommand passthrough_mode_request = 3; + optional AcceptanceFilterBypassCommand acceptance_filter_bypass_command = 4; + optional PayloadFormatCommand payload_format_command = 5; + optional PredefinedObd2RequestsCommand predefined_obd2_requests_command = 6; + optional ModemConfigurationCommand modem_configuration_command = 7; + optional RTCConfigurationCommand rtc_configuration_command = 8; +} + +message DiagnosticControlCommand { + enum Action { ADD = 1; CANCEL = 2; } + + optional DiagnosticRequest request = 1; + optional Action action = 2; +} + +message PassthroughModeControlCommand { + optional int32 bus = 1; + optional bool enabled = 2; +} + +message AcceptanceFilterBypassCommand { + optional int32 bus = 1; + optional bool bypass = 2; +} + +message PayloadFormatCommand { + enum PayloadFormat { + JSON = 1; + PROTOBUF = 2; + MESSAGEPACK = 3; + } + + optional PayloadFormat format = 1; +} + +message PredefinedObd2RequestsCommand { + optional bool enabled = 1; +} + +message NetworkOperatorSettings { + enum OperatorSelectMode { + AUTOMATIC = 0; + MANUAL = 1; + DEREGISTER = 2; + SET_ONLY = 3; + MANUAL_AUTOMATIC = 4; + } + message NetworkDescriptor { + enum NetworkType { + GSM = 0; + UTRAN = 2; + } + optional uint32 PLMN = 1; + optional NetworkType networkType = 2; + } + optional bool allowDataRoaming = 1; + optional OperatorSelectMode operatorSelectMode = 2; + optional NetworkDescriptor networkDescriptor = 3; +} + +message NetworkDataSettings { + optional string APN = 1; +} + +message ServerConnectSettings { + optional string host = 1; + optional uint32 port = 2; +} + +message ModemConfigurationCommand { + optional NetworkOperatorSettings networkOperatorSettings = 1; + optional NetworkDataSettings networkDataSettings = 2; + optional ServerConnectSettings serverConnectSettings = 3; +} + +message RTCConfigurationCommand { + optional uint32 unix_time = 1; +} + +message CommandResponse { + optional ControlCommand.Type type = 1; + optional string message = 2; + optional bool status = 3; +} + +message DiagnosticRequest { + enum DecodedType { NONE = 1; OBD2 = 2; } + + optional int32 bus = 1; + optional uint32 message_id = 2; + optional uint32 mode = 3; + optional uint32 pid = 4; + // TODO we are capping this at 8 bytes for now - need to change when we + // support multi-frame responses + optional bytes payload = 5; + optional bool multiple_responses = 6; + optional double frequency = 7; + optional string name = 8; + optional DecodedType decoded_type = 9; +} + +message DiagnosticResponse { + optional int32 bus = 1; + optional uint32 message_id = 2; + optional uint32 mode = 3; + optional uint32 pid = 4; + optional bool success = 5; + optional uint32 negative_response_code = 6; + // TODO we are capping this at 8 bytes for now - need to change when we + // support multi-frame responses + optional bytes payload = 7; + optional double value = 8; +} + +message DynamicField { + enum Type { STRING = 1; NUM = 2; BOOL = 3; } + + optional Type type = 1; + optional string string_value = 2; + optional double numeric_value = 3; + optional bool boolean_value = 4; +} + +message SimpleMessage { + optional string name = 1; + optional DynamicField value = 2; + optional DynamicField event = 3; +} diff --git a/libs/openxc-message-format/pip-requirements.txt b/libs/openxc-message-format/pip-requirements.txt new file mode 100644 index 00000000..7f147d92 --- /dev/null +++ b/libs/openxc-message-format/pip-requirements.txt @@ -0,0 +1 @@ +protobuf==2.5.0 diff --git a/libs/openxc-message-format/script/bootstrap.sh b/libs/openxc-message-format/script/bootstrap.sh new file mode 100755 index 00000000..c0422422 --- /dev/null +++ b/libs/openxc-message-format/script/bootstrap.sh @@ -0,0 +1,179 @@ +#!/usr/bin/env bash + +set -e + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +pushd $DIR/.. + +# TODO this is kind of a hacky way of determining if root is required - +# ideally we wouuld set up a little virtualenv in the dependencies folder +SUDO_CMD= +if command -v sudo >/dev/null 2>&1; then + SUDO_CMD="sudo -E" + + echo "The bootstrap script needs to install a few packages to your system as an admin, and we will use the 'sudo' command - enter your password to continue" + $SUDO_CMD ls > /dev/null +fi + +KERNEL=`uname` +if [ ${KERNEL:0:7} == "MINGW32" ]; then + OS="windows" +elif [ ${KERNEL:0:6} == "CYGWIN" ]; then + OS="cygwin" +elif [ $KERNEL == "Darwin" ]; then + OS="mac" +else + OS="linux" + if ! command -v lsb_release >/dev/null 2>&1; then + # Arch Linux + if command -v pacman>/dev/null 2>&1; then + $SUDO_CMD pacman -S lsb-release + fi + fi + + DISTRO=`lsb_release -si` +fi + +die() { + echo >&2 "${bldred}$@${txtrst}" + exit 1 +} + +_cygwin_error() { + echo + echo "${bldred}Missing \"$1\"${txtrst} - run the Cygwin installer again and select the base package set:" + echo " $CYGWIN_PACKAGES" + echo "After installing the packages, re-run this bootstrap script." + die +} + +if ! command -v tput >/dev/null 2>&1; then + if [ $OS == "cygwin" ]; then + echo "OPTIONAL: Install the \"ncurses\" package in Cygwin to get colored shell output" + fi +else + txtrst=$(tput sgr0) # reset + bldred=${txtbld}$(tput setaf 1) + bldgreen=${txtbld}$(tput setaf 2) +fi + +_pushd() { + pushd $1 > /dev/null +} + +_popd() { + popd > /dev/null +} + +_wait() { + if [ -z $CI ]; then + echo "Press Enter when done" + read + fi +} + +_install() { + if [ $OS == "cygwin" ]; then + _cygwin_error $1 + elif [ $OS == "mac" ]; then + # brew exists with 1 if it's already installed + set +e + brew install $1 + set -e + else + if [ -z $DISTRO ]; then + echo + echo "Missing $1 - install it using your distro's package manager or build from source" + _wait + else + if [ $DISTRO == "arch" ]; then + $SUDO_CMD pacman -S $1 + elif [ $DISTRO == "Ubuntu" ]; then + $SUDO_CMD apt-get update -qq + $SUDO_CMD apt-get install $1 -y + else + echo + echo "Missing $1 - install it using your distro's package manager or build from source" + _wait + fi + fi + fi +} + +CYGWIN_PACKAGES="make curl, libsasl2, ca-certificates, ncurses, python-setuptools" + +download() { + url=$1 + filename=$2 + curl $url -L --O $filename +} + +if [ `id -u` == 0 ]; then + die "Error: running as root - don't use 'sudo' with this script" +fi + +if ! command -v curl >/dev/null 2>&1; then + if [ $OS == "cygwin" ]; then + _cygwin_error "curl" + else + _install curl + fi +fi + +if [ $OS == "windows" ]; then + die "Sorry, the bootstrap script for compiling from source doesn't support the Windows console - try Cygwin." +fi + +if [ $OS == "mac" ] && ! command -v brew >/dev/null 2>&1; then + echo "Installing Homebrew..." + ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)" +fi + +if ! command -v make >/dev/null 2>&1; then + if [ $OS == "cygwin" ]; then + _cygwin_error "make" + elif [ $OS == "mac" ]; then + die "Missing 'make' - install the Xcode CLI tools" + else + if [ $DISTRO == "arch" ]; then + $SUDO_CMD pacman -S base-devel + elif [ $DISTRO == "Ubuntu" ]; then + $SUDO_CMD apt-get update -qq + $SUDO_CMD apt-get install build-essential -y + fi + fi +fi + +if ! command -v python >/dev/null 2>&1; then + echo "Installing Python..." + _install "python" +fi + +if ! command -v pip >/dev/null 2>&1; then + echo "Installing Pip..." + if ! command -v easy_install >/dev/null 2>&1; then + die "easy_install not available, can't install pip" + fi + + $SUDO_CMD easy_install pip +fi + +$SUDO_CMD pip install -U pip +$SUDO_CMD pip install --pre -Ur pip-requirements.txt + +if ! command -v protoc >/dev/null 2>&1; then + if [ $OS == "cygwin" ]; then + _cygwin_error "protobuf" + elif [ $OS == "mac" ] || [ $OS == "linux" ]; then + if [ $DISTRO == "Ubuntu" ]; then + _install protobuf-compiler + else + _install protobuf + fi + fi +fi + +popd + +echo +echo "${bldgreen}All developer dependencies installed, ready to compile.$txtrst" diff --git a/libs/uds-c/.gitignore b/libs/uds-c/.gitignore new file mode 100644 index 00000000..834a305d --- /dev/null +++ b/libs/uds-c/.gitignore @@ -0,0 +1,5 @@ +*.o +.DS_Store +*~ +*.bin +build diff --git a/libs/uds-c/.travis.yml b/libs/uds-c/.travis.yml new file mode 100644 index 00000000..31bfdeb3 --- /dev/null +++ b/libs/uds-c/.travis.yml @@ -0,0 +1,8 @@ +language: c +compiler: + - gcc +script: make test +before_install: + - git submodule update --init + - sudo apt-get update -qq + - sudo apt-get install check diff --git a/libs/uds-c/CHANGELOG.mkd b/libs/uds-c/CHANGELOG.mkd new file mode 100644 index 00000000..96eaa178 --- /dev/null +++ b/libs/uds-c/CHANGELOG.mkd @@ -0,0 +1,9 @@ +# OBD-II Support Library in C + +## v0.2 + +* Add support for multi-frame diagnostic responses. + +## v0.1 + +* Initial release diff --git a/libs/uds-c/CMakeLists.txt b/libs/uds-c/CMakeLists.txt new file mode 100644 index 00000000..8f78fd6d --- /dev/null +++ b/libs/uds-c/CMakeLists.txt @@ -0,0 +1,41 @@ +########################################################################### +# Copyright 2015, 2016, 2017 IoT.bzh +# +# author: Fulup Ar Foll +# contrib: Romain Forlot +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +########################################################################### + +# Add target to project dependency list +PROJECT_TARGET_ADD(uds-c) + + # Define project Target + add_library(${TARGET_NAME} STATIC + src/uds/extras.c + src/uds/uds.c) + + # Binder exposes a unique public entry point + SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + OUTPUT_NAME ${TARGET_NAME} + ) + + # Define target includes + TARGET_INCLUDE_DIRECTORIES(${TARGET_NAME} + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + + # Library dependencies (include updates automatically) + TARGET_LINK_LIBRARIES(${TARGET_NAME} + isotp-c + ${link_libraries}) diff --git a/libs/uds-c/LICENSE b/libs/uds-c/LICENSE new file mode 100644 index 00000000..330d61f4 --- /dev/null +++ b/libs/uds-c/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2013 Ford Motor Company +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/libs/uds-c/Makefile b/libs/uds-c/Makefile new file mode 100644 index 00000000..4adf3ceb --- /dev/null +++ b/libs/uds-c/Makefile @@ -0,0 +1,56 @@ +CC = gcc +INCLUDES = -Isrc -Ideps/bitfield-c/src -Ideps/isotp-c/src +CFLAGS = $(INCLUDES) -c -Wall -Werror -g -ggdb -std=gnu99 -coverage +LDFLAGS = -coverage -lm +LDLIBS = -lcheck + +TEST_DIR = tests +TEST_OBJDIR = build + +# Guard against \r\n line endings only in Cygwin +OSTYPE := $(shell uname) +ifneq ($(OSTYPE),Darwin) + OSTYPE := $(shell uname -o) + ifeq ($(OSTYPE),Cygwin) + TEST_SET_OPTS = igncr + endif +endif + +SRC = $(wildcard src/**/*.c) +SRC += $(wildcard deps/bitfield-c/src/**/*.c) +SRC += $(wildcard deps/isotp-c/src/**/*.c) +OBJS = $(patsubst %,$(TEST_OBJDIR)/%,$(SRC:.c=.o)) +TEST_SRC = $(wildcard $(TEST_DIR)/test_*.c) +TESTS=$(patsubst %.c,$(TEST_OBJDIR)/%.bin,$(TEST_SRC)) +TEST_SUPPORT_SRC = $(TEST_DIR)/common.c +TEST_SUPPORT_OBJS = $(patsubst %,$(TEST_OBJDIR)/%,$(TEST_SUPPORT_SRC:.c=.o)) + +all: $(OBJS) + +test: $(TESTS) + @set -o $(TEST_SET_OPTS) >/dev/null 2>&1 + @export SHELLOPTS + @sh runtests.sh $(TEST_OBJDIR)/$(TEST_DIR) + +COVERAGE_INFO_FILENAME = coverage.info +COVERAGE_INFO_PATH = $(TEST_OBJDIR)/$(COVERAGE_INFO_FILENAME) +coverage: + @lcov --base-directory . --directory src --zerocounters -q + @make clean + @make test + @lcov --base-directory . --directory $(TEST_OBJDIR) -c -o $(TEST_OBJDIR)/coverage.info + @lcov --remove $(COVERAGE_INFO_PATH) "deps/*" -o $(COVERAGE_INFO_PATH) + @genhtml -o $(TEST_OBJDIR)/coverage -t "isotp-c test coverage" --num-spaces 4 $(COVERAGE_INFO_PATH) + @$(BROWSER) $(TEST_OBJDIR)/coverage/index.html + @echo "$(GREEN)Coverage information generated in $(TEST_OBJDIR)/coverage/index.html.$(COLOR_RESET)" + +$(TEST_OBJDIR)/%.o: %.c + @mkdir -p $(dir $@) + $(CC) $(CFLAGS) $(CC_SYMBOLS) $(INCLUDES) -o $@ $< + +$(TEST_OBJDIR)/%.bin: $(TEST_OBJDIR)/%.o $(OBJS) $(TEST_SUPPORT_OBJS) + @mkdir -p $(dir $@) + $(CC) $(LDFLAGS) $(CC_SYMBOLS) $(INCLUDES) -o $@ $^ $(LDLIBS) + +clean: + rm -rf $(TEST_OBJDIR) diff --git a/libs/uds-c/README.mkd b/libs/uds-c/README.mkd new file mode 100644 index 00000000..aa0d7fd7 --- /dev/null +++ b/libs/uds-c/README.mkd @@ -0,0 +1,196 @@ +Unified Diagnostic Services (UDS) Support Library in C +====================================================== + +This is a platform agnostic C library that implements the Unified Diagnostics +Services protocol for automotive electronics. UDS is documented in ISO 14229 and +is the underpinning for the more well-known On-board Diagnostics (OBD) standard. +The library currently supports UDS running over CAN (ISO 15765-4), which uses +the ISO-TP (ISO 15765-2) protocol for message framing. + +This library doesn't assume anything about the source of your diagnostic message +requests or underlying interface to the CAN bus. It uses dependency injection to +give you complete control. + +## Usage + +First, create some shim functions to let this library use your lower level +system: + + // required, this must send a single CAN message with the given arbitration + // ID (i.e. the CAN message ID) and data. The size will never be more than 8 + // bytes. + bool send_can(const uint32_t arbitration_id, const uint8_t* data, + const uint8_t size) { + ... + } + + // optional, provide to receive debugging log messages + void debug(const char* format, ...) { + ... + } + + + // not used in the current version + void set_timer(uint16_t time_ms, void (*callback)) { + ... + } + +With your shims in place, create a `DiagnosticShims` object to pass them around: + + DiagnosticShims shims = diagnostic_init_shims(debug, send_can, set_timer); + +With your shims in hand, send a simple PID request to the standard broadcast +address, `0x7df` (we use the constant `OBD2_FUNCTIONAL_BROADCAST_ID` here): + + // Optional: This is your callback that will be called the response to your + // diagnostic request is received. + void response_received_handler(const DiagnosticResponse* response) { + // You received a response! Do something with it. + } + + DiagnosticRequestHandle handle = diagnostic_request_pid(&shims, + DIAGNOSTIC_STANDARD_PID, // this is a standard PID request, not an extended or enhanced one + OBD2_FUNCTIONAL_BROADCAST_ID, // the request is going out to the broadcast arbitration ID + 0x2, // we want PID 0x2 + response_received_handler); // our callback (optional, use NULL if you don't have one) + + if(handle.completed) { + if(!handle.success) { + // something happened and it already failed - possibly we aren't + // able to send CAN messages + return; + } else { + // this should never occur right away - you need to receive a fresh + // CAN message first + } + } else { + while(true) { + // Continue to read from CAN, passing off each message to the handle. + // This will return a 'completed' DiagnosticResponse when the when + // the request is completely sent and the response is received + // (which may take more than 1 CAN frames) + DiagnosticResponse response = diagnostic_receive_can_frame(&shims, + &handle, can_message_id, can_data, sizeof(can_data)); + + if(response.completed && handle.completed) { + if(handle.success) { + if(response.success) { + // The request was sent successfully, the response was + // received successfully, and it was a positive response - we + // got back some data! + } else { + // The request was sent successfully, the response was + // received successfully, BUT it was a negative response + // from the other node. + printf("This is the error code: %d", response.negative_response_code); + } + } else { + // Some other fatal error ocurred - we weren't able to send + // the request or receive the response. The CAN connection + // may be down. + } + } + } + } + +### Requests for other modes + +If you want to do more besides PID requests on mode 0x1 and 0x22, there's a +lower level API you can use. Here's how to make a mode 3 request to get DTCs. + + DiagnosticRequest request = { + arbitration_id: OBD2_FUNCTIONAL_BROADCAST_ID, + mode: OBD2_MODE_EMISSIONS_DTC_REQUEST + }; + DiagnosticRequestHandle handle = diagnostic_request(&SHIMS, &request, NULL); + + if(handle.completed) { + if(!handle.success) { + // something happened and it already failed - possibly we aren't + // able to send CAN messages + return; + } else { + // this should never occur right away - you need to receive a fresh + // CAN message first + } + } else { + while(true) { + // Continue to read from CAN, passing off each message to the handle. + // This will return a 'completed' DiagnosticResponse when the when + // the request is completely sent and the response is received + // (which may take more than 1 CAN frames) + DiagnosticResponse response = diagnostic_receive_can_frame(&shims, + &handle, can_message_id, can_data, sizeof(can_data)); + + if(response.completed && handle.completed) { + if(handle.success) { + if(response.success) { + // The request was sent successfully, the response was + // received successfully, and it was a positive response - we + // got back some data! + printf("The DTCs are: "); + for(int i = 0; i < response.payload_length; i++) { + printf("0x%x ", response.payload[i]); + } + } else { + // The request was sent successfully, the response was + // received successfully, BUT it was a negative response + // from the other node. + printf("This is the error code: %d", response.negative_response_code); + } + } else { + // Some other fatal error ocurred - we weren't able to send + // the request or receive the response. The CAN connection + // may be down. + } + } + } + } + +## Dependencies + +This library requires 2 dependencies: + +* [isotp-c](https://github.com/openxc/isotp-c) +* [bitfield-c](https://github.com/openxc/bitfield-c) + +## Testing + +The library includes a test suite that uses the `check` C unit test library. + + $ make test + +You can also see the test coverage if you have `lcov` installed and the +`BROWSER` environment variable set to your choice of web browsers: + + $ BROWSER=google-chrome-stable make coverage + +## OBD-II Basics + +TODO diagram out a request, response and error response + +* store the request arb id, mode, pid, and payload locally +* send a can message +* get all new can messages passed to it +* Check the incoming can message to see if it matches one of the standard ECU + response IDs, or our arb ID + 0x8 +* if it matches, parse the diagnostic response and call the callback + + +## Future Notes + +you're going to request a few PIDs over and over again at some frequency +you're going to request DTCs once and read the response +you're going to clear DTCs once + +we need another layer on top of that to handle the repeated requests. + +## Authors + +Chris Peplin cpeplin@ford.com + +## License + +Copyright (c) 2013 Ford Motor Company + +Licensed under the BSD license. diff --git a/libs/uds-c/runtests.sh b/libs/uds-c/runtests.sh new file mode 100644 index 00000000..4781636b --- /dev/null +++ b/libs/uds-c/runtests.sh @@ -0,0 +1,17 @@ +echo "Running unit tests:" + +for i in $1/*.bin +do + if test -f $i + then + if ./$i + then + echo $i PASS + else + echo "ERROR in test $i:" + exit 1 + fi + fi +done + +echo "${txtbld}$(tput setaf 2)All unit tests passed.$(tput sgr0)" diff --git a/libs/uds-c/src/uds/extras.c b/libs/uds-c/src/uds/extras.c new file mode 100644 index 00000000..2be6bdd8 --- /dev/null +++ b/libs/uds-c/src/uds/extras.c @@ -0,0 +1,39 @@ +#include +#include + +// TODO everything below here is for future work...not critical for now. + +DiagnosticRequestHandle diagnostic_request_malfunction_indicator_status( + DiagnosticShims* shims, + DiagnosticMilStatusReceived callback) { + // TODO request malfunction indicator light (MIL) status - request mode 1 + // pid 1, parse first bit + DiagnosticRequestHandle handle; + return handle; +} + +DiagnosticRequestHandle diagnostic_request_vin(DiagnosticShims* shims, + DiagnosticVinReceived callback) { + DiagnosticRequestHandle handle; + return handle; +} + +DiagnosticRequestHandle diagnostic_request_dtc(DiagnosticShims* shims, + DiagnosticTroubleCodeType dtc_type, + DiagnosticTroubleCodesReceived callback) { + DiagnosticRequestHandle handle; + return handle; +} + +bool diagnostic_clear_dtc(DiagnosticShims* shims) { + return false; +} + +DiagnosticRequestHandle diagnostic_enumerate_pids(DiagnosticShims* shims, + DiagnosticRequest* request, DiagnosticPidEnumerationReceived callback) { + // before calling the callback, split up the received bytes into 1 or 2 byte + // chunks depending on the mode so the final pid list is actual 1 or 2 byte PIDs + // TODO request supported PIDs - request PID 0 and parse 4 bytes in response + DiagnosticRequestHandle handle; + return handle; +} diff --git a/libs/uds-c/src/uds/extras.h b/libs/uds-c/src/uds/extras.h new file mode 100644 index 00000000..126e5d42 --- /dev/null +++ b/libs/uds-c/src/uds/extras.h @@ -0,0 +1,71 @@ +#ifndef __EXTRAS_H__ +#define __EXTRAS_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// TODO everything in here is unused for the moment! + +typedef enum { + POWERTRAIN = 0x0, + CHASSIS = 0x1, + BODY = 0x2, + NETWORK = 0x3 +} DiagnosticTroubleCodeGroup; + +typedef struct { + DiagnosticTroubleCodeGroup group; + uint8_t group_num; + uint8_t code; +} DiagnosticTroubleCode; + + +/* Private: TODO unused for now + */ +typedef enum { + DTC_EMISSIONS, + DTC_DRIVE_CYCLE, + DTC_PERMANENT +} DiagnosticTroubleCodeType; + + +// TODO should we enumerate every OBD-II PID? need conversion formulas, too +typedef struct { + uint16_t pid; + uint8_t bytes_returned; + float min_value; + float max_value; +} DiagnosticParameter; + +typedef void (*DiagnosticMilStatusReceived)(bool malfunction_indicator_status); +typedef void (*DiagnosticVinReceived)(uint8_t vin[]); +typedef void (*DiagnosticTroubleCodesReceived)( + DiagnosticMode mode, DiagnosticTroubleCode* codes); +typedef void (*DiagnosticPidEnumerationReceived)( + const DiagnosticResponse* response, uint16_t* pids); + +DiagnosticRequestHandle diagnostic_request_malfunction_indicator_status( + DiagnosticShims* shims, + DiagnosticMilStatusReceived callback); + +DiagnosticRequestHandle diagnostic_request_vin(DiagnosticShims* shims, + DiagnosticVinReceived callback); + +DiagnosticRequestHandle diagnostic_request_dtc(DiagnosticShims* shims, + DiagnosticTroubleCodeType dtc_type, + DiagnosticTroubleCodesReceived callback); + +bool diagnostic_clear_dtc(DiagnosticShims* shims); + +DiagnosticRequestHandle diagnostic_enumerate_pids(DiagnosticShims* shims, + DiagnosticRequest* request, DiagnosticPidEnumerationReceived callback); + + +#ifdef __cplusplus +} +#endif + +#endif // __EXTRAS_H__ diff --git a/libs/uds-c/src/uds/uds.c b/libs/uds-c/src/uds/uds.c new file mode 100644 index 00000000..0114384d --- /dev/null +++ b/libs/uds-c/src/uds/uds.c @@ -0,0 +1,400 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#define ARBITRATION_ID_OFFSET 0x8 +#define MODE_RESPONSE_OFFSET 0x40 +#define NEGATIVE_RESPONSE_MODE 0x7f +#define MAX_DIAGNOSTIC_PAYLOAD_SIZE 6 +#define MODE_BYTE_INDEX 0 +#define PID_BYTE_INDEX 1 +#define NEGATIVE_RESPONSE_MODE_INDEX 1 +#define NEGATIVE_RESPONSE_NRC_INDEX 2 + +#ifndef MAX +#define MAX(x, y) (((x) > (y)) ? (x) : (y)) +#endif + +DiagnosticShims diagnostic_init_shims(LogShim log, + SendCanMessageShim send_can_message, + SetTimerShim set_timer) { + DiagnosticShims shims = { + log: log, + send_can_message: send_can_message, + set_timer: set_timer + }; + return shims; +} + +static void setup_receive_handle(DiagnosticRequestHandle* handle) { + if(handle->request.arbitration_id == OBD2_FUNCTIONAL_BROADCAST_ID) { + uint32_t response_id; + for(response_id = 0; + response_id < OBD2_FUNCTIONAL_RESPONSE_COUNT; ++response_id) { + handle->isotp_receive_handles[response_id] = isotp_receive( + &handle->isotp_shims, + OBD2_FUNCTIONAL_RESPONSE_START + response_id, + NULL); + } + handle->isotp_receive_handle_count = OBD2_FUNCTIONAL_RESPONSE_COUNT; + } else { + handle->isotp_receive_handle_count = 1; + handle->isotp_receive_handles[0] = isotp_receive(&handle->isotp_shims, + handle->request.arbitration_id + ARBITRATION_ID_OFFSET, + NULL); + } +} + +static uint16_t autoset_pid_length(uint8_t mode, uint16_t pid, + uint8_t pid_length) { + if(pid_length == 0) { + if(mode <= 0xa || mode == 0x3e ) { + pid_length = 1; + } else if(pid > 0xffff || ((pid & 0xFF00) > 0x0)) { + pid_length = 2; + } else { + pid_length = 1; + } + } + return pid_length; +} + +static void send_diagnostic_request(DiagnosticShims* shims, + DiagnosticRequestHandle* handle) { + uint8_t payload[MAX_DIAGNOSTIC_PAYLOAD_SIZE] = {0}; + payload[MODE_BYTE_INDEX] = handle->request.mode; + if(handle->request.has_pid) { + handle->request.pid_length = autoset_pid_length(handle->request.mode, + handle->request.pid, handle->request.pid_length); + set_bitfield(handle->request.pid, PID_BYTE_INDEX * CHAR_BIT, + handle->request.pid_length * CHAR_BIT, payload, + sizeof(payload)); + } + + if(handle->request.payload_length > 0) { + memcpy(&payload[PID_BYTE_INDEX + handle->request.pid_length], + handle->request.payload, handle->request.payload_length); + } + + handle->isotp_send_handle = isotp_send(&handle->isotp_shims, + handle->request.arbitration_id, payload, + 1 + handle->request.payload_length + handle->request.pid_length, + NULL); + if(handle->isotp_send_handle.completed && + !handle->isotp_send_handle.success) { + handle->completed = true; + handle->success = false; + if(shims->log != NULL) { + shims->log("%s", "Diagnostic request not sent"); + } + } else if(shims->log != NULL) { + char request_string[128] = {0}; + diagnostic_request_to_string(&handle->request, request_string, + sizeof(request_string)); + shims->log("Sending diagnostic request: %s", request_string); + } +} + +bool diagnostic_request_sent(DiagnosticRequestHandle* handle) { + return handle->isotp_send_handle.completed; +} + +void start_diagnostic_request(DiagnosticShims* shims, + DiagnosticRequestHandle* handle) { + handle->success = false; + handle->completed = false; + send_diagnostic_request(shims, handle); + if(!handle->completed) { + setup_receive_handle(handle); + } +} + +DiagnosticRequestHandle generate_diagnostic_request(DiagnosticShims* shims, + DiagnosticRequest* request, DiagnosticResponseReceived callback) { + DiagnosticRequestHandle handle = { + request: *request, + callback: callback, + success: false, + completed: false + }; + + handle.isotp_shims = isotp_init_shims(shims->log, + shims->send_can_message, + shims->set_timer); + handle.isotp_shims.frame_padding = !request->no_frame_padding; + + return handle; + // TODO notes on multi frame: + // TODO what are the timers for exactly? + // + // when sending multi frame, send 1 frame, wait for a response + // if it says send all, send all right away + // if it says flow control, set the time for the next send + // instead of creating a timer with an async callback, add a process_handle + // function that's called repeatedly in the main loop - if it's time to + // send, we do it. so there's a process_handle_send and receive_can_frame + // that are just called continuously from the main loop. it's a waste of a + // few cpu cycles but it may be more natural than callbacks. + // + // what would a timer callback look like...it would need to pass the handle + // and that's all. seems like a context void* would be able to capture all + // of the information but arg, memory allocation. look at how it's done in + // the other library again + // +} + +DiagnosticRequestHandle diagnostic_request(DiagnosticShims* shims, + DiagnosticRequest* request, DiagnosticResponseReceived callback) { + DiagnosticRequestHandle handle = generate_diagnostic_request( + shims, request, callback); + start_diagnostic_request(shims, &handle); + return handle; +} + +DiagnosticRequestHandle diagnostic_request_pid(DiagnosticShims* shims, + DiagnosticPidRequestType pid_request_type, uint32_t arbitration_id, + uint16_t pid, DiagnosticResponseReceived callback) { + DiagnosticRequest request = { + arbitration_id: arbitration_id, + mode: pid_request_type == DIAGNOSTIC_STANDARD_PID ? 0x1 : 0x22, + has_pid: true, + pid: pid + }; + + return diagnostic_request(shims, &request, callback); +} + +static bool handle_negative_response(IsoTpMessage* message, + DiagnosticResponse* response, DiagnosticShims* shims) { + bool response_was_negative = false; + if(response->mode == NEGATIVE_RESPONSE_MODE) { + response_was_negative = true; + if(message->size > NEGATIVE_RESPONSE_MODE_INDEX) { + response->mode = message->payload[NEGATIVE_RESPONSE_MODE_INDEX]; + } + + if(message->size > NEGATIVE_RESPONSE_NRC_INDEX) { + response->negative_response_code = + message->payload[NEGATIVE_RESPONSE_NRC_INDEX]; + } + + response->success = false; + response->completed = true; + } + return response_was_negative; +} + +static bool handle_positive_response(DiagnosticRequestHandle* handle, + IsoTpMessage* message, DiagnosticResponse* response, + DiagnosticShims* shims) { + bool response_was_positive = false; + if(response->mode == handle->request.mode + MODE_RESPONSE_OFFSET) { + response_was_positive = true; + // hide the "response" version of the mode from the user + // if it matched + response->mode = handle->request.mode; + response->has_pid = false; + if(handle->request.has_pid && message->size > 1) { + response->has_pid = true; + if(handle->request.pid_length == 2) { + response->pid = get_bitfield(message->payload, message->size, + PID_BYTE_INDEX * CHAR_BIT, sizeof(uint16_t) * CHAR_BIT); + } else { + response->pid = message->payload[PID_BYTE_INDEX]; + } + + } + + if((!handle->request.has_pid && !response->has_pid) + || response->pid == handle->request.pid) { + response->success = true; + response->completed = true; + + uint8_t payload_index = 1 + handle->request.pid_length; + response->payload_length = MAX(0, message->size - payload_index); + if(response->payload_length > 0) { + memcpy(response->payload, &message->payload[payload_index], + response->payload_length); + } + } else { + response_was_positive = false; + } + } + return response_was_positive; +} + +DiagnosticResponse diagnostic_receive_can_frame(DiagnosticShims* shims, + DiagnosticRequestHandle* handle, const uint32_t arbitration_id, + const uint8_t data[], const uint8_t size) { + + DiagnosticResponse response = { + arbitration_id: arbitration_id, + multi_frame: false, + success: false, + completed: false + }; + + if(!handle->isotp_send_handle.completed) { + isotp_continue_send(&handle->isotp_shims, + &handle->isotp_send_handle, arbitration_id, data, size); + } else { + uint8_t i; + for(i = 0; i < handle->isotp_receive_handle_count; ++i) { + IsoTpMessage message = isotp_continue_receive(&handle->isotp_shims, + &handle->isotp_receive_handles[i], arbitration_id, data, + size); + response.multi_frame = message.multi_frame; + + if(message.completed) { + if(message.size > 0) { + response.mode = message.payload[0]; + if(handle_negative_response(&message, &response, shims) || + handle_positive_response(handle, &message, + &response, shims)) { + if(shims->log != NULL) { + char response_string[128] = {0}; + diagnostic_response_to_string(&response, + response_string, sizeof(response_string)); + shims->log("Diagnostic response received: %s", + response_string); + } + + handle->success = true; + handle->completed = true; + } + } else { + if(shims->log != NULL) { + shims->log("Received an empty response on arb ID 0x%x", + response.arbitration_id); + } + } + + if(handle->completed && handle->callback != NULL) { + handle->callback(&response); + } + + break; + } + } + } + return response; +} + +int diagnostic_payload_to_integer(const DiagnosticResponse* response) { + return get_bitfield(response->payload, response->payload_length, 0, + response->payload_length * CHAR_BIT); +} + +float diagnostic_decode_obd2_pid(const DiagnosticResponse* response) { + // handles on the single number values, not the bit encoded ones + switch(response->pid) { + case 0xa: + return response->payload[0] * 3; + case 0xc: + return (response->payload[0] * 256 + response->payload[1]) / 4.0; + case 0xd: + case 0x33: + case 0xb: + return response->payload[0]; + case 0x10: + return (response->payload[0] * 256 + response->payload[1]) / 100.0; + case 0x11: + case 0x2f: + case 0x45: + case 0x4c: + case 0x52: + case 0x5a: + case 0x4: + return response->payload[0] * 100.0 / 255.0; + case 0x46: + case 0x5c: + case 0xf: + case 0x5: + return response->payload[0] - 40; + case 0x62: + return response->payload[0] - 125; + default: + return diagnostic_payload_to_integer(response); + } +} + +void diagnostic_response_to_string(const DiagnosticResponse* response, + char* destination, size_t destination_length) { + int bytes_used = snprintf(destination, destination_length, + "arb_id: 0x%lx, mode: 0x%x, ", + (unsigned long) response->arbitration_id, + response->mode); + + if(response->has_pid) { + bytes_used += snprintf(destination + bytes_used, + destination_length - bytes_used, + "pid: 0x%x, ", + response->pid); + } + + if(!response->success) { + bytes_used += snprintf(destination + bytes_used, + destination_length - bytes_used, + "nrc: 0x%x, ", + response->negative_response_code); + } + + if(response->payload_length > 0) { + snprintf(destination + bytes_used, destination_length - bytes_used, + "payload: 0x%02x%02x%02x%02x%02x%02x%02x", + response->payload[0], + response->payload[1], + response->payload[2], + response->payload[3], + response->payload[4], + response->payload[5], + response->payload[6]); + } else { + snprintf(destination + bytes_used, destination_length - bytes_used, + "no payload"); + } +} + +void diagnostic_request_to_string(const DiagnosticRequest* request, + char* destination, size_t destination_length) { + int bytes_used = snprintf(destination, destination_length, + "arb_id: 0x%lx, mode: 0x%x, ", + (unsigned long) request->arbitration_id, + request->mode); + + if(request->has_pid) { + bytes_used += snprintf(destination + bytes_used, + destination_length - bytes_used, + "pid: 0x%x, ", + request->pid); + } + + int remaining_space = destination_length - bytes_used; + if(request->payload_length > 0) { + snprintf(destination + bytes_used, remaining_space, + "payload: 0x%02x%02x%02x%02x%02x%02x%02x", + request->payload[0], + request->payload[1], + request->payload[2], + request->payload[3], + request->payload[4], + request->payload[5], + request->payload[6]); + } else { + snprintf(destination + bytes_used, remaining_space, "no payload"); + } +} + +bool diagnostic_request_equals(const DiagnosticRequest* ours, + const DiagnosticRequest* theirs) { + bool equals = ours->arbitration_id == theirs->arbitration_id && + ours->mode == theirs->mode; + equals &= ours->has_pid == theirs->has_pid; + equals &= ours->pid == theirs->pid; + return equals; +} diff --git a/libs/uds-c/src/uds/uds.h b/libs/uds-c/src/uds/uds.h new file mode 100644 index 00000000..43058342 --- /dev/null +++ b/libs/uds-c/src/uds/uds.h @@ -0,0 +1,165 @@ +#ifndef __UDS_H__ +#define __UDS_H__ + +#include +#include +#include + +#define OBD2_FUNCTIONAL_BROADCAST_ID 0x7df +#define OBD2_FUNCTIONAL_RESPONSE_START 0x7e8 +#define OBD2_FUNCTIONAL_RESPONSE_COUNT 8 + +#ifdef __cplusplus +extern "C" { +#endif + +/* Public: Initialize an DiagnosticShims with the given callback functions. + * + * If any callbacks are not to be used, set them to NULL. For documentation of + * the function type signatures, see higher up in this header file. This struct + * is a handy encapsulation used to pass the shims around to the various + * diagnostic_* functions. + * + * Returns a struct with the fields initailized to the callbacks. + */ +DiagnosticShims diagnostic_init_shims(LogShim log, + SendCanMessageShim send_can_message, + SetTimerShim set_timer); + +/* Public: Generate a new diagnostic request, send the first CAN message frame + * and set up the handle required to process the response via + * diagnostic_receive_can_frame(...). + * + * shims - Low-level shims required to send CAN messages, etc. + * request - + * callback - an optional function to be called when the response is receved + * (use NULL if no callback is required). + * + * Returns a handle to be used with diagnostic_receive_can_frame to complete + * sending the request and receive the response. The 'completed' field in the + * returned DiagnosticRequestHandle will be true when the message is completely + * sent. The first frame of the message will already be sent. + */ +DiagnosticRequestHandle diagnostic_request(DiagnosticShims* shims, + DiagnosticRequest* request, DiagnosticResponseReceived callback); + +/* Public: Generate the handle for a new diagnostic request, but do not send any + * data to CAN yet - you must call start_diagnostic_request(...) on the handle + * returned from this function actually kick off the request. + * + * shims - Low-level shims required to send CAN messages, etc. + * request - + * callback - an optional function to be called when the response is receved + * (use NULL if no callback is required). + * + * Returns a handle to be used with start_diagnostic_request and then + * diagnostic_receive_can_frame to complete sending the request and receive the + * response. The 'completed' field in the returned DiagnosticRequestHandle will + * be true when the message is completely sent. + */ +DiagnosticRequestHandle generate_diagnostic_request(DiagnosticShims* shims, + DiagnosticRequest* request, DiagnosticResponseReceived callback); + +/* Public: Send the first frame of the request to CAN for the handle, generated + * by generate_diagnostic_request. + * + * You can also call this method to re-do the request for a handle that has + * already completed. + */ +void start_diagnostic_request(DiagnosticShims* shims, + DiagnosticRequestHandle* handle); + +/* Public: Request a PID from the given arbitration ID, determining the mode + * automatically based on the PID type. + * + * shims - Low-level shims required to send CAN messages, etc. + * pid_request_type - either DIAGNOSTIC_STANDARD_PID (will use mode 0x1 and 1 + * byte PIDs) or DIAGNOSTIC_ENHANCED_PID (will use mode 0x22 and 2 byte + * PIDs) + * arbitration_id - The arbitration ID to send the request to. + * pid - The PID to request from the other node. + * callback - an optional function to be called when the response is receved + * (use NULL if no callback is required). + * + * Returns a handle to be used with diagnostic_receive_can_frame to complete + * sending the request and receive the response. The 'completed' field in the + * returned DiagnosticRequestHandle will be true when the message is completely + * sent. + */ +DiagnosticRequestHandle diagnostic_request_pid(DiagnosticShims* shims, + DiagnosticPidRequestType pid_request_type, uint32_t arbitration_id, + uint16_t pid, DiagnosticResponseReceived callback); + +/* Public: Continue to send and receive a single diagnostic request, based on a + * freshly received CAN message. + * + * shims - Low-level shims required to send CAN messages, etc. + * handle - A DiagnosticRequestHandle previously returned by one of the + * diagnostic_request*(..) functions. + * arbitration_id - The arbitration_id of the received CAN message. + * data - The data of the received CAN message. + * size - The size of the data in the received CAN message. + * + * Returns true if the request was completed and response received, or the + * request was otherwise cancelled. Check the 'success' field of the handle to + * see if it was successful. + */ +DiagnosticResponse diagnostic_receive_can_frame(DiagnosticShims* shims, + DiagnosticRequestHandle* handle, + const uint32_t arbitration_id, const uint8_t data[], + const uint8_t size); + +/* Public: Parse the entier payload of the reponse as a single integer. + * + * response - the received DiagnosticResponse. + */ +int diagnostic_payload_to_integer(const DiagnosticResponse* response); + +/* Public: Render a DiagnosticResponse as a string into the given buffer. + * + * response - the response to convert to a string, for debug logging. + * destination - the target string buffer. + * destination_length - the size of the destination buffer, i.e. the max size + * for the rendered string. + */ +void diagnostic_response_to_string(const DiagnosticResponse* response, + char* destination, size_t destination_length); + +/* Public: Render a DiagnosticRequest as a string into the given buffer. + * + * request - the request to convert to a string, for debug logging. + * destination - the target string buffer. + * destination_length - the size of the destination buffer, i.e. the max size + * for the rendered string. + */ +void diagnostic_request_to_string(const DiagnosticRequest* request, + char* destination, size_t destination_length); + +/* Public: For many OBD-II PIDs with a numerical result, translate a diagnostic + * response payload into a meaningful number using the standard formulas. + * + * Functions pulled from http://en.wikipedia.org/wiki/OBD-II_PIDs#Mode_01 + * + * Returns the translated value or 0 if the PID is not in the OBD-II standard or + * does not use a numerical value (e.g. VIN). + */ +float diagnostic_decode_obd2_pid(const DiagnosticResponse* response); + +/* Public: Returns true if the "fingerprint" of the two diagnostic messages + * matches - the arbitration_id, mode and pid (or lack of pid). + */ +bool diagnostic_request_equals(const DiagnosticRequest* ours, + const DiagnosticRequest* theirs); + +/* Public: Returns true if the request has been completely sent - if false, make + * sure you called start_diagnostic_request once to start it, and then pass + * incoming CAN messages to it with diagnostic_receive_can_frame(...) so it can + * continue the ISO-TP transfer. + */ +bool diagnostic_request_sent(DiagnosticRequestHandle* handle); + +#ifdef __cplusplus +} +#endif + +#endif // __UDS_H__ diff --git a/libs/uds-c/src/uds/uds_types.h b/libs/uds-c/src/uds/uds_types.h new file mode 100644 index 00000000..4ebc150c --- /dev/null +++ b/libs/uds-c/src/uds/uds_types.h @@ -0,0 +1,200 @@ +#ifndef __UDS_TYPES_H__ +#define __UDS_TYPES_H__ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// TODO This still doesn't have enough space for the largest possible +// multiframe response. May need to dynamically allocate in the future. +#define MAX_UDS_RESPONSE_PAYLOAD_LENGTH 127 +#define MAX_UDS_REQUEST_PAYLOAD_LENGTH 7 +#define MAX_RESPONDING_ECU_COUNT 8 +#define VIN_LENGTH 17 + +/* Private: The four main types of diagnositc requests that determine how the + * request should be parsed and what type of callback should be used. + * + * TODO this may not be used...yet? + */ +typedef enum { + DIAGNOSTIC_REQUEST_TYPE_PID, + DIAGNOSTIC_REQUEST_TYPE_DTC, + DIAGNOSTIC_REQUEST_TYPE_MIL_STATUS, + DIAGNOSTIC_REQUEST_TYPE_VIN +} DiagnosticRequestType; + +/* Public: A container for a single diagnostic request. + * + * The only required fields are the arbitration_id and mode. + * + * arbitration_id - The arbitration ID to send the request. + * mode - The OBD-II mode for the request. + * has_pid - (optional) If the requests uses a PID, this should be true. + * pid - (optional) The PID to request, if the mode requires one. has_pid must + * be true. + * pid_length - The length of the PID field, either 1 (standard) or 2 bytes + * (extended). If 0, it will be set automatically based on the request + * mode. + * payload - (optional) The payload for the request, if the request requires + * one. If payload_length is 0 this field is ignored. + * payload_length - The length of the payload, or 0 if no payload is used. + * no_frame_padding - false if sent CAN payloads should *not* be padded out to a + * full 8 byte CAN frame. Many ECUs require this, but others require the + * size of the CAN message to only be the actual data. By default padding + * is enabled (so this struct value can default to 0). + * type - the type of the request (TODO unused) + */ +typedef struct { + uint32_t arbitration_id; + uint8_t mode; + bool has_pid; + uint16_t pid; + uint8_t pid_length; + uint8_t payload[MAX_UDS_REQUEST_PAYLOAD_LENGTH]; + uint8_t payload_length; + bool no_frame_padding; + DiagnosticRequestType type; +} DiagnosticRequest; + +/* Public: All possible negative response codes that could be received from a + * requested node. + * + * When a DiagnosticResponse is received and the 'completed' field is true, but + * the 'success' field is false, the 'negative_response_code' field will contain + * one of these values as reported by the requested node. + * + * Thanks to canbushack.com for the list of NRCs. + */ +typedef enum { + NRC_SUCCESS = 0x0, + NRC_SERVICE_NOT_SUPPORTED = 0x11, + NRC_SUB_FUNCTION_NOT_SUPPORTED = 0x12, + NRC_INCORRECT_LENGTH_OR_FORMAT = 0x13, + NRC_CONDITIONS_NOT_CORRECT = 0x22, + NRC_REQUEST_OUT_OF_RANGE = 0x31, + NRC_SECURITY_ACCESS_DENIED = 0x33, + NRC_INVALID_KEY = 0x35, + NRC_TOO_MANY_ATTEMPS = 0x36, + NRC_TIME_DELAY_NOT_EXPIRED = 0x37, + NRC_RESPONSE_PENDING = 0x78 +} DiagnosticNegativeResponseCode; + +/* Public: A partially or fully completed response to a diagnostic request. + * + * completed - True if the request is complete - some functions return a + * DiagnosticResponse even when it's only partially completed, so be sure + * to check this field. + * success - True if the request was successful. The value if this + * field isn't valid if 'completed' isn't true. If this is 'false', check + * the negative_response_code field for the reason. + * arbitration_id - The arbitration ID the response was received on. + * multi_frame - True if this response (whether completed or not) required + * multi-frame CAN support. Can be used for updating time-out functions. + * mode - The OBD-II mode for the original request. + * has_pid - If this is a response to a PID request, this will be true and the + * 'pid' field will be valid. + * pid - If the request was for a PID, this is the PID echo. Only valid if + * 'has_pid' is true. + * negative_response_code - If the request was not successful, 'success' will be + * false and this will be set to a DiagnosticNegativeResponseCode returned + * by the other node. + * payload - An optional payload for the response - NULL if no payload. + * payload_length - The length of the payload or 0 if none. + */ +typedef struct { + bool completed; + bool success; + bool multi_frame; + uint32_t arbitration_id; + uint8_t mode; + bool has_pid; + uint16_t pid; + DiagnosticNegativeResponseCode negative_response_code; + uint8_t payload[MAX_UDS_RESPONSE_PAYLOAD_LENGTH]; + uint8_t payload_length; +} DiagnosticResponse; + +/* Public: Friendly names for all OBD-II modes. + */ +typedef enum { + OBD2_MODE_POWERTRAIN_DIAGNOSTIC_REQUEST = 0x1, + OBD2_MODE_POWERTRAIN_FREEZE_FRAME_REQUEST = 0x2, + OBD2_MODE_EMISSIONS_DTC_REQUEST = 0x3, + OBD2_MODE_EMISSIONS_DTC_CLEAR = 0x4, + // 0x5 is for non-CAN only + // OBD2_MODE_OXYGEN_SENSOR_TEST = 0x5, + OBD2_MODE_TEST_RESULTS = 0x6, + OBD2_MODE_DRIVE_CYCLE_DTC_REQUEST = 0x7, + OBD2_MODE_CONTROL = 0x8, + OBD2_MODE_VEHICLE_INFORMATION = 0x9, + OBD2_MODE_PERMANENT_DTC_REQUEST = 0xa, + // this one isn't technically in uds, but both of the enhanced standards + // have their PID requests at 0x22 + OBD2_MODE_ENHANCED_DIAGNOSTIC_REQUEST = 0x22 +} DiagnosticMode; + +/* Public: The signature for an optional function to be called when a diagnostic + * request is complete, and a response is received or there is a fatal error. + * + * response - the completed DiagnosticResponse. + */ +typedef void (*DiagnosticResponseReceived)(const DiagnosticResponse* response); + +/* Public: A handle for initiating and continuing a single diagnostic request. + * + * A diagnostic request requires one or more CAN messages to be sent, and one + * or more CAN messages to be received before it is completed. This struct + * encapsulates the local state required to track the request while it is in + * progress. + * + * request - The original DiagnosticRequest that this handle was created for. + * completed - True if the request was completed successfully, or was otherwise + * cancelled. + * success - True if the request send and receive process was successful. The + * value if this field isn't valid if 'completed' isn't true. + */ +typedef struct { + DiagnosticRequest request; + bool success; + bool completed; + + // Private + IsoTpShims isotp_shims; + IsoTpSendHandle isotp_send_handle; + IsoTpReceiveHandle isotp_receive_handles[MAX_RESPONDING_ECU_COUNT]; + uint8_t isotp_receive_handle_count; + DiagnosticResponseReceived callback; + // DiagnosticMilStatusReceived mil_status_callback; + // DiagnosticVinReceived vin_callback; +} DiagnosticRequestHandle; + +/* Public: The two major types of PIDs that determine the OBD-II mode and PID + * field length. + */ +typedef enum { + DIAGNOSTIC_STANDARD_PID, + DIAGNOSTIC_ENHANCED_PID +} DiagnosticPidRequestType; + +/* Public: A container for the 3 shim functions used by the library to interact + * with the wider system. + * + * Use the diagnostic_init_shims(...) function to create an instance of this + * struct. + */ +typedef struct { + LogShim log; + SendCanMessageShim send_can_message; + SetTimerShim set_timer; +} DiagnosticShims; + +#ifdef __cplusplus +} +#endif + +#endif // __UDS_TYPES_H__ diff --git a/libs/uds-c/tests/common.c b/libs/uds-c/tests/common.c new file mode 100644 index 00000000..fd1e4b2c --- /dev/null +++ b/libs/uds-c/tests/common.c @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +#include + +DiagnosticShims SHIMS; + +uint32_t last_can_frame_sent_arb_id; +uint8_t last_can_payload_sent[8]; +uint8_t last_can_payload_size; +bool can_frame_was_sent; + +DiagnosticResponse last_response_received; +bool last_response_was_received; + +void debug(const char* format, ...) { + va_list args; + va_start(args, format); + vprintf(format, args); + printf("\r\n"); + va_end(args); +} + +bool mock_send_can(const uint32_t arbitration_id, const uint8_t* data, + const uint8_t size) { + can_frame_was_sent = true; + last_can_frame_sent_arb_id = arbitration_id; + last_can_payload_size = size; + if(size > 0) { + memcpy(last_can_payload_sent, data, size); + } + return true; +} + +void setup() { + SHIMS = diagnostic_init_shims(debug, mock_send_can, NULL); + memset(last_can_payload_sent, 0, sizeof(last_can_payload_sent)); + can_frame_was_sent = false; + last_response_was_received = false; +} + diff --git a/libs/uds-c/tests/test_core.c b/libs/uds-c/tests/test_core.c new file mode 100644 index 00000000..81200cca --- /dev/null +++ b/libs/uds-c/tests/test_core.c @@ -0,0 +1,526 @@ +#include +#include +#include +#include +#include + +extern bool can_frame_was_sent; +extern void setup(); +extern bool last_response_was_received; +extern DiagnosticResponse last_response_received; +extern DiagnosticShims SHIMS; +extern uint16_t last_can_frame_sent_arb_id; +extern uint8_t last_can_payload_sent[8]; +extern uint8_t last_can_payload_size; + +void response_received_handler(const DiagnosticResponse* response) { + last_response_was_received = true; + last_response_received = *response; +} + +START_TEST (test_receive_wrong_arb_id) +{ + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: OBD2_MODE_POWERTRAIN_DIAGNOSTIC_REQUEST + }; + DiagnosticRequestHandle handle = diagnostic_request(&SHIMS, &request, + response_received_handler); + + fail_if(last_response_was_received); + const uint8_t can_data[] = {0x2, request.mode + 0x40, 0x23}; + diagnostic_receive_can_frame(&SHIMS, &handle, request.arbitration_id, + can_data, sizeof(can_data)); + fail_if(last_response_was_received); +} +END_TEST + +START_TEST (test_send_diag_request_with_payload) +{ + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: OBD2_MODE_POWERTRAIN_DIAGNOSTIC_REQUEST, + payload: {0x12, 0x34}, + payload_length: 2, + no_frame_padding: true + }; + DiagnosticRequestHandle handle = diagnostic_request(&SHIMS, &request, + response_received_handler); + + fail_if(handle.completed); + // TODO it'd be better to check the ISO-TP message instead of the CAN frame, + // but we don't have a good way to do that + ck_assert_int_eq(last_can_frame_sent_arb_id, request.arbitration_id); + ck_assert_int_eq(last_can_payload_sent[1], request.mode); + ck_assert_int_eq(last_can_payload_size, 4); + ck_assert_int_eq(last_can_payload_sent[2], request.payload[0]); + ck_assert_int_eq(last_can_payload_sent[3], request.payload[1]); +} +END_TEST + +START_TEST (test_send_functional_request) +{ + DiagnosticRequest request = { + arbitration_id: OBD2_FUNCTIONAL_BROADCAST_ID, + mode: OBD2_MODE_EMISSIONS_DTC_REQUEST, + no_frame_padding: true + }; + DiagnosticRequestHandle handle = diagnostic_request(&SHIMS, &request, + response_received_handler); + + fail_if(handle.completed); + ck_assert_int_eq(last_can_frame_sent_arb_id, request.arbitration_id); + ck_assert_int_eq(last_can_payload_sent[1], request.mode); + ck_assert_int_eq(last_can_payload_size, 2); + + fail_if(last_response_was_received); + const uint8_t can_data[] = {0x2, request.mode + 0x40, 0x23}; + for(uint16_t filter = OBD2_FUNCTIONAL_RESPONSE_START; filter < + OBD2_FUNCTIONAL_RESPONSE_START + OBD2_FUNCTIONAL_RESPONSE_COUNT; + filter++) { + DiagnosticResponse response = diagnostic_receive_can_frame(&SHIMS, + &handle, filter, can_data, sizeof(can_data)); + fail_unless(response.success); + fail_unless(response.completed); + fail_unless(handle.completed); + ck_assert(last_response_received.success); + ck_assert_int_eq(last_response_received.arbitration_id, + filter); + ck_assert_int_eq(last_response_received.mode, request.mode); + fail_if(last_response_received.has_pid); + ck_assert_int_eq(last_response_received.payload_length, 1); + ck_assert_int_eq(last_response_received.payload[0], can_data[2]); + } +} +END_TEST + +START_TEST (test_sent_message_no_padding) +{ + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: OBD2_MODE_EMISSIONS_DTC_REQUEST, + no_frame_padding: true + }; + DiagnosticRequestHandle handle = diagnostic_request(&SHIMS, &request, + response_received_handler); + + fail_if(handle.completed); + ck_assert_int_eq(last_can_frame_sent_arb_id, request.arbitration_id); + ck_assert_int_eq(last_can_payload_size, 2); +} +END_TEST + +START_TEST (test_sent_message_is_padded_by_default) +{ + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: OBD2_MODE_EMISSIONS_DTC_REQUEST + }; + DiagnosticRequestHandle handle = diagnostic_request(&SHIMS, &request, + response_received_handler); + + fail_if(handle.completed); + ck_assert_int_eq(last_can_frame_sent_arb_id, request.arbitration_id); + ck_assert_int_eq(last_can_payload_size, 8); +} +END_TEST + +START_TEST (test_sent_message_is_padded) +{ + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: OBD2_MODE_EMISSIONS_DTC_REQUEST, + no_frame_padding: false + }; + DiagnosticRequestHandle handle = diagnostic_request(&SHIMS, &request, + response_received_handler); + + fail_if(handle.completed); + ck_assert_int_eq(last_can_frame_sent_arb_id, request.arbitration_id); + ck_assert_int_eq(last_can_payload_size, 8); +} +END_TEST + +START_TEST (test_send_diag_request) +{ + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: OBD2_MODE_EMISSIONS_DTC_REQUEST, + no_frame_padding: true + }; + DiagnosticRequestHandle handle = diagnostic_request(&SHIMS, &request, + response_received_handler); + + fail_if(handle.completed); + fail_unless(can_frame_was_sent); + ck_assert_int_eq(last_can_frame_sent_arb_id, request.arbitration_id); + ck_assert_int_eq(last_can_payload_sent[1], request.mode); + ck_assert_int_eq(last_can_payload_size, 2); + + fail_if(last_response_was_received); + const uint8_t can_data[] = {0x2, request.mode + 0x40, 0x23}; + DiagnosticResponse response = diagnostic_receive_can_frame(&SHIMS, &handle, + request.arbitration_id + 0x8, can_data, sizeof(can_data)); + fail_unless(response.success); + fail_unless(response.completed); + fail_unless(handle.completed); + ck_assert(last_response_received.success); + ck_assert_int_eq(last_response_received.arbitration_id, + request.arbitration_id + 0x8); + ck_assert_int_eq(last_response_received.mode, request.mode); + fail_if(last_response_received.has_pid); + ck_assert_int_eq(last_response_received.payload_length, 1); + ck_assert_int_eq(last_response_received.payload[0], can_data[2]); +} +END_TEST + +START_TEST (test_generate_then_send_request) +{ + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: OBD2_MODE_EMISSIONS_DTC_REQUEST, + no_frame_padding: true + }; + DiagnosticRequestHandle handle = generate_diagnostic_request(&SHIMS, + &request, response_received_handler); + + fail_if(handle.completed); + fail_if(can_frame_was_sent); + + start_diagnostic_request(&SHIMS, &handle); + fail_unless(can_frame_was_sent); + ck_assert_int_eq(last_can_frame_sent_arb_id, request.arbitration_id); + ck_assert_int_eq(last_can_payload_sent[1], request.mode); + ck_assert_int_eq(last_can_payload_size, 2); + + fail_if(last_response_was_received); + const uint8_t can_data[] = {0x2, request.mode + 0x40, 0x23}; + DiagnosticResponse response = diagnostic_receive_can_frame(&SHIMS, &handle, + request.arbitration_id + 0x8, can_data, sizeof(can_data)); + fail_unless(response.success); + fail_unless(response.completed); + fail_unless(handle.completed); + ck_assert(last_response_received.success); + ck_assert_int_eq(last_response_received.arbitration_id, + request.arbitration_id + 0x8); + ck_assert_int_eq(last_response_received.mode, request.mode); + fail_if(last_response_received.has_pid); + ck_assert_int_eq(last_response_received.payload_length, 1); + ck_assert_int_eq(last_response_received.payload[0], can_data[2]); +} +END_TEST + +START_TEST (test_generate_diag_request) +{ + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: OBD2_MODE_EMISSIONS_DTC_REQUEST, + no_frame_padding: true + }; + DiagnosticRequestHandle handle = generate_diagnostic_request(&SHIMS, + &request, response_received_handler); + + fail_if(handle.completed); + fail_if(can_frame_was_sent); +} +END_TEST + +START_TEST (test_autoset_pid_length) +{ + uint16_t arb_id = OBD2_MODE_POWERTRAIN_DIAGNOSTIC_REQUEST; + diagnostic_request_pid(&SHIMS, DIAGNOSTIC_STANDARD_PID, arb_id, 0x2, + response_received_handler); + + ck_assert_int_eq(last_can_frame_sent_arb_id, arb_id); + ck_assert_int_eq(last_can_payload_sent[1], 0x1); + ck_assert_int_eq(last_can_payload_sent[2], 0x2); + // padding is on for the diagnostic_request_pid helper function - if you + // need to turn it off, use the more manual diagnostic_request(...) + ck_assert_int_eq(last_can_payload_size, 8); + + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: 0x22, + has_pid: true, + pid: 0x1234, + no_frame_padding: true + }; + diagnostic_request(&SHIMS, &request, response_received_handler); + + ck_assert_int_eq(last_can_frame_sent_arb_id, request.arbitration_id); + ck_assert_int_eq(last_can_payload_sent[1], request.mode); + ck_assert_int_eq(last_can_payload_sent[2], (request.pid & 0xFF00) >> 8); + ck_assert_int_eq(last_can_payload_sent[3], request.pid & 0xFF); + ck_assert_int_eq(last_can_payload_size, 4); + + request.arbitration_id = 0x101; + request.pid = 0x12; + + diagnostic_request(&SHIMS, &request, response_received_handler); + + ck_assert_int_eq(last_can_frame_sent_arb_id, request.arbitration_id); + ck_assert_int_eq(last_can_payload_sent[1], request.mode); + ck_assert_int_eq(last_can_payload_sent[2], request.pid); + ck_assert_int_eq(last_can_payload_size, 3); +} +END_TEST + +START_TEST (test_request_pid_standard) +{ + uint16_t arb_id = OBD2_MODE_POWERTRAIN_DIAGNOSTIC_REQUEST; + DiagnosticRequestHandle handle = diagnostic_request_pid(&SHIMS, + DIAGNOSTIC_STANDARD_PID, arb_id, 0x2, response_received_handler); + + fail_if(last_response_was_received); + const uint8_t can_data[] = {0x3, 0x1 + 0x40, 0x2, 0x45}; + diagnostic_receive_can_frame(&SHIMS, &handle, arb_id + 0x8, + can_data, sizeof(can_data)); + fail_unless(last_response_was_received); + ck_assert(last_response_received.success); + ck_assert_int_eq(last_response_received.arbitration_id, + arb_id + 0x8); + ck_assert_int_eq(last_response_received.mode, 0x1); + fail_unless(last_response_received.has_pid); + ck_assert_int_eq(last_response_received.pid, 0x2); + ck_assert_int_eq(last_response_received.payload_length, 1); + ck_assert_int_eq(last_response_received.payload[0], can_data[3]); +} +END_TEST + +START_TEST (test_request_pid_enhanced) +{ + uint16_t arb_id = 0x100; + DiagnosticRequestHandle handle = diagnostic_request_pid(&SHIMS, + DIAGNOSTIC_ENHANCED_PID, arb_id, 0x1234, response_received_handler); + + fail_if(last_response_was_received); + const uint8_t can_data[] = {0x4, 0x22 + 0x40, 0x12, 0x34, 0x45}; + diagnostic_receive_can_frame(&SHIMS, &handle, arb_id + 0x8, can_data, + sizeof(can_data)); + fail_unless(last_response_was_received); + ck_assert(last_response_received.success); + ck_assert_int_eq(last_response_received.arbitration_id, + arb_id + 0x8); + ck_assert_int_eq(last_response_received.mode, 0x22); + fail_unless(last_response_received.has_pid); + ck_assert_int_eq(last_response_received.pid, 0x1234); + ck_assert_int_eq(last_response_received.payload_length, 1); + ck_assert_int_eq(last_response_received.payload[0], can_data[4]); +} +END_TEST + +START_TEST (test_wrong_mode_response) +{ + uint16_t arb_id = 0x100; + DiagnosticRequestHandle handle = diagnostic_request_pid(&SHIMS, + DIAGNOSTIC_ENHANCED_PID, arb_id, 0x1234, response_received_handler); + + fail_if(last_response_was_received); + const uint8_t can_data[] = {0x4, 0x1 + 0x40, 0x12, 0x34, 0x45}; + diagnostic_receive_can_frame(&SHIMS, &handle, arb_id + 0x8, can_data, + sizeof(can_data)); + fail_if(last_response_was_received); + fail_if(handle.completed); +} +END_TEST + +START_TEST (test_missing_pid) +{ + uint16_t arb_id = 0x100; + DiagnosticRequestHandle handle = diagnostic_request_pid(&SHIMS, + DIAGNOSTIC_ENHANCED_PID, arb_id, 0x1234, response_received_handler); + + fail_if(last_response_was_received); + const uint8_t can_data[] = {0x1, 0x22 + 0x40}; + diagnostic_receive_can_frame(&SHIMS, &handle, arb_id + 0x8, can_data, + sizeof(can_data)); + fail_if(last_response_was_received); + fail_if(handle.completed); +} +END_TEST + +START_TEST (test_wrong_pid_response) +{ + uint16_t arb_id = 0x100; + DiagnosticRequestHandle handle = diagnostic_request_pid(&SHIMS, + DIAGNOSTIC_ENHANCED_PID, arb_id, 0x1234, response_received_handler); + + fail_if(last_response_was_received); + const uint8_t can_data[] = {0x4, 0x22 + 0x40, 0x12, 0x33, 0x45}; + diagnostic_receive_can_frame(&SHIMS, &handle, arb_id + 0x8, can_data, + sizeof(can_data)); + fail_if(last_response_was_received); + fail_if(handle.completed); +} +END_TEST + +START_TEST (test_wrong_pid_then_right_completes) +{ + uint16_t arb_id = 0x100; + DiagnosticRequestHandle handle = diagnostic_request_pid(&SHIMS, + DIAGNOSTIC_ENHANCED_PID, arb_id, 0x1234, response_received_handler); + + fail_if(last_response_was_received); + uint8_t can_data[] = {0x4, 0x22 + 0x40, 0x12, 0x33, 0x45}; + diagnostic_receive_can_frame(&SHIMS, &handle, arb_id + 0x8, can_data, + sizeof(can_data)); + fail_if(last_response_was_received); + fail_if(handle.completed); + + can_data[3] = 0x34; + diagnostic_receive_can_frame(&SHIMS, &handle, arb_id + 0x8, can_data, + sizeof(can_data)); + fail_unless(last_response_was_received); + fail_unless(handle.completed); + fail_unless(handle.success); + fail_unless(last_response_received.success); + ck_assert_int_eq(last_response_received.pid, 0x1234); +} +END_TEST + +START_TEST (test_negative_response) +{ + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: OBD2_MODE_POWERTRAIN_DIAGNOSTIC_REQUEST + }; + DiagnosticRequestHandle handle = diagnostic_request(&SHIMS, &request, + response_received_handler); + const uint8_t can_data[] = {0x3, 0x7f, request.mode, + NRC_SERVICE_NOT_SUPPORTED}; + DiagnosticResponse response = diagnostic_receive_can_frame(&SHIMS, &handle, + request.arbitration_id + 0x8, can_data, sizeof(can_data)); + fail_unless(response.completed); + fail_if(response.success); + fail_unless(handle.completed); + + fail_if(last_response_received.success); + ck_assert_int_eq(last_response_received.arbitration_id, + request.arbitration_id + 0x8); + ck_assert_int_eq(last_response_received.mode, request.mode); + ck_assert_int_eq(last_response_received.pid, 0); + ck_assert_int_eq(last_response_received.negative_response_code, + NRC_SERVICE_NOT_SUPPORTED); + ck_assert_int_eq(last_response_received.payload_length, 0); +} +END_TEST + +START_TEST (test_payload_to_integer) +{ + uint16_t arb_id = OBD2_MODE_POWERTRAIN_DIAGNOSTIC_REQUEST; + DiagnosticRequestHandle handle = diagnostic_request_pid(&SHIMS, + DIAGNOSTIC_STANDARD_PID, arb_id, 0x2, response_received_handler); + + fail_if(last_response_was_received); + const uint8_t can_data[] = {0x4, 0x1 + 0x40, 0x2, 0x45, 0x12}; + DiagnosticResponse response = diagnostic_receive_can_frame(&SHIMS, &handle, + arb_id + 0x8, can_data, sizeof(can_data)); + ck_assert_int_eq(diagnostic_payload_to_integer(&response), 0x4512); +} +END_TEST + +START_TEST (test_response_multi_frame) +{ + DiagnosticRequest request = { + arbitration_id: 0x100, + mode: OBD2_MODE_VEHICLE_INFORMATION, + has_pid: true, + pid: 0x2 + }; + DiagnosticRequestHandle handle = diagnostic_request(&SHIMS, &request, + response_received_handler); + + const uint8_t can_data[] = {0x10, 0x14, 0x9 + 0x40, 0x2, 0x1, 0x31, 0x46, 0x4d}; + DiagnosticResponse response = diagnostic_receive_can_frame(&SHIMS, &handle, + request.arbitration_id + 0x8, can_data, sizeof(can_data)); + + fail_unless(can_frame_was_sent); + fail_unless(!response.success); + fail_unless(!response.completed); + fail_unless(response.multi_frame); + ck_assert_int_eq(last_can_frame_sent_arb_id, request.arbitration_id); + ck_assert_int_eq(last_can_payload_sent[0], 0x30); + + const uint8_t can_data_1[] = {0x21, 0x43, 0x55, 0x39, 0x4a, 0x39, 0x34, 0x48}; + response = diagnostic_receive_can_frame(&SHIMS, &handle, + request.arbitration_id + 0x8, can_data_1, sizeof(can_data_1)); + fail_unless(!response.success); + fail_unless(!response.completed); + fail_unless(response.multi_frame); + + const uint8_t can_data_2[] = {0x22, 0x55, 0x41, 0x30, 0x34, 0x35, 0x32, 0x34}; + response = diagnostic_receive_can_frame(&SHIMS, &handle, + request.arbitration_id + 0x8, can_data_2, sizeof(can_data_2)); + fail_unless(response.success); + fail_unless(response.completed); + fail_unless(response.multi_frame); + ck_assert_int_eq(response.mode, OBD2_MODE_VEHICLE_INFORMATION); + ck_assert_int_eq(response.pid, 0x2); + ck_assert_int_eq(response.payload_length, 18); + ck_assert_int_eq(response.payload[0], 0x01); + ck_assert_int_eq(response.payload[1], 0x31); + ck_assert_int_eq(response.payload[2], 0x46); + ck_assert_int_eq(response.payload[3], 0x4d); + ck_assert_int_eq(response.payload[4], 0x43); + ck_assert_int_eq(response.payload[5], 0x55); + ck_assert_int_eq(response.payload[6], 0x39); + ck_assert_int_eq(response.payload[7], 0x4a); + ck_assert_int_eq(response.payload[8], 0x39); + ck_assert_int_eq(response.payload[9], 0x34); + ck_assert_int_eq(response.payload[10], 0x48); + ck_assert_int_eq(response.payload[11], 0x55); + ck_assert_int_eq(response.payload[12], 0x41); + ck_assert_int_eq(response.payload[13], 0x30); + ck_assert_int_eq(response.payload[14], 0x34); + ck_assert_int_eq(response.payload[15], 0x35); + ck_assert_int_eq(response.payload[16], 0x32); + ck_assert_int_eq(response.payload[17], 0x34); +} +END_TEST + +Suite* testSuite(void) { + Suite* s = suite_create("uds"); + TCase *tc_core = tcase_create("core"); + tcase_add_checked_fixture(tc_core, setup, NULL); + tcase_add_test(tc_core, test_sent_message_no_padding); + tcase_add_test(tc_core, test_sent_message_is_padded); + tcase_add_test(tc_core, test_sent_message_is_padded_by_default); + tcase_add_test(tc_core, test_generate_diag_request); + tcase_add_test(tc_core, test_generate_then_send_request); + tcase_add_test(tc_core, test_send_diag_request); + tcase_add_test(tc_core, test_send_functional_request); + tcase_add_test(tc_core, test_send_diag_request_with_payload); + tcase_add_test(tc_core, test_receive_wrong_arb_id); + tcase_add_test(tc_core, test_autoset_pid_length); + tcase_add_test(tc_core, test_request_pid_standard); + tcase_add_test(tc_core, test_request_pid_enhanced); + tcase_add_test(tc_core, test_wrong_mode_response); + tcase_add_test(tc_core, test_wrong_pid_response); + tcase_add_test(tc_core, test_missing_pid); + tcase_add_test(tc_core, test_wrong_pid_then_right_completes); + tcase_add_test(tc_core, test_negative_response); + tcase_add_test(tc_core, test_payload_to_integer); + tcase_add_test(tc_core, test_response_multi_frame); + + // TODO these are future work: + // TODO test request MIL + // TODO test request VIN + // TODO test request DTC + // TODO test clear DTC + // TODO test enumerate PIDs + suite_add_tcase(s, tc_core); + + return s; +} + +int main(void) { + int numberFailed; + Suite* s = testSuite(); + SRunner *sr = srunner_create(s); + // Don't fork so we can actually use gdb + srunner_set_fork_status(sr, CK_NOFORK); + srunner_run_all(sr, CK_NORMAL); + numberFailed = srunner_ntests_failed(sr); + srunner_free(sr); + return (numberFailed == 0) ? 0 : 1; +} -- cgit 1.2.3-korg